c# - MemoryStream seems be closed after NPOI workbook.write? -
i using npoi convert datatable excel in asp.net web api project.
but got nothing response. here's code:
public httpresponsemessage getexcelfromdatatable(datatable dt) { iworkbook workbook = new xssfworkbook(); // create *.xlsx file, use hssfworkbook() creating *.xls file. isheet sheet1 = workbook.createsheet(); irow row1 = sheet1.createrow(0); (int = 0; dt.columns.count > i; i++) { row1.createcell(i).setcellvalue(dt.columns[i].columnname); } (int = 0; dt.rows.count > i; i++) { irow row = sheet1.createrow(i + 1); (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; }
i set break point inspect ms.length
after workbook.write(ms)
, return exception : system.objectdisposedexception
.
where did go wrong?
another workaround issue...which doesn't use multiple memorystream
objects.
create npoimemorystream
class inherits memorystream
, , overrides close
method:
public class npoimemorystream : memorystream { public npoimemorystream() { allowclose = true; } public bool allowclose { get; set; } public override void close() { if (allowclose) base.close(); } }
then, use stream this:
var ms = new npoimemorystream(); ms.allowclose = false; workbook.write(ms); ms.flush(); ms.seek(0, seekorigin.begin); ms.allowclose = true;
at point between flush , seek, npoi attempt close stream, since overrode close()
, allowclose
flag false, can keep stream open. then, set allowclose
true normal disposal mechanisms can close it.
don't me wrong...this still hack shouldn't need implemented...but it's bit cleaner memory usage standpoint.
Comments
Post a Comment