引入命名空间:
using System.Data;
using Microsoft.Office.Interop.Excel;
添加com引用:
Microsoft.Office.Interop.Excel.dll
OFFICE.DLL
C#:
public void doReports(System.Data.DataSet ds, string strExcelFileName)
{
strExcelFileName = "D:/"+ strExcelFileName + ".xls";
bool fileSaved = false;
Application xlApp = new Application();
if (xlApp == null)
{
return;
}
Workbooks workbooks = xlApp.Workbooks;
Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1
//写入字段
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName;
}
//写入数值
for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = ds.Tables[0].Rows[r][i];
}
}
worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
if (strExcelFileName != "")
{
try
{
workbook.Saved = true;
workbook.SaveCopyAs(strExcelFileName);//保存创建文件
fileSaved = true;
}
catch (Exception ex)
{
fileSaved = false;
}
}
else
{
fileSaved = false;
}
xlApp.Quit();
GC.Collect();//强行销毁
//导出成功就打开文件
if (fileSaved && System.IO.File.Exists(strExcelFileName))
System.Diagnostics.Process.Start(strExcelFileName); //打开EXCEL
}