我正在尝试通过C#保存excel文件,但该文件未保存在我使用变量指定的位置。以下是我的代码:
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
//MessageBox.Show("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
if (!System.IO.File.Exists(FileName))
{
xlWorkBook = xlApp.Workbooks.Add(misValue);
}
else
{
xlWorkBook = xlApp.Workbooks.Open(FileName, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", true, false, 0, true, 1, 0);
}
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//一些代码
xlApp.DisplayAlerts = false;
xlWorkBook.SaveAs(FileName, Type.Missing,Type.Missing,Type.Missing,false,Type.Missing,XlSaveAsAccessMode.xlExclusive,Type.Missing,Type.Missing,Type.Missing);
xlWorkBook.Close(true, FileName, misValue);
xlApp.Application.Quit();
xlApp.Quit();
我在这里做错了什么?我感到非常沮丧,不能保存在我想要的地方。任何帮助将不胜感激
答案 0 :(得分:0)
根据@mohammedlok关于确保没有内存泄漏的评论,我总是使用try-catch-finally方法来确保excel进程无论如何都会一直关闭。 下面的示例代码对我有用:
Application excelApp = new Application();
Workbook excelWorkbook = null;
string excelFilePath = "C:\\Users\\Desktop\\Sample.xlsx";
try
{
//Create a workbook
excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
//Make and name a worksheet
activeWorksheet = excelWorkbook.ActiveSheet;
//Write in cell B3 of the worksheet
Range r = activeWorksheet.get_Range("B3", Type.Missing);
r.Value2 = "This is a sample.";
//Save the workbook
excelWorkbook.SaveAs(excelFilePath, Type.Missing, Type.Missing, Type.Missing, false, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (excelWorkbook != null)
{
excelApp.Calculation = XlCalculation.xlCalculationAutomatic;
excelApp.DisplayAlerts = false;
excelWorkbook.RefreshAll();
excelWorkbook.Close(true, excelFilePath);
excelApp.Quit();
}
}