C#创建Excel
使用C#编程创建Excel电子表格文件是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 WorkBook 的类型(.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的名称。
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. 从 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
下面是我们的输出结果:
现在,让我们使用 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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
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");
IRON VB CONVERTER ERROR developers@ironsoftware.com
让我们来看一个完整的示例,包括创建新的 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 文件请按照所提供的代码示例和步骤进行操作。