[英]Empty Worksheet - Microsoft.Office.Interop.Excel
I've been struggling with this for a while now. 我已经为此苦了一段时间了。 I am using Microsoft.Office.Interop.Excel and I try to do the following: 我正在使用Microsoft.Office.Interop.Excel,并且尝试执行以下操作:
I have a template that I made in Excel with 4 Worksheets. 我有一个用4个工作表在Excel中制作的模板。 When I try to fill the worksheets there is always one worksheet that is empty, even though when debugging I can see that the right Worksheet has been selected and each Range object is given a value without any errors. 当我尝试填充工作表时,总是有一个空的工作表,即使在调试时我可以看到已选择了正确的工作表,并且为每个Range对象提供了一个没有错误的值。
In this method there are 2 iterations. 在此方法中,有2次迭代。 If I comment out one of the iterations the other iteration works perfectly. 如果我注释掉其中一个迭代,则另一个迭代效果很好。 So basically I always end up with one blank worksheet. 所以基本上我总是得到一个空白工作表。
Any Idea where I go wrong?? 知道我哪里出错了吗?
Thank you in advance! 先感谢您!
public void generateReport()
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
Excel.Range range;
int row = 3;
xlApp = new Excel.Application();
if (xlApp == null)
{
MessageBox.Show("Kon Excel niet starten, kijk uw softwareinstelling na !");
return;
}
string workbookPath = Path.Combine(Environment.CurrentDirectory, @"..\report.xlsx");
xlWorkBook = xlApp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
ArrayList dossiers = DossierDao.Instance.getDossiers("SELECT * FROM dossier ORDER BY referentie;");
foreach (Object o in dossiers)
{
File f = (File)o;
range = xlWorkSheet.get_Range("A" + row);
range.Value = d.Reference;
range = xlWorkSheet.get_Range("B" + row);
range.Value = d.Info;
row++;
}
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);
ArrayList facturen = FactuurDao.Instance.getAllFacturen();
foreach (Object o in facturen)
{
Invoice i = (Invoice)o;
range = xlWorkSheet.get_Range("A" + row);
range.Value = f.InvoiceNumber;
range = xlWorkSheet.get_Range("B" + row);
range.Value = f.Amount;
row++;
}
try
{
xlApp.Visible = true;
}
catch
//...
}
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
releaseObject(xlWorkSheet);
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
}
You're not reinitializing row
between processing the dossiers and the facturen. 您无需在处理档案和工厂之间重新初始化row
。 So, if you have 50 dossiers, on rows 3 through 52, then the code will start putting the facturen on row 53 of the next worksheet. 因此,如果在第3到52行上有50个卷宗,那么代码将开始将工厂放置在下一个工作表的第53行上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.