一般情况下都是 DataTable导出为Excel,这次来一个导出为自定义格式的Excel
Workbook wb = new Workbook(); Worksheet sheet = wb.Worksheets[0];//获取工作页 Cells cs = sheet.Cells;//获取工作页的单元格 //设置标题 Aspose.Cells.Style headerStyle = wb.Styles[wb.Styles.Add()];//设置标题样式 headerStyle.HorizontalAlignment = TextAlignmentType.Center; headerStyle.Font.Name = "宋体"; headerStyle.Font.Size = 18; headerStyle.Font.IsBold = true; cs.Merge(0, 0, 1, 12);//合并单元格(参数详解:第一个为哪一行,第二个为那一列,第三个为合并几个行单元格,最后一个为合并几个列单元格) cs[0, 0].PutValue("表");//表名(该方法是为 单元格赋值) cs[0, 0].SetStyle(headerStyle);//设置样式 cs.SetRowHeight(0, 28);//设置行高
设置好单元格好,就可以导出了
MemoryStream ms = wb.SaveToStream(); byte[] bt = ms.ToArray(); string fileName = "情况"+DateTime.Now.ToString("yyyyMMddHHmmss")+".xls"; System.Web.HttpContext curContext = System.Web.HttpContext.Current; curContext.Response.Clear(); curContext.Response.Buffer = true; curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = ""; curContext.Response.AppendHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls"); curContext.Response.BinaryWrite(bt); curContext.Response.Flush(); curContext.ApplicationInstance.CompleteRequest();
附一个导入excel的方法
public DataTable ReadExcel(String strFileName) { Workbook book = new Workbook(); book.Open(strFileName); Worksheet sheet = book.Worksheets[0]; Cells cells = sheet.Cells; return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true); }