虽然发表了2篇关于NPOI导出EXCEL的文章,但是最近再次使用的时候,把以前的代码粘贴过来,居然报了一个错误:
“服务器无法在发送 HTTP 标头之后追加标头”
后来也查询了很多其他同学的文章,都没有成功,可能问题不太一样吧,我的问题出在:获取httpResponse对象没有写在方法内部,是用的一个属性接受的,在方法调用导致的。
下面粘上完整代码,错误代码已注释,供其他同学参考:
////// EXCEL帮助类 /// ///泛型类 ///泛型类集合 public class ExcelHelpwhere TCollection : List { public static ExcelHelp instance = new ExcelHelp (); //获取httpResponse对象原位置,放在这里不知道会报错:服务器无法在发送 HTTP 标头之后追加标头 //可能是这里拿到的httpResponse对象不是最新请求的对象导致的,将其放到方法内部即可 //HttpResponse baseResponse = HttpContext.Current.Response; /// /// 将数据导出EXCEL /// /// 键值对集合(键:列名,值:每列数据集合) public void ExportExcelData(Dictionary> columnNameAndShowNameDic) { IWorkbook workbook = new HSSFWorkbook(); ISheet worksheet = workbook.CreateSheet("sheet1"); List columnNameList = columnNameAndShowNameDic.Keys.ToList(); //设置首列显示 IRow row1 = worksheet.CreateRow(0); ICell cell = null; ICellStyle cellHeadStyle = workbook.CreateCellStyle(); //设置首行字体加粗 IFont font = workbook.CreateFont(); font.Boldweight = short.MaxValue; cellHeadStyle.SetFont(font); for (var i = 0; i < columnNameList.Count; i++) { cell = row1.CreateCell(i); cell.SetCellValue(columnNameList[i]); cell.CellStyle = cellHeadStyle; } var raws = columnNameAndShowNameDic[columnNameList[0]].Count; for (int i = 0; i < columnNameList.Count; i++) { for (int j = 0; j < raws; j++) { if (i == 0) { row1 = worksheet.CreateRow(j + 1); } else { row1 = worksheet.GetRow(j + 1); } cell = row1.CreateCell(i); cell.SetCellValue(columnNameAndShowNameDic[columnNameList[i]][j]); } //设置行宽度自适应 worksheet.AutoSizeColumn(i, true); //worksheet.SetColumnWidth(i, columnWidth * 200); } //http请求Response对象-这里httpResponse对象要在方法内获取,否则可能会出现:无法再response发送表头后添加header的问题 HttpResponse baseResponse = HttpContext.Current.Response; baseResponse.Clear(); baseResponse.Buffer = true; baseResponse.ContentEncoding = System.Text.Encoding.UTF8; baseResponse.ContentType = "application/vnd.ms-excel"; //设置导出文件名 baseResponse.AppendHeader("content-disposition", "attachment;filename=zhilian.xls"); MemoryStream ms = new MemoryStream(); workbook.Write(ms); byte[] buffer = ms.ToArray(); baseResponse.AddHeader("Content-Length", buffer.Length.ToString()); baseResponse.BinaryWrite(buffer); baseResponse.Flush(); baseResponse.End(); } }