C# 创建 Excel
以编程方式创建 Excel 电子表格文件是 C# 开发人员的一项常见任务,我们今天要解决的问题包括学习使用 C# 编程创建新 Excel 文件、设置单元格样式和插入数据。有了正确的代码,你就可以完全自定义和样式化你的工作表,以满足你的要求。我们将逐步讲解如何为您的 .NET 项目创建 C# Excel 工作簿。
步骤 1
1.使用 IronXL 创建 C# Excel 电子表格
今天我们将使用 IronXL,这是一个 Excel 功能的 C# 库,它能使 Excel 文件的处理更加高效。它可免费用于开发项目。请安装并按照教程操作。
下载到您的项目 或关注 将 NuGet 安装到 Visual Studio.
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()
它将创建一个新的 Excel 工作簿 wb
。我们可以指定 XL 工作簿的类型 ( .xlsx "或 "xls ) 在 WorkBook.Create'(创建工作簿)中使用
ExcelFileFormat` 作为参数。()功能如下
/**
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
是新创建的工作表。同样,我们可以根据需要创建任意多个工作表。例如
/**
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 电子表格示例.
7.创建、插入数据和保存示例
/**
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# Excel from DataTable
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 文件 请按照所提供的代码示例和步骤进行操作。