我创建了一个程序来自动填写发票excel文件,以便以后可以打印。我能够填充单元格并格式化它们。但是excel进程仍然在后台运行。
TypeError: Type error
我无法从后台杀死excel进程。我不确定我做错了什么。上面的代码是我为自动化excel所做的全部工作。请帮助我。
答案 0 :(得分:1)
我所做的是为Excel对象使用Initializer和Deinitializer,如下所示:
private void InitializeExcelObjects()
{
_xlApp = new Excel.Application
{
SheetsInNewWorkbook = 2,
StandardFont = "Tahoma",
StandardFontSize = 11
};
_xlBook = _xlApp.Workbooks.Add(Type.Missing);
_xlApp.Windows.Application.ActiveWindow.DisplayGridlines = false;
_xlSheets = _xlBook.Worksheets;
_xlSheet = (Excel.Worksheet)_xlSheets.Item[1];
_xlSheetDelPerf = (Excel.Worksheet)_xlSheets.Item[2];
}
private void DeinitializeExcelObjects()
{
Marshal.ReleaseComObject(_xlSheet);
Marshal.ReleaseComObject(_xlSheetDelPerf);
Marshal.ReleaseComObject(_xlSheets);
_xlBook.Close(false, null, null);
Marshal.ReleaseComObject(_xlBook);
_xlApp.DisplayAlerts = false;
_xlApp.Quit();
Marshal.ReleaseComObject(_xlApp);
_xlApp = null;
}
他们被这样称呼:
public void GenerateDuckbilledPlatypusRpt()
{
try
{
InitializeExcelObjects();
. . . // all the Excel generation code goes here
}
finally
{
DeinitializeExcelObjects();
}
}
IOW,我认为您可以将代码更改为以下内容:
public void Write(tbl_Sale sale,List<SalesModel> saleCollection)
{
Mouse.SetCursor(Cursors.Wait);
Excel.Application application = null;
Workbook workbook = null;
Worksheet inputSheet = null;
Range range = null;
try
{
. . .
InitializeExcelObjects();
. . .
}
finally
{
DeinitializeExcelObjects();
Mouse.SetCursor(Cursors.Arrow);
}
}
private void InitializeExcelObjects()
{
application = new Excel.Application();
workbook = application.Workbooks.Add(Type.Missing);
sheets = workbook.Worksheets;
inputSheet = (Excel.Worksheet)sheets.Item[1];
}
private void DeinitializeExcelObjects()
{
Marshal.ReleaseComObject(inputSheet);
Marshal.ReleaseComObject(sheets);
workbook.Close(false, null, null);
Marshal.ReleaseComObject(workbook);
application.DisplayAlerts = false;
application.Quit();
Marshal.ReleaseComObject(application);
application = null;
}
对我有用; YMMV
答案 1 :(得分:1)
看到这个答案: How do I properly clean up Excel interop objects?
您正在使用releaseObject(application)
,但这似乎指的是您没有显示的某种方法。不知道那里有什么代码。
除了注意链接问题中的注意事项外,请尝试使用Marshal.ReleaseComObject(application)
。