(C#)DataTable导出Excel
public bool DataTableToExcel(System.Data.DataTable excelTable, string filePath) { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); try { app.Visible = false; Microsoft.Office.Interop.Excel.Workbook wBook = app.Workbooks.Add(true); Microsoft.Office.Interop.Excel.Worksheet wSheet = wBook.Sheets[1]; object[,] objData = new object[excelTable.Rows.Count + 1, excelTable.Columns.Count]; //首先将数据写入到一个二维数组中 for (int i = 0; i < excelTable.Columns.Count; i++) { objData[0, i] = excelTable.Columns[i].ColumnName; } if (excelTable.Rows.Count > 0) { for (int i = 0; i < excelTable.Rows.Count; i++) { for (int j = 0; j < excelTable.Columns.Count; j++) { //if (excelTable.Rows[i][j].Equals(float.NaN))//查询过来的float.NaN // objData[i + 1, j] = "-"; ////else if (String.IsNullOrEmpty(excelTable.Rows[i][j].ToString()) && excelTable.Rows[i][j].Equals(DBNull.Value))//有dbnull的数据,需要屏蔽掉——在数据源处理了 //// objData[i + 1, j] = excelTable.Rows[i][j]; //else objData[i + 1, j] = excelTable.Rows[i][j]; } } } string startCol = "A";//这里关键,计算要替换的区域 int iCnt = ((excelTable.Columns.Count - 1) / 26);//当列数是26时 不-1 会出现问题,自己试试就明白了 string endColSignal = (iCnt == 0 ? "" : ((char)('A' + (iCnt - 1))).ToString()); string endCol = endColSignal + ((char)('A' + excelTable.Columns.Count - iCnt * 26 - 1)).ToString(); Microsoft.Office.Interop.Excel.Range range = wSheet.get_Range(startCol + "1", endCol + (excelTable.Rows.Count + 1).ToString()); range.Value = objData; //给Exccel中的Range整体赋值 range.EntireColumn.AutoFit(); //设定Excel列宽度自适应 wSheet.get_Range(startCol + "1", endCol + "1").Font.Bold = 1;//Excel文件列名 字体设定为Bold //设置禁止弹出保存和覆盖的询问提示框 app.DisplayAlerts = false; app.AlertBeforeOverwriting = false; //保存工作簿 //wBook.Save(); wSheet.SaveAs(filePath); wBook.Close(); //保存excel文件 //app.Save(filePath); //app.SaveWorkspace(filePath); app.Quit(); GC.Collect(); return true; } catch (Exception err)//这里还有些问题,比如 对方安装的是WPS 不会提示中文错误,没有安装office 也不会弹出该错误 { return false; } finally { } }