我创建了一个转换Excel文件的工具。当用户转换excel文件时,代码首先创建一个Excel文件。当我在我的系统上(Excel 2007)时,它没有问题。当我在使用Excel 98的系统上安装程序时,它会抛出异常。我得到的第一个例外是另一个,但也是一个HResult错误。我通过将“SaveAs”更改为“SaveCopyAs”来修复此问题。然后它被修复了!另外对于安装了Excel 98的其他系统,但现在我有另一个HResult错误。这有什么问题:
_savePath = sfd.FileName;
MessageBox.Show("GOOD1");
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
MessageBox.Show("GOOD2");
// The exception is here on the workbook
// HResult 8x00010105 (COMException)
Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Add(Missing.Value);
MessageBox.Show("GOOD3");
workbook.SaveCopyAs(_savePath);
MessageBox.Show("GOOD4");
lblSavePath.Text = _savePath;
workbook.Close(false, _savePath, Type.Missing);
excelApp.Quit();
我希望有人可以帮我解决这个问题。
谢谢,
杰米
答案 0 :(得分:1)
您可以尝试:
_savePath = sfd.FileName;
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
MessageBox.Show("GOOD2");
excelApp.SheetsInNewWorkbook = 1;
try
{
// Must be surrounded by try catch to work.
excelApp.Visible = true;
}
catch (Exception e)
{
Console.WriteLine("-------Error hiding the application-------");
Console.WriteLine("Occured error might be: " + e.StackTrace);
}
Microsoft.Office.Interop.Excel.Workbook workbook
workbook = excelApp.Workbooks.Open("your excel file", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // if working with another excel
excelApp.Workbooks.Add();
MessageBox.Show("GOOD3");
Excel.Worksheet sheetC = excelApp.Sheets.get_Item(1);
sheetC.Name = "name-of-sheet";
workbook.SaveCopyAs(_savePath); // SaveAs should work actually.
workbook.Close();
excelApp.Quit();
我拿了你的解决方案并修改了 Missing.Value 部分,这是不正确的。另外,您不需要为 workbook.Close 提供参数。 解决方案:I want to add only one sheet after creating an Excel workbook through C#
答案 1 :(得分:0)
也许在没有excelApp.Quit();
行的情况下尝试使用您的代码。
仅当您不打算再次使用 excelApp 对象时才使用excelApp.Quit();
功能。