c# excel 导出 流
时间: 2023-08-01 16:15:12 浏览: 193
C#中可以使用Microsoft.Office.Interop.Excel库来实现Excel导出。下面是一个示例代码,可以将数据导出到Excel表格中并保存为流:
```csharp
using Microsoft.Office.Interop.Excel;
using System.IO;
public MemoryStream ExportToExcel(DataTable data)
{
Application excel = new Application();
Workbook workbook = excel.Workbooks.Add();
Worksheet worksheet = workbook.ActiveSheet;
for (int i = 1; i <= data.Columns.Count; i++)
{
worksheet.Cells[1, i] = data.Columns[i - 1].ColumnName;
}
for (int i = 0; i < data.Rows.Count; i++)
{
for (int j = 0; j < data.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = data.Rows[i][j].ToString();
}
}
MemoryStream memoryStream = new MemoryStream();
workbook.SaveAs(memoryStream);
workbook.Close();
excel.Quit();
return memoryStream;
}
```
你可以根据需要修改代码来满足你的需求。
阅读全文