我有生成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
}
现在问题是当我们运行此代码时,一切正常。但有时会发生什么,在客户端,没有生成其中一个工作表名称,它会跳过。所以我们对它们的解决方案是尝试再次生成工作表然后它工作正常, 所以我的问题是为什么代码跳过sheetName(有时),尽管代码中没有问题。是否必须对客户端的其他正在运行的进程执行任何操作?
答案 0 :(得分:0)
试试这个:
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();