1 private void 导出ToolStripMenuItem_Click(object sender, EventArgs e) { 2 string path = ""; 3 SaveFileDialog save = new SaveFileDialog(); 4 save.DefaultExt = "xlsx"; 5 save.Filter = "Excel File(*.xlsx)|*.xlsx"; 6 if (save.ShowDialog() == DialogResult.OK) { 7 path = save.FileName; 8 if(DataTableToExcel(path,dt,true)) { 9 MessageBox.Show("导出成功"); 10 } 11 } 12 else { 13 return; 14 } 15 } 16 public bool DataTableToExcel(string filePath, System.Data.DataTable dataTable, bool isShowExcle) { 17 //System.Data.DataTable dataTable = dataSet.Tables[0]; 18 int rowNumber = dataTable.Rows.Count; 19 int columnNumber = dataTable.Columns.Count; 20 int colIndex = 0; 21 if (rowNumber == 0) { 22 return false; 23 } 24 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 25 Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); 26 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; 27 excel.Visible = isShowExcle; 28 Microsoft.Office.Interop.Excel.Range range; 29 foreach (DataColumn col in dataTable.Columns) { 30 colIndex++; 31 excel.Cells[1, colIndex] = col.ColumnName; 32 } 33 object[,] objData = new object[rowNumber, columnNumber]; 34 for (int r = 0; r < rowNumber; r++) { 35 for (int c = 0; c < columnNumber; c++) { 36 objData[r, c] = dataTable.Rows[r][c]; 37 } 38 } 39 range= worksheet.Range[worksheet.Cells[2,1], worksheet.Cells[rowNumber + 1, columnNumber]]; //4.0版本以上 40 // range = worksheet.get_Range(excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]); //如果出现没有找到get_Range定义是因为版本不同,使用上面的就可以啦 41 range.Value = objData; 42 worksheet.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing); 43 //excel.Quit(); 44 return true; 45 }