我想知道是否有一种方法可以获取 Web 浏览器控件的内容并将其保存为可以在 Excel 中打开的格式?目前,我有一个应用程序从用户那里获取数据并将其转换为表格并在 WPF Web 浏览器控件中以 html 格式显示。我可以成功将此控件内容导出为 PDF 文档,如下所示:
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";
File.WriteAllText(fileName, generateHtml());
//Creates a new instance of the Microsoft office interop for using MS Word
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
app.Visible = false;
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open(fileName);
doc.SaveAs("C:\\Temp\\testExport.pdf", 17);
app.Quit();
这对于导出 PDF 文件效果很好,我遇到的问题是我无法终生使用 Excel 文件。到目前为止,我正在尝试这样做:
string filePath = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";
File.WriteAllText(filePath, generateHtml());
//Creates a new instance of Microsoft office interop for using MS Excel
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Create a new instance of a workbook
Microsoft.Office.Interop.Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();
//Don't Show MS Excel
excelApp.Visible = false;
//Open a file at location
Microsoft.Office.Interop.Excel.Workbook excelWorkBook2 = excelApp.Workbooks.Open(filePath);
//Convert that file to an XLSX document
excelWorkBook2.SaveAs("C:\\Temp\\testExport.xlsx", Microsoft.Office.Interop.Excel.XlFileFormat.xlXMLSpreadsheet, Missing.Value, Missing.Value, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
//Close excel
excelApp.Quit();
但是,当我尝试打开生成的文件时,出现以下错误: