c#保存数据到excel
时间: 2023-08-10 22:02:52 浏览: 126
你可以使用C#中的Excel Interop来保存数据到Excel中。以下是一个示例代码:
1.引入Microsoft.Office.Interop.Excel命名空间
```
using Excel = Microsoft.Office.Interop.Excel;
```
2.创建Excel应用程序对象
```
Excel.Application excel = new Excel.Application();
```
3.创建一个新的工作簿
```
Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
```
4.创建一个新的工作表
```
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
```
5.将数据写入工作表
```
worksheet.Cells[1, 1] = "姓名";
worksheet.Cells[1, 2] = "年龄";
worksheet.Cells[2, 1] = "张三";
worksheet.Cells[2, 2] = "20";
worksheet.Cells[3, 1] = "李四";
worksheet.Cells[3, 2] = "25";
```
6.保存工作簿
```
workbook.SaveAs("data.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
```
7.释放Excel对象
```
workbook.Close(true, Type.Missing, Type.Missing);
excel.Quit();
```
完整代码示例:
```
using Excel = Microsoft.Office.Interop.Excel;
public static void SaveToExcel()
{
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.ActiveSheet;
// 写入数据
worksheet.Cells[1, 1] = "姓名";
worksheet.Cells[1, 2] = "年龄";
worksheet.Cells[2, 1] = "张三";
worksheet.Cells[2, 2] = "20";
worksheet.Cells[3, 1] = "李四";
worksheet.Cells[3, 2] = "25";
// 保存工作簿
workbook.SaveAs("data.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// 释放Excel对象
workbook.Close(true, Type.Missing, Type.Missing);
excel.Quit();
}
```
阅读全文