我正在使用NPOI將DataTable轉換爲ASP.NET Web API項目中的Excel。在NPOI workbook.write後,MemoryStream似乎會關閉?
但我沒有收到任何迴應。這裏是我的代碼:
public HttpResponseMessage GetExcelFromDataTable(DataTable dt)
{
IWorkbook workbook = new XSSFWorkbook(); // create *.xlsx file, use HSSFWorkbook() for creating *.xls file.
ISheet sheet1 = workbook.CreateSheet();
IRow row1 = sheet1.CreateRow(0);
for (int i = 0; dt.Columns.Count > i; i++)
{
row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = 0; dt.Rows.Count > i; i++)
{
IRow row = sheet1.CreateRow(i + 1);
for (int j = 0; dt.Columns.Count > j; j++)
{
row.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString());
}
}
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(ms);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = string.Format("{0}.xlsx", dt.TableName);
return result;
}
我設置一個斷點檢查workbook.Write(ms)
的ms.Length
之後,但它返回一個例外:System.ObjectDisposedException
。
我哪裏錯了?
NPOI的xlsx變體可以做到這一點,而另一種做不到。這只是圖書館的一個奇怪的東西,它有點糟糕。您可以通過執行ms.ToArray()並將其添加到新的MemoryStream中來解決此問題,但這有點令人傷心和浪費。 – alun
@alun謝謝你,它的工作原理!但是,像你說的那樣真的很浪費......我會將它標記爲一種工作,並且看看它是否可以在未來得到解決。再次感謝你。 – fankt
@alun謝謝。我使用的是生成xlsx的stream.getbuffer(),但在MS Excel中給出了「...損壞的數據..」消息。將stream.getbuffer更改爲ms.ToArray()修復了問題。 – maddog