c# 动态生成execel
时间: 2023-08-04 10:07:12 浏览: 118
C# 动态生成exe
3星 · 编辑精心推荐
你可以使用 C# 中的 Microsoft.Office.Interop.Excel 库来动态生成 Excel。以下是一个简单的示例代码:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
Excel.Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
Excel.Worksheet worksheet = null;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "MySheet";
// 在 Excel 表格中添加数据
worksheet.Cells[1, 1] = "姓名";
worksheet.Cells[1, 2] = "年龄";
worksheet.Cells[2, 1] = "Tom";
worksheet.Cells[2, 2] = "20";
worksheet.Cells[3, 1] = "Jerry";
worksheet.Cells[3, 2] = "25";
// 保存 Excel 文件
workbook.SaveAs("MyExcelFile.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close();
excelApp.Quit();
```
上述代码会生成一个名为 "MyExcelFile.xlsx" 的 Excel 文件,并在其中添加了一些数据。你可以根据你的需求进行修改和扩展。
阅读全文