c#数据存储到EXCEL
时间: 2023-11-22 17:38:09 浏览: 100
c# 存入数据到excel以及读取excel数据
在C#中,可以使用以下代码将数据存储到Excel文件中:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
public bool DataSetToExcel(DataSet dataSet, string fileName, bool isShowExcel, string sFieldName)
{
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add();
Excel.Worksheet worksheet = workbook.ActiveSheet;
DataTable dataTable = dataSet.Tables[0];
int rowNumber = dataTable.Rows.Count;
int columnNumber = dataTable.Columns.Count;
// 将数据写入Excel
for (int row = 1; row <= rowNumber; row++)
{
for (int col = 1; col <= columnNumber; col++)
{
worksheet.Cells[row, col] = dataTable.Rows[row - 1][col - 1].ToString();
}
}
// 设置字段名称
for (int col = 1; col <= columnNumber; col++)
{
worksheet.Cells[1, col] = dataTable.Columns[col - 1].ColumnName;
}
// 保存Excel文件
workbook.SaveAs(fileName);
// 打开Excel文件
if (isShowExcel)
{
excel.Visible = true;
}
else
{
excel.Quit();
}
return true;
}
```
阅读全文