public void saveAsExcel(string path, DataTable tbdt) { object objMissing = System.Reflection.Missing.Value; Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); app.Visible = false; Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Add(objMissing); Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets[1]; for (int i = 0; i < tbdt.Columns.Count; i++) { Microsoft.Office.Interop.Excel.Range head = (Microsoft.Office.Interop.Excel.Range)workSheet.Cells[3, i + 1]; head.Value = tbdt.Columns[i].ColumnName; head = null; } Microsoft.Office.Interop.Excel.Range range = workSheet.get_Range("A4", objMissing); int rows = tbdt.Rows.Count, cols = tbdt.Columns.Count; Microsoft.Office.Interop.Excel.Range ranges = range.get_Resize(rows, cols); object[,] datas = new object[rows, cols]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { datas[i, j] = tbdt.Rows[i][j].ToString(); } } ranges.Value = datas; workBook.SaveAs(path, objMissing, objMissing, objMissing, objMissing, objMissing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, objMissing, objMissing, objMissing, objMissing); workBook.Close(false, objMissing, objMissing); app.Quit(); range = null; ranges = null; workBook = null; workSheet = null; app = null; }
分多个sheet
更换成 excel 2007 或 excel 2010