简体   繁体   中英

Error while generating excel from C#

I have simple code for generating Excel which loops and produces excel sheet.

        Excel.Application XlApp = null;
        Excel.Workbook workbook = null;
        Excel.Worksheet Ws = null;

        XlApp = new Excel.Application();
        XlApp.Visible = true;
        workbook = XlApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
        Ws = (Excel.Worksheet)workbook.Worksheets[1];

        workbook.Worksheets.Add(Missing.Value,Missing.Value,  
        6, Missing.Value);

        for (int j = 0; j < 7; j++)
        {
             Ws = (Excel.Worksheet)workbook.Worksheets[j];
             Ws.Activate();
             Ws.Name = SheetName.ToString();//Sheetname has a Name 
        }

Now the problem is When we run this code everything works fine. But sometimes what happens is, at the client side one of the sheet name is not generated it skips. So our solution to them is to try generating the sheet again and then it works fine, So my question is why does the code skip the sheetName ( sometimes ), although there is no problem in the code. Does it have to do anything with clients other running processes?

Try this:

Excel.Application XlApp = null;
Excel.Workbook workbook = null;
Excel.Worksheet Ws = null;

XlApp = new Excel.Application();
XlApp.Visible = true;
workbook = XlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

// here you get the first ws, index 1
Ws = (Excel.Worksheet)workbook.Worksheets[1];

workbook.Worksheets.Add(Missing.Value, Missing.Value,
6, Missing.Value);

var SheetName = "sheet_";
// here you should start from 1 (not from 0) and include 7 in the loop count
for (int j = 1; j <= 7; j++)
{
    // make sure that the ws name is unique
    SheetName=String.Format("sheet_{0}",j);
    Ws = (Excel.Worksheet)workbook.Worksheets[j];
    Ws.Activate();
    Ws.Name = SheetName;// this is already a string
}

XlApp.Quit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM