private void doExport(System.Data.DataTable dt, string strSheetName)
{
Excel.Application excel = new Excel.Application(); //Execl的操作类
//读取保存目标的对象
Excel.Workbook bookDest = (Excel.WorkbookClass)excel.Workbooks.Add(Missing.Value);
Excel.Worksheet sheetDest = bookDest.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;//给工作薄添加一个Sheet
sheetDest.Name = strSheetName;//自己定义名字O(∩_∩)O哈哈~
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);//这句不写不知道会不会报错
foreach (DataColumn col in dt.Columns)
{
colIndex++;
sheetDest.Cells[1, colIndex] = col.ColumnName;//Execl中的第一列,把DataTable的列名先导进去
}
//导入数据行
foreach (DataRow row in dt.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in dt.Columns)
{
colIndex++;
sheetDest.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
}
}
bookDest.Saved = true;
String path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
bookDest.SaveCopyAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/查询" + DateTime.Now.ToShortDateString() + ".xls");//方式一
//方式二 bookDest.SaveAs("要保存的文件路径+文件名.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
excel.Quit();
excel = null;
GC.Collect();//垃圾回收
}