public static class ExportExcel
{ public static void DataTable2Excel(string attachName, DataTable tab) { string file = HttpContext.Current.Server.MapPath("/uploads/export/" + Guid.NewGuid().ToString() + ".xls"); Workbook workbook = new Workbook(); Worksheet worksheet = new Worksheet("Sheet1"); //构建表头 for (int col = 0; col < tab.Columns.Count; col++) { worksheet.Cells[0, col] = new Cell(tab.Columns[col].ColumnName); } for (int rowIndex = 0; rowIndex < tab.Rows.Count; rowIndex++) { for (int colIndex = 0; colIndex < tab.Columns.Count; colIndex++) { worksheet.Cells[rowIndex + 1, colIndex] = new Cell(tab.Rows[rowIndex][colIndex].ToString()); } } //设置默认宽度 if (worksheet.Cells.LastRowIndex > 1) { for (int n = 0; n < tab.Columns.Count; n++) { if (worksheet.Cells[1, n].Value.ToString().Length >= 50) worksheet.Cells.ColumnWidth[(ushort)n] = 10000; else if (worksheet.Cells[1, n].Value.ToString().Length >= 10) worksheet.Cells.ColumnWidth[(ushort)n] = (ushort)(worksheet.Cells[1, n].Value.ToString().Length * 300); else worksheet.Cells.ColumnWidth[(ushort)n] = 3000; } } else worksheet.Cells.ColumnWidth[0, (ushort)(tab.Columns.Count - 1)] = 3000; workbook.Worksheets.Add(worksheet); workbook.Save(file); FileInfo info = new FileInfo(file); long size = 0; if (info.Exists) size = info.Length; HttpContext.Current.Response.AddHeader("content-type", "application/x-msdownload;"); HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(attachName + ".xls")); HttpContext.Current.Response.AddHeader("content-length", size.ToString()); HttpContext.Current.Response.WriteFile(file, 0, size); } }