excel - C# Open XML SDK write data at specific cell reference -
i have excel sheet cell changed cell reference.
with code, can load excel sheet , load data it. want data begin insert @ specific cell "int_startdok".
my code:
private byte[] loaddatatofile([notnull] datatable datatable) { if (datatable == null) throw new argumentnullexception(nameof(datatable)); var memorystream = new memorystream(); var bytearray = file.readallbytes(templatefilepath); memorystream.write(bytearray, 0, bytearray.length); using (var spreadsheetdocument = spreadsheetdocument.open(memorystream, true)) { var workbookpart = spreadsheetdocument.workbookpart; var worksheetpart = workbookpart.worksheetparts.first(); var sheetdata = worksheetpart.worksheet.elements<sheetdata>().first(); var headerrow = new row(); var columns = new list<string>(); foreach (datacolumn column in datatable.columns) { columns.add(column.columnname); var cell = new cell(); cell.datatype = cellvalues.string; cell.cellvalue = new cellvalue(column.columnname); headerrow.appendchild(cell); } foreach (datarow dsrow in datatable.rows) { var newrow = new row(); foreach (var col in columns) { var cell = new cell(); cell.datatype = cellvalues.string; cell.cellvalue = new cellvalue(dsrow[col].tostring()); newrow.appendchild(cell); } sheetdata.appendchild(newrow); } } return memorystream.toarray(); }
how can this?
i got solution problem. closedxml trick easy , reduce code. closedxml need open xml sdk. can closedxml wiki page.
here solution:
private byte[] insertdatatotemplate([notnull] datatable datatable) { if (datatable == null) throw new argumentnullexception(nameof(datatable)); // create memorystream template var memorystream = new memorystream(); var bytearray = file.readallbytes(templatefilepath); memorystream.write(bytearray, 0, bytearray.length); using (var workbook = new xlworkbook(memorystream)) { var sheetdata = workbook.worksheets.first(); sheetdata.cell("int_startdok").insertdata(datatable.rows); workbook.save(); } return memorystream.toarray(); }
Comments
Post a Comment