public static bool DataSetToExcel(DataSet dataSet, string filePath, bool isShowExcle = true) { DataTable dataTable = dataSet.Tables[0]; int rowNumber = dataTable.Rows.Count; int columnNumber = dataTable.Columns.Count; if (rowNumber == 0) { return false; } //建立Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workBook = excel.Application.Workbooks.Add(true); excel.Visible = false;//是否打开该Excel文件 excel.Cells.ColumnWidth = 16;//设置单元格宽 excel.Cells.NumberFormatLocal = "@";//设置所有单元格式 //生成字段名称 //从第一行开始 EXCEL起始索引为1 for (int col = 0; col < columnNumber; col++) { excel.Cells[1, col + 1] = dataTable.Columns[col].ColumnName; } //填充数据 //从第二行开始 for (int row = 0; row < rowNumber; row++) { for (int col = 0; col < columnNumber; col++) { excel.Cells[row + 2, col + 1] = dataTable.Rows[row].ItemArray[col]; //if (col < 3) //{ // excel.Cells[row + 2, col + 1].NumberFormatLocal = "@"; //} } } workBook.SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); try { workBook.Saved = true; excel.UserControl = false; } catch (Exception ex) { Log.Writer(ex, "DataSetToExcel异常"); return false; } finally { workBook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Missing.Value, Missing.Value); excel.Quit(); } if (isShowExcle) { System.Diagnostics.Process.Start(filePath); } return true; }