C# 使用 Excel 作成

This article was translated from English: Does it need improvement?
Translated
View the article in English

エクセルスプレッドシートファイルをプログラムで作成することは、C#開発者にとって一般的なタスクです。今日は、新しいエクセルファイルの作成、セルスタイルの設定、およびC#プログラミングでのデータ挿入について学びます。 適切なコードを使用すれば、ニーズに合わせたシートのカスタマイズやスタイリングが完全に可能です。 以下は、.NETプロジェクトでC#のExcelワークブックを作成する方法のステップバイステップガイドです。


ステップ 1

1. IronXLでC# Excel スプレッドシートを作成する

今日は、Excelファイルの操作をより効率的にするためのC#ライブラリであるIronXLを使用します。 開発プロジェクトには無料で利用できます。 インストールしてチュートリアルに従ってください。

プロジェクトにダウンロード またはフォロー Visual Studio にインストールするための NuGet.

Install-Package IronXL.Excel

チュートリアルの方法

2. C# で Excel ワークブックを作成する

私たちのプロジェクトにIronXLをインストールしたら、Excelワークブックを作成できます。 Workbook.Createを使用()IronXLの関数

WorkBook wb = WorkBook.Create();
WorkBook wb = WorkBook.Create();
Dim wb As WorkBook = WorkBook.Create()
VB   C#

それは新しいExcel WorkBook wbを作成します。 XL WorkBookのタイプを指定できます ( .xlsx または xls ) 次の引数として ExcelFileFormat を使用して WorkBook.Create()以下のように機能します:

/**
Create Csharp WorkBook 
anchor-c-num-create-excel-workbook
**/
//for creating .xlsx extension file
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
//for creating .xls extension file
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
/**
Create Csharp WorkBook 
anchor-c-num-create-excel-workbook
**/
//for creating .xlsx extension file
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
//for creating .xls extension file
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
'''
'''Create Csharp WorkBook 
'''anchor-c-num-create-excel-workbook
'''*
'for creating .xlsx extension file
Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
'for creating .xls extension file
Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
VB   C#

さて、wbを使用してワークシートを作成できます。


3. C# でExcelスプレッドシートを作成する

ワークシートを作成するために、IronXLは Workbook.CreateWorkSheet メソッドを提供しています。()` 関数。 この関数は文字列パラメータを必要とし、そこでワークシートの名前を指定できます。

WorkSheet ws = wb.CreateWorkSheet("SheetName");
WorkSheet ws = wb.CreateWorkSheet("SheetName");
Dim ws As WorkSheet = wb.CreateWorkSheet("SheetName")
VB   C#

wb はワークブックです。 (上記参照) そして ws は新しく作成されたワークシートです。 同様に、必要に応じていくつでもWorkSheetsを作成できます。 例えば:

/**
Create Csharp WorkSheets 
anchor-c-num-create-excel-workbook
**/
WorkSheet ws1 = wb.CreateWorkSheet("Sheet1");
WorkSheet ws2 = wb.CreateWorkSheet("Sheet2");
/**
Create Csharp WorkSheets 
anchor-c-num-create-excel-workbook
**/
WorkSheet ws1 = wb.CreateWorkSheet("Sheet1");
WorkSheet ws2 = wb.CreateWorkSheet("Sheet2");
'''
'''Create Csharp WorkSheets 
'''anchor-c-num-create-excel-workbook
'''*
Dim ws1 As WorkSheet = wb.CreateWorkSheet("Sheet1")
Dim ws2 As WorkSheet = wb.CreateWorkSheet("Sheet2")
VB   C#

セルデータの挿入

では、指定されたワークシートにデータを挿入できます。 Excelのセルアドレッシングシステムを使用します:

/**
Insert Data in Cell Address
anchor-insert-cell-data
**/
WorkSheet ["CellAddress"].Value = "Value";
/**
Insert Data in Cell Address
anchor-insert-cell-data
**/
WorkSheet ["CellAddress"].Value = "Value";
'''
'''Insert Data in Cell Address
'''anchor-insert-cell-data
'''*
WorkSheet ("CellAddress").Value = "Value"
VB   C#

5. 範囲にデータを挿入

この方法論により、必要なだけ多くのセルに値を挿入することも可能です。 Rangeを使用して、複数のセルにデータを挿入することができます。

/**
Insert Data in Range
anchor-insert-data-in-range
**/
WorkSheet ["From Cell Address : To Cell Address"].Value="value";
/**
Insert Data in Range
anchor-insert-data-in-range
**/
WorkSheet ["From Cell Address : To Cell Address"].Value="value";
'''
'''Insert Data in Range
'''anchor-insert-data-in-range
'''*
WorkSheet ("From Cell Address : To Cell Address").Value="value"
VB   C#

これは、指定された範囲内のすべてのセルに value を挿入します。 詳しくは、 C# エクセル範囲 あなたの .NET プロジェクトで使用するために。


6. Excelファイルを保存する

データを挿入した後、指定されたパスにExcelファイルを保存する必要があります。

/**
Save Excel File
anchor-save-excel-file
**/
WorkBook.SaveAs("Path + Filename");
/**
Save Excel File
anchor-save-excel-file
**/
WorkBook.SaveAs("Path + Filename");
'''
'''Save Excel File
'''anchor-save-excel-file
'''*
WorkBook.SaveAs("Path + Filename")
VB   C#

上記の一行のコードによって、新しく作成されたExcel WorkBookが指定された場所に保存されます。 さらに詳しく見る C# で Excel スプレッドシートを作成する例.


データの作成、挿入、および保存の例

/**
Complete Example
anchor-create-insert-data-and-save-example
**/
using IronXL;
static void Main(string [] args)
{
    //Create new XL WorkBook
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    //Create worksheet of specified WorkBook
    WorkSheet ws = wb.CreateWorkSheet("Sheet1");
    //insert data by cell addressing
    ws ["A1"].Value = "Welcome";
    ws ["A2"].Value = "To";
    ws ["A3"].Value = "IronXL";
    //insert data by range
    ws ["C3:C8"].Value = "Cell Value";
    //save the file in specified path
    wb.SaveAs("sample.xlsx");
    Console.WriteLine("successfully created.");
    Console.ReadKey();    
}
/**
Complete Example
anchor-create-insert-data-and-save-example
**/
using IronXL;
static void Main(string [] args)
{
    //Create new XL WorkBook
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    //Create worksheet of specified WorkBook
    WorkSheet ws = wb.CreateWorkSheet("Sheet1");
    //insert data by cell addressing
    ws ["A1"].Value = "Welcome";
    ws ["A2"].Value = "To";
    ws ["A3"].Value = "IronXL";
    //insert data by range
    ws ["C3:C8"].Value = "Cell Value";
    //save the file in specified path
    wb.SaveAs("sample.xlsx");
    Console.WriteLine("successfully created.");
    Console.ReadKey();    
}
'''
'''Complete Example
'''anchor-create-insert-data-and-save-example
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	'Create new XL WorkBook
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
	'Create worksheet of specified WorkBook
	Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")
	'insert data by cell addressing
	ws ("A1").Value = "Welcome"
	ws ("A2").Value = "To"
	ws ("A3").Value = "IronXL"
	'insert data by range
	ws ("C3:C8").Value = "Cell Value"
	'save the file in specified path
	wb.SaveAs("sample.xlsx")
	Console.WriteLine("successfully created.")
	Console.ReadKey()
End Sub
VB   C#

こちらは、新しく作成した Excel WorkBook sample.xlsx のスクリーンショットです。


8. DataTableからのC# Excel

複雑になりがちなコードの代わりに、IronXLはDataTableデータをExcelファイルに変換し、指定された場所に保存する効率的な方法を提供します。 新しいExcelファイルを作成し、DataTableからデータを入力します。 シンプル!

まず、新しいデータでDataTableを作成しましょう。 次に、Excelファイルを作成し、挿入して保存します。

/**
Excel from DataTable
anchor-c-num-excel-from-datatable
**/
using IronXL;
static void Main(string [] args)
{
    //create new datatable
    DataTable dt = new DataTable();
    dt.Columns.Add("id");
    dt.Columns.Add("name");
    dt.Columns.Add("phone");
    //fill data in datatable
    for (int i = 0; i < 5; i++)
    {
        dt.Rows.Add("id" + i.ToString(), "name" + i.ToString(), "phone" + i.ToString());
    }
    //Create new XL file
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    //Create WorkSheet
    WorkSheet ws = wb.CreateWorkSheet("sheet1");
    //send data in worksheet from datatable
    int j = 1; 
    foreach (DataRow row in dt.Rows)
    {
        ws ["A" + j].Value = row ["id"].ToString();
        ws ["B" + j].Value = row ["name"].ToString();
        ws ["C" + j].Value = row ["phone"].ToString();
        j = j + 1;
    }
    //save the file
    wb.SaveAs("sample.xlsx");
}
/**
Excel from DataTable
anchor-c-num-excel-from-datatable
**/
using IronXL;
static void Main(string [] args)
{
    //create new datatable
    DataTable dt = new DataTable();
    dt.Columns.Add("id");
    dt.Columns.Add("name");
    dt.Columns.Add("phone");
    //fill data in datatable
    for (int i = 0; i < 5; i++)
    {
        dt.Rows.Add("id" + i.ToString(), "name" + i.ToString(), "phone" + i.ToString());
    }
    //Create new XL file
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    //Create WorkSheet
    WorkSheet ws = wb.CreateWorkSheet("sheet1");
    //send data in worksheet from datatable
    int j = 1; 
    foreach (DataRow row in dt.Rows)
    {
        ws ["A" + j].Value = row ["id"].ToString();
        ws ["B" + j].Value = row ["name"].ToString();
        ws ["C" + j].Value = row ["phone"].ToString();
        j = j + 1;
    }
    //save the file
    wb.SaveAs("sample.xlsx");
}
'''
'''Excel from DataTable
'''anchor-c-num-excel-from-datatable
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	'create new datatable
	Dim dt As New DataTable()
	dt.Columns.Add("id")
	dt.Columns.Add("name")
	dt.Columns.Add("phone")
	'fill data in datatable
	For i As Integer = 0 To 4
		dt.Rows.Add("id" & i.ToString(), "name" & i.ToString(), "phone" & i.ToString())
	Next i
	'Create new XL file
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
	'Create WorkSheet
	Dim ws As WorkSheet = wb.CreateWorkSheet("sheet1")
	'send data in worksheet from datatable
	Dim j As Integer = 1
	For Each row As DataRow In dt.Rows
		ws ("A" & j).Value = row ("id").ToString()
		ws ("B" & j).Value = row ("name").ToString()
		ws ("C" & j).Value = row ("phone").ToString()
		j = j + 1
	Next row
	'save the file
	wb.SaveAs("sample.xlsx")
End Sub
VB   C#

こちらが私たちの出力の一例です:

では、IronXL を使用して XL WorkBook のセルプロパティを設定しましょう。


9. Excel ワークブック スタイルの設定

それでは、セルのプロパティを設定しましょう。 時には、さまざまな異なる要件に応じてプログラムでスタイルを設定する必要があります。 IronXLは、さまざまな機能のオプションを提供してくれるため、簡単にセルのスタイルを設定できます。

Excelファイルのセルアドレッシングシステムを使用して、スタイリングを適用する場所を指定できます。 日常的に使用することが多い基本的なスタイルプロパティを設定しましょう。

//bold the text of specified cell
WorkSheet ["CellAddress"].Style.Font.Bold =true;

//Italic the text of specified cell
WorkSheet ["CellAddress"].Style.Font.Italic =true;

//Strikeout the text of specified cell
WorkSheet ["CellAddress"].Style.Font.Strikeout = true;

//border style of specific cell 
WorkSheet ["CellAddress"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted;

//border color of specific cell 
WorkSheet ["CellAddress"].Style.BottomBorder.SetColor("color value");
//bold the text of specified cell
WorkSheet ["CellAddress"].Style.Font.Bold =true;

//Italic the text of specified cell
WorkSheet ["CellAddress"].Style.Font.Italic =true;

//Strikeout the text of specified cell
WorkSheet ["CellAddress"].Style.Font.Strikeout = true;

//border style of specific cell 
WorkSheet ["CellAddress"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted;

//border color of specific cell 
WorkSheet ["CellAddress"].Style.BottomBorder.SetColor("color value");
'bold the text of specified cell
WorkSheet ("CellAddress").Style.Font.Bold =True

'Italic the text of specified cell
WorkSheet ("CellAddress").Style.Font.Italic =True

'Strikeout the text of specified cell
WorkSheet ("CellAddress").Style.Font.Strikeout = True

'border style of specific cell 
WorkSheet ("CellAddress").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted

'border color of specific cell 
WorkSheet ("CellAddress").Style.BottomBorder.SetColor("color value")
VB   C#

IronXL では、指定された範囲内で上記のすべてのプロパティを設定する方法も提供しています。 この範囲内にあるすべてのセルにセルのスタイルが適用されます、次のように:

//bold the text of specified range cells
WorkSheet ["FromCellAddress : ToCellAddress"].Style.Font.Bold =true;

//Italic the text of specified range cells
WorkSheet ["FromCellAddress : ToCellAddress"].Style.Font.Italic =true;

//Strikeout the text of specified range cells
WorkSheet ["FromCellAddress : ToCellAddress"].Style.Font.Strikeout = true;

//border style of specified range cells 
WorkSheet ["FromCellAddress : ToCellAddress"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted;

//border color of specified range cells 
WorkSheet ["FromCellAddress : ToCellAddress"].Style.BottomBorder.SetColor("color value");
//bold the text of specified range cells
WorkSheet ["FromCellAddress : ToCellAddress"].Style.Font.Bold =true;

//Italic the text of specified range cells
WorkSheet ["FromCellAddress : ToCellAddress"].Style.Font.Italic =true;

//Strikeout the text of specified range cells
WorkSheet ["FromCellAddress : ToCellAddress"].Style.Font.Strikeout = true;

//border style of specified range cells 
WorkSheet ["FromCellAddress : ToCellAddress"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted;

//border color of specified range cells 
WorkSheet ["FromCellAddress : ToCellAddress"].Style.BottomBorder.SetColor("color value");
'bold the text of specified range cells
WorkSheet ("FromCellAddress : ToCellAddress").Style.Font.Bold =True

'Italic the text of specified range cells
WorkSheet ("FromCellAddress : ToCellAddress").Style.Font.Italic =True

'Strikeout the text of specified range cells
WorkSheet ("FromCellAddress : ToCellAddress").Style.Font.Strikeout = True

'border style of specified range cells 
WorkSheet ("FromCellAddress : ToCellAddress").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted

'border color of specified range cells 
WorkSheet ("FromCellAddress : ToCellAddress").Style.BottomBorder.SetColor("color value")
VB   C#

完全な例を見てみましょう。新しいXL WorkBookを作成し、セルのスタイリングを適用することを含みます。

/**
Set Workbook Styling
anchor-set-excel-workbook-style
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet ws = wb.CreateWorkSheet("Sheet1");
    ws ["B2:G2"].Value = "Range1";          
    ws ["B4:G4"].Value = "Range2";
    //------setting the styles----------
    ws ["B2:D2"].Style.Font.Bold = true;
    ws ["E2:G2"].Style.Font.Italic = true;
    ws ["B4:D4"].Style.Font.Strikeout = true;
    ws ["E4:G4"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted;
    ws ["E4:G4"].Style.BottomBorder.SetColor("#ff6600");
    wb.SaveAs("sample.xlsx");
    Console.WriteLine("successfully created.");
    Console.ReadKey();
}
/**
Set Workbook Styling
anchor-set-excel-workbook-style
**/
using IronXL;
static void Main(string [] args)
{
    WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet ws = wb.CreateWorkSheet("Sheet1");
    ws ["B2:G2"].Value = "Range1";          
    ws ["B4:G4"].Value = "Range2";
    //------setting the styles----------
    ws ["B2:D2"].Style.Font.Bold = true;
    ws ["E2:G2"].Style.Font.Italic = true;
    ws ["B4:D4"].Style.Font.Strikeout = true;
    ws ["E4:G4"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted;
    ws ["E4:G4"].Style.BottomBorder.SetColor("#ff6600");
    wb.SaveAs("sample.xlsx");
    Console.WriteLine("successfully created.");
    Console.ReadKey();
}
'''
'''Set Workbook Styling
'''anchor-set-excel-workbook-style
'''*
Imports IronXL
Shared Sub Main(ByVal args() As String)
	Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
	Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")
	ws ("B2:G2").Value = "Range1"
	ws ("B4:G4").Value = "Range2"
	'------setting the styles----------
	ws ("B2:D2").Style.Font.Bold = True
	ws ("E2:G2").Style.Font.Italic = True
	ws ("B4:D4").Style.Font.Strikeout = True
	ws ("E4:G4").Style.BottomBorder.Type = IronXL.Styles.BorderType.Dotted
	ws ("E4:G4").Style.BottomBorder.SetColor("#ff6600")
	wb.SaveAs("sample.xlsx")
	Console.WriteLine("successfully created.")
	Console.ReadKey()
End Sub
VB   C#

以下は、新しく作成した Excel ワークブック sample.xlsx の外観です:

あなたのExcelワークシートでプログラム的にできることがもっとたくさんあります。 より長いチュートリアルについては C#でExcelファイルを開いて書き込む .NETでは、提供されたコード例および手順に従ってください。


チュートリアル クイック アクセス

C# で Excel ドキュメントを作成

IronXLのAPIリファレンスで、Excelワークブックやワークシートの作成、セルスタイリングの適用、その他の多くの機能についてのドキュメントを探索してください。

C# で Excel ドキュメントを作成