C# 創建 Excel
以程式方式創建 Excel 試算表文件是 C# 開發人員經常執行的任務,今天我們將解決這些問題,包括學習如何創建新的 Excel 文件、設置單元格樣式以及使用 C# 程式插入數據。使用適當的程式碼,您可以完全自訂和樣式化您的工作表以滿足您的需求。我們將一步一步地介紹如何為您的 .NET 項目創建 C# Excel 工作簿。
第一步
1. 使用 IronXL 創建 C# Excel 試算表
今天我們將使用 IronXL,這是一個 C# 函式庫,可提供 Excel 功能,使處理 Excel 文件變得更加高效。它免費提供給開發項目使用。安裝它並按照教程進行操作。
下載到您的專案 或遵循 使用 NuGet 安裝到 Visual Studio.
Install-Package IronXL.Excel
如何操作教程
2. C# 創建 Excel WorkBook
一旦我們在項目中安裝了 IronXL,我們就可以創建一個 Excel Workbook。使用 WorkBook.Create
()IronXL 的功能
WorkBook wb = WorkBook.Create();
WorkBook wb = WorkBook.Create();
Dim wb As WorkBook = WorkBook.Create()
它將創建一個新的 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)
現在,我們可以使用 wb
創建工作表。
3. 使用C#建立Excel電子表格
要建立工作表,IronXL提供了Workbook.CreateWorkSheet
()函數。該函數需要一個字符串參數,我們可以在其中指定工作表的名稱。
WorkSheet ws = wb.CreateWorkSheet("SheetName");
WorkSheet ws = wb.CreateWorkSheet("SheetName");
Dim ws As WorkSheet = wb.CreateWorkSheet("SheetName")
wb
是工作簿 (見上文) 以及 ws
是一個新建立的 WorkSheet。同樣地,我們可以根據需要創建任意多的 WorkSheet。例如:
/**
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")
4. 插入儲存格資料
現在,我們可以在指定的工作表中插入資料。我們將使用 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"
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"
這將在所有位於指定範圍內的儲存格中插入 value
。你可以閱讀更多有關 C# Excel 範圍 用於您的 .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")
通過上述單行代碼,新創建的Excel工作簿將保存到指定位置。深入了解 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
這是我們新建的 Excel 工作簿名為 sample.xlsx
的截圖:
8. C# 从 DataTable 导出 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
這是我們的輸出:
現在,讓我們使用 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")
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")
讓我們來看一個完整的範例,包括建立一個新的 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
以下是我們新創建的名為 sample.xlsx
的 Excel 工作簿的樣子:
用程式化方式操作你的 Excel 工作表可以做更多的事情。欲了解更多教程請參考 使用 C# 打開和寫入 Excel 文件 在 .NET 中,按照提供的代碼範例和步驟進行操作。