这似乎是我的逻辑错误。但是如何?这对我来说似乎是好的。我究竟做错了什么?表单已创建。但整个内容都在第一张纸上。 我甚至记得有一次硬编码.get_Item(2),它写在第二张纸上,为什么不现在呢?C#和Excel:写在多张纸上,它总是写在第一张?
public void createXls()
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
Console.WriteLine("Excel is not properly installed!!");
return;
}
object misValue = System.Reflection.Missing.Value;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
for (int z = 1; z <= Sheets.Count; z++)
{
if (z > 1) xlWorkBook.Worksheets.Add(misValue, misValue, 1, misValue);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(z);
Console.WriteLine("We are writing on sheet #" + z); // it says ...1, 2, 3, 4, 5
for (int y = 1; y <= Sheets[z - 1].Count; y++)
{
int x = 1;
foreach (var Column in Sheets[z - 1][y - 1])
{
xlWorkSheet.Cells[y, x] = Column.Value;
x++;
}
}
releaseObject(xlWorkSheet);
}
xlWorkBook.SaveAs("\\\\psf\\Home\\Desktop\\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
Console.WriteLine("Exception Occured while releasing object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
我可能是盲人,Sheets'定义在哪里? –