简体   繁体   English

从C#生成excel时出错

[英]Error while generating excel from C#

I have simple code for generating Excel which loops and produces excel sheet. 我有简单的代码生成Excel循环和生成excel表。

        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. 因此我们对它们的解决方案是尝试再次生成工作表然后它工作正常,所以我的问题是为什么代码跳过sheetName( 有时 ),尽管代码中没有问题。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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