下面这个方法需引用Microsoft Excel 11 Object Library COM组件
传入一个Dataset和Excel文件完整路径
public static void ExportToExcel(DataSet ds,string strExcelFileName)
{
Excel.Application excel= new Excel.Application();
Excel.Worksheet sheet = null;
int i = 1;
excel.Application.Workbooks.Add(true);
sheet = (Excel.Worksheet)excel.Application.Worksheets.get_Item(1);
foreach(DataTable table in ds.Tables)
{
int rowIndex=1;
int colIndex=0;
try
{
if(i>1)
excel.Worksheets.Add(System.Reflection.Missing.Value,sheet,1,Excel.XlSheetType.xlWorksheet);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1,colIndex]=col.ColumnName;
}
foreach(DataRow row in table.Rows)
{
rowIndex++;
colIndex=0;
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
}
}
sheet = (Excel.Worksheet)excel.Application.Worksheets.get_Item(i);
i++;
}
excel.Visible=false;
excel.ActiveWorkbook.SaveAs(strExcelFileName,Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);
excel.Quit();
excel=null;
GC.Collect();
}
直接调用就可以了,大家可以试一试.
还有其他方法:参考如下地址:
http://support.microsoft.com/kb/302815/
For additional information about automating Excel from Visual C# .NET, click the article numbers below to view the articles in the Microsoft Knowledge Base:
DataGrid 导出到 Excel 的帮助类