How to append datagridview to excel file using c# -
i trying export datagridview contents excel file exist in application.startuppath. problem facing whenever export grid content excel, overwrites previous content. append excel file , not overwrite existing content.
here code:
microsoft.office.interop.excel._application app = new microsoft.office.interop.excel.application(); microsoft.office.interop.excel._workbook workbook = app.workbooks.open(application.startuppath+"excelfile.xls"); microsoft.office.interop.excel._worksheet worksheet = null; app.visible = false; worksheet = workbook.sheets["sheet1"]; worksheet = workbook.activesheet; (int = 0; < datagridview1.rows.count - 1; i++) { (int j = 0; j < datagridview1.columns.count; j++) { if (datagridview1.rows[i].cells[j].value != null) worksheet.cells[i + 2, j + 1] = datagridview1.rows[i].cells[j].value.tostring(); else worksheet.cells[i + 2, j + 1] = ""; } } workbook.close(savechanges: true); app.quit(); edit: updated code : @alex bell
int _offset = worksheet.usedrange.rows.count; (int = 0; < datagridview1.rows.count - 1; i++) { (int j = 1; j < datagridview1.columns.count; j++) { if (datagridview1.rows[i].cells[j].value != null) worksheet.cells[i + 2 + _offset, j + 1] = datagridview1.rows[i].cells[j].value.tostring(); else worksheet.cells[i + 2 + _offset, j + 1] = ""; } } resolved problem of appending data small problem every time update leaves blank row between old rows , new rows.
pertinent case, may use int _offset = worksheet.usedrange.rows.count row offset in loop:
for (int = 0; < datagridview1.rows.count - 1; i++) { (int j = 0; j < datagridview1.columns.count; j++) { if (datagridview1.rows[i].cells[j].value != null) worksheet.cells[i + 2 + _offset, j + 1] = datagridview1.rows[i].cells[j].value.tostring(); else worksheet.cells[i + 2 + _offset, j + 1] = ""; } }
hope help. regards,
Comments
Post a Comment