首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net
将DataTable导出Xlsx格式的文件下载(网页输出):
1 /// <summary> 2 /// 导出Excel表格 3 /// </summary> 4 /// <param name="list">数据集合</param> 5 /// <param name="header">数据表头</param> 6 /// <returns></returns> 7 public void ExportExcel(DataTable dt, string[] header) 8 { 9 Workbook wb = new Workbook(FileFormatType.Xlsx); 10 try 11 { 12 Worksheet sheet = wb.Worksheets[0]; 13 sheet.Name = "MO上行查询结果"; 14 if (dt.Rows.Count <= 0) 15 { 16 System.Web.HttpContext.Current.Response.Write("<script>alert(‘没有检测到需要导出数据!‘);</script>"); 17 return; 18 } 19 // 为单元格添加样式 20 Aspose.Cells.Style style = wb.CreateStyle(); 21 style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center; //设置居中 22 style.Font.Size = 12;//文字大小 23 style.Font.IsBold = true;//粗体 24 style.HorizontalAlignment = TextAlignmentType.Center;//文字居中 25 26 int rowIndex = 0; 27 for (int i = 0; i < header.Length; i++) 28 { 29 sheet.Cells[rowIndex, i].PutValue(header[i]); 30 sheet.Cells[rowIndex, i].SetStyle(style); 31 sheet.Cells.SetColumnWidth(i, 20);//设置宽度 32 } 33 for (int i = 0; i < dt.Rows.Count; i++)//遍历DataTable行 34 { 35 sheet.Cells[i + 1, 0].PutValue(dt.Rows[i]["SENDER"].ToString()); 36 sheet.Cells[i + 1, 1].PutValue(dt.Rows[i]["SENDCONTENT"].ToString()); 37 sheet.Cells[i + 1, 2].PutValue(""); 38 sheet.Cells[i + 1, 3].PutValue(dt.Rows[i]["RECDATE"].ToString()); 39 sheet.Cells[i + 1, 4].PutValue(dt.Rows[i]["sn"].ToString()); 40 } 41 } 42 catch (Exception e) 43 { 44 System.Web.HttpContext.Current.Response.Write("<script>alert(‘导出异常:" + e.Message + "!‘);</script>"); 45 } 46 #region 输出到Excel 47 using (MemoryStream ms = new MemoryStream()) 48 { 49 50 wb.Save(ms, new OoxmlSaveOptions(SaveFormat.Xlsx));//默认支持xls版,需要修改指定版本 51 System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); 52 System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; 53 System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); 54 wb = null; 55 System.Web.HttpContext.Current.Response.End(); 56 } 57 #endregion 58 }
Aspose.Cells.dll 下载地址:http://pan.baidu.com/s/1o8TRXDg
其它相关参考:
https://my.oschina.net/u/876556/blog/98801
http://www.cnblogs.com/top5/archive/2010/02/16/1668801.html
http://www.cnblogs.com/springyangwc/archive/2011/08/12/2136498.html
原文地址:https://www.cnblogs.com/wwwbdabc/p/11652449.html
时间: 2024-10-31 04:25:37