/// <summary> /// /// </summary> /// <param name="excelTable"></param> /// <param name="filePath"></param> /// <returns></returns> public static bool SaveDataTableToExcel(System.Data.DataTable excelTable, string filePath, int startRow, int startColumn, int sheets) { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = false; Workbook wBook = app.Workbooks.Add(true); Worksheet wSheet = wBook.Worksheets[sheets] as Worksheet; try { if (excelTable.Rows.Count > 0) { int row = 0; row = excelTable.Rows.Count; int col = excelTable.Columns.Count; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { string str = excelTable.Rows[i][j].ToString(); wSheet.Cells[i + startRow, j + startColumn] = str; } Console.WriteLine("导出进度(行):" + i); } } //设置标题 int size = excelTable.Columns.Count; for (int i = 0; i < size; i++) { wSheet.Cells[1, 1 + i] = excelTable.Columns[i].ColumnName; } //设置禁止弹出保存和覆盖的询问提示框 app.DisplayAlerts = false; app.AlertBeforeOverwriting = false; //保存工作簿 wBook.Save(); //保存excel文件 app.Save(filePath); app.SaveWorkspace(filePath); //app.Quit(); //app = null; } catch (Exception err) { Console.WriteLine("导出Excel出错!错误原因:" + err.Message); return(false); } finally { app.Quit(); app = null; // 9.释放资源 System.Runtime.InteropServices.Marshal.ReleaseComObject(wSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook); //System.Runtime.InteropServices.Marshal.ReleaseComObject(app); // 10.调用GC的垃圾收集方法 GC.Collect(); GC.WaitForPendingFinalizers(); } return(true); }