NPOI導出EXCEL報_伺服器無法在發送 HTTP 標頭之後追加標頭 ...
雖然發表了2篇關於NPOI導出EXCEL的文章,但是最近再次使用的時候,把以前的代碼粘貼過來,居然報了一個錯誤:
“伺服器無法在發送 HTTP 標頭之後追加標頭”
後來也查詢了很多其他同學的文章,都沒有成功,可能問題不太一樣吧,我的問題出在:獲取httpResponse對象沒有寫在方法內部,是用的一個屬性接受的,在方法調用導致的。
下麵粘上完整代碼,錯誤代碼已註釋,供其他同學參考:
/// <summary> /// EXCEL幫助類 /// </summary> /// <typeparam name="T">泛型類</typeparam> /// <typeparam name="TCollection">泛型類集合</typeparam> public class ExcelHelp<T, TCollection> where TCollection : List<T> { public static ExcelHelp<T, TCollection> instance = new ExcelHelp<T, TCollection>(); //獲取httpResponse對象原位置,放在這裡不知道會報錯:伺服器無法在發送 HTTP 標頭之後追加標頭 //可能是這裡拿到的httpResponse對象不是最新請求的對象導致的,將其放到方法內部即可 //HttpResponse baseResponse = HttpContext.Current.Response; /// <summary> /// 將數據導出EXCEL /// </summary> /// <param name="columnNameAndShowNameDic">鍵值對集合(鍵:列名,值:每列數據集合)</param> public void ExportExcelData(Dictionary<string, List<string>> columnNameAndShowNameDic) { IWorkbook workbook = new HSSFWorkbook(); ISheet worksheet = workbook.CreateSheet("sheet1"); List<string> 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(); } }