c# - Tow to add a new worksheet to Excel with interop -
i can create excel 2 worksheets, , can write datatable's data sheet 1 , want write same data sheet 2 sheet 2 seems blank. why "sheet 2" blank?
here code:
microsoft.office.interop.excel.application xlapp = new microsoft.office.interop.excel.application(); if (xlapp == null) { console.writeline("excel not started. check office installation , project references correct."); return; } xlapp.visible = true; microsoft.office.interop.excel.workbook wb = xlapp.workbooks.add(microsoft.office.interop.excel.xlwbatemplate.xlwbatworksheet); microsoft.office.interop.excel.worksheet ws = (microsoft.office.interop.excel.worksheet)wb.worksheets[1]; { if (ws == null) { console.writeline("worksheet not created. check office installation , project references correct."); } microsoft.office.interop.excel.range arange = ws2.get_range("c1", "c7"); (int = 0; < main_dt.columns.count; i++) { ws.cells[1, + 1] = main_dt.columns[i].columnname; arange = (microsoft.office.interop.excel.range)ws.cells[1, + 1]; arange.interior.colorindex = 15; arange.font.bold = true; } (int r = 0; r < main_dt.rows.count; r++) { (int = 0; < main_dt.columns.count; i++) { ws.cells[r + 2, + 1] = main_dt.rows[r][i].tostring(); } } } // worksheet 2 ****************** wb.sheets.add(); microsoft.office.interop.excel.worksheet ws2 = (microsoft.office.interop.excel.worksheet)wb.worksheets[2]; { if (ws2 == null) { console.writeline("worksheet not created. check office installation , project references correct."); } microsoft.office.interop.excel.range arange = ws2.get_range("c1", "c7"); (int = 0; < main_dt.columns.count; i++) { ws2.cells[1, + 1] = main_dt.columns[i].columnname; arange = (microsoft.office.interop.excel.range)ws2.cells[1, + 1]; arange.interior.colorindex = 15; arange.font.bold = true; } (int r = 0; r < main_dt.rows.count; r++) { (int = 0; < main_dt.columns.count; i++) { ws2.cells[r + 2, + 1] = main_dt.rows[r][i].tostring(); } } }
instead of:
wb.sheets.add(); microsoft.office.interop.excel.worksheet ws2 = (microsoft.office.interop.excel.worksheet)wb.worksheets[2];
try:
microsoft.office.interop.excel.worksheet ws2 = (microsoft.office.interop.excel.worksheet)wb.sheets.add();
Comments
Post a Comment