如果你在尝试使用C#导出数据到Excel文件时遇到了问题,可以尝试以下方法来解决:
using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
public void ExportToExcel(string[] data, string fileName)
{
Application excel = new Application();
Workbook workbook = excel.Workbooks.Add();
Worksheet worksheet = workbook.ActiveSheet;
for (int i = 0; i < data.Length; i++)
{
worksheet.Cells[i + 1, 1] = data[i];
}
workbook.SaveAs(fileName);
workbook.Close();
excel.Quit();
}
例如,使用EPPlus库导出数据到Excel文件的示例代码如下:
using OfficeOpenXml;
using System.IO;
public void ExportToExcel(string[] data, string fileName)
{
FileInfo fileInfo = new FileInfo(fileName);
using (ExcelPackage package = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
for (int i = 0; i < data.Length; i++)
{
worksheet.Cells[i + 1, 1].Value = data[i];
}
package.Save();
}
}
领取专属 10元无门槛券
手把手带您无忧上云