excel - passing a workbook Name into a For Loop C# -


so doing few loops iterate through different variable changes imported template, sql script run, data dumped, loop next sql script, etc, , done multiple times using same template file (which @ end of query dumps saved new file. background:

i need able open template first time through loop, keep open through each query dump until done. don't want keep reopening file big , cumbersome have far:

public void exporttoexcel(dataset dataset, string templatepath)     {         excel.application excelapp = new excel.application();         excelapp.visible = true;         fileinfo excelfileinfo = new fileinfo(templatepath);         boolean fileopentest = isfilelocked(excelfileinfo);          if (!fileopentest)         {             excel.workbook templatebook = excelapp.workbooks.open(templatepath);         }         else         {             excel.workbook templatebook = excelapp.workbooks[templatepath];         }          (int = 0; < lstquerydumpsheet.items.count; i++)         {                  string tabname = lstquerydumpsheet.items[i].tostring();             excel.worksheet templatesheet = templatebook.sheets[tabname];              // copy datatable             foreach (system.data.datatable dt in dataset.tables)             { ... rest of loops... 

my problem code line "excel.worksheet templatesheet = templatebook.sheets[tabname];" tells me "templatebook" not assigned, assigning outside if statement should pass....right?

this problem of scope. code:

if (!fileopentest) {     excel.workbook templatebook = excelapp.workbooks.open(templatepath); } else {     excel.workbook templatebook = excelapp.workbooks[templatepath]; } 

declares templatebook variable inside blocks , scope limited within block. have variable persist outside of blocks need declare outside this:

excel.workbook templatebook; if (!fileopentest) {     templatebook = excelapp.workbooks.open(templatepath); } else {     templatebook = excelapp.workbooks[templatepath]; } 

Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -