可能な使用シナリオ
特定のデータを強調表示したい場合、セルのスタイルを変更できます。
Excelのセルのフォーマットを変更する方法
Excelの単一のセルのフォーマットを変更するには、次の手順に従います。
-
Excelを開き、セルのフォーマットを変更したいワークブックを開きます。
-
フォーマットを変更したいセルを見つけます。
-
セルを右クリックして、コンテキストメニューから"セルの書式設定"を選択します。または、セルを選択し、Excelリボンのホームタブに移動し、“セル"グループの"書式"ドロップダウンをクリックし、「セルの書式設定」を選択することもできます。
-
「セルの書式設定」ダイアログボックスが表示されます。ここでは、選択したセルに適用するさまざまな書式オプションを選択できます。たとえば、フォントスタイル、フォントサイズ、フォントの色、数値形式、罫線、背景色などを変更できます。ダイアログボックスのさまざまなタブを探索して、さまざまな書式オプションにアクセスできます。
-
所望の書式設定変更を行った後、「OK」ボタンをクリックして、選択したセルに書式を適用します。
C#を使用してセルのフォーマットを変更する方法
Aspose.Cellsを使用してセルのフォーマットを変更するには、次のメソッドを使用できます。
- Cell.SetStyle(Style style)
- Cell.SetStyle(Style style, bool explicitFlag)
- Cell.SetStyle(Style style, StyleFlag flag)
サンプルコード
この例では、Excelワークブックを作成し、いくつかのサンプルデータを追加し、最初のワークシートにアクセスし、2つのセル(“A2"および"B3”)を取得します。次に、セルのスタイルを取得し、さまざまな書式オプション(たとえば、フォントの色、太字)を設定し、セルの形式を変更します。最後に、作業ブックを新しいファイルに保存します。
// Create the workbook | |
Workbook workbook = new Workbook(); | |
//Get the first worksheet | |
Worksheet ws = workbook.Worksheets[0]; | |
Aspose.Cells.Cells cells = ws.Cells; | |
//Setting the value to the cells | |
Aspose.Cells.Cell cell = cells["A1"]; | |
cell.PutValue("Fruit"); | |
cell = cells["B1"]; | |
cell.PutValue("Count"); | |
cell = cells["C1"]; | |
cell.PutValue("Price"); | |
cell = cells["A2"]; | |
cell.PutValue("Apple"); | |
cell = cells["A3"]; | |
cell.PutValue("Mango"); | |
cell = cells["A4"]; | |
cell.PutValue("Blackberry"); | |
cell = cells["A5"]; | |
cell.PutValue("Cherry"); | |
cell = cells["B2"]; | |
cell.PutValue(5); | |
cell = cells["B3"]; | |
cell.PutValue(3); | |
cell = cells["B4"]; | |
cell.PutValue(6); | |
cell = cells["B5"]; | |
cell.PutValue(4); | |
cell = cells["C2"]; | |
cell.PutValue(5); | |
cell = cells["C3"]; | |
cell.PutValue(20); | |
cell = cells["C4"]; | |
cell.PutValue(30); | |
cell = cells["C5"]; | |
cell.PutValue(60); | |
// Access the worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
Cell a2 = worksheet.Cells["A2"]; | |
// Get style of A2 | |
Style style = a2.GetStyle(); | |
// Change the format | |
style.Font.Color = Color.Red; | |
style.Font.IsBold = true; | |
StyleFlag flag = new StyleFlag(); | |
flag.FontColor = true; | |
a2.SetStyle(style, flag); | |
Cell b3 = worksheet.Cells["B3"]; | |
// Get style of B3 | |
Style style2 = b3.GetStyle(); | |
// Change the format | |
style2.Font.Color = Color.Blue; | |
style2.Font.IsItalic = true; | |
b3.SetStyle(style2); | |
// Save the modified workbook | |
workbook.Save("output.xlsx"); |