该文档展示了如何在 C# 中生成 Excel 文件。以下步骤和代码片段演示了如何在不使用 MS Office 互操作的情况下在 C# 中创建 Excel 文件。
在 C# 中生成 Excel 文件的步骤
- 从 NuGet.org 下载或安装 Aspose.Cells for .NET 包
- 将 Aspose.Cells 命名空间导入 VS.NET 项目
- 定义 License 对象并使用 SetLicense 方法设置它
- 创建一个空的 Workbook
- 在第一个 Worksheet 的单元格中输入报告数据
- 保存包含数据的 Excel XLSX 文件
多年来,众所周知,MS Excel 文件格式可用于数据分析和数据报告。上述步骤描述了使用 C# 写入 Excel 文件的过程。我们编写 C# 代码从头开始创建一个新的 Excel 文件。 Excel 文件将包含一个示例客户报告;您可以通过使用工作表中的数据填充相关单元格来创建所需的报告。
在 C# 中生成 Excel 文件的示例代码
//Add reference to the namespace of Aspose.Cells for .NET | |
using Aspose.Cells; | |
namespace GenerateExcelFile | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//At the start, set the license before using other APIs | |
Aspose.Cells.License Aspose_Cells_license = new Aspose.Cells.License(); | |
Aspose_Cells_license.SetLicense("Aspose.Cells.lic"); | |
//Create an Excel workbook from the scratch | |
Workbook ExcelFileWorkbook = new Workbook(); | |
//Get the first worksheet (0 indexed position) in the workbook, the default worksheet | |
Worksheet ExcelFileSheet = ExcelFileWorkbook.Worksheets[0]; | |
//Get the cells collection in the default worksheet | |
Cells SheetCells = ExcelFileSheet.Cells; | |
//Insert data into the cells of the sheet | |
SheetCells["A1"].PutValue("Customers Report"); | |
SheetCells["A2"].PutValue("C_ID"); | |
SheetCells["B2"].PutValue("C_Name"); | |
SheetCells["A3"].PutValue("C001"); | |
SheetCells["B3"].PutValue("Customer1"); | |
SheetCells["A4"].PutValue("C002"); | |
SheetCells["B4"].PutValue("Customer2"); | |
SheetCells["A5"].PutValue("C003"); | |
SheetCells["B5"].PutValue("Customer3"); | |
SheetCells["A6"].PutValue("C004"); | |
SheetCells["B6"].PutValue("Customer4"); | |
//Save to Excel file (XLSX) | |
ExcelFileWorkbook.Save("ExcelFile.xlsx"); | |
} | |
} | |
} |
在上面的示例中,您将学习如何在 C# 中动态创建 Excel 文件。使用 C#.NET,您可以轻松创建 Excel 文件。在代码片段中,我们将数据插入到工作簿中第一个工作表的几个单元格中,以制作一个简单的报告。最后,我们将 Excel XLSX 文件保存到磁盘。此外,您可能会喜欢 如何在 C# 中将大型 Excel 文件导出为 CSV。