在我的 MVC 应用程序中,我使用Microsoft.Office.Interop.Excel
.
我还启用ASP.NET Impersonation
并提供了身份验证详细信息。它将数据写入excel,但不保存或打开excel文件。它抛出一个异常Exception from HRESULT: 0x800A03EC
。如果有人可以提供帮助,我会很高兴。提前致谢。
我的导出代码是:
public static void ExportExcel(this DataTable Tbl, string ExcelFilePath = null)
{
ExcelFilePath = "ExportTable.xls";
try
{
if (Tbl == null || Tbl.Columns.Count == 0)
//throw new Exception("ExportToExcel: Null or empty input table!\n");
Console.WriteLine("ExportToExcel: Null or empty input table!\n");
// load excel, and create a new workbook
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
workSheet.Cells[1, (i + 1)].Font.Bold = true;
workSheet.Cells[1, (i + 1)].Font.Size = 12;
}
// rows
for (int i = 0; i < Tbl.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < Tbl.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
}
}
// works fine till here
// check fielpath
if (ExcelFilePath != null && ExcelFilePath != "")
{
try
{
workSheet.SaveAs(ExcelFilePath);
excelApp.Quit();
}
catch (Exception ex)
{
Console.WriteLine("ExportToExcel: Excel file could not be saved! Check filepath.\n"+ ex.Message);
}
}
else // no filepath is given
{
excelApp.Visible = true;
}
}
catch (Exception ex)
{
Console.WriteLine("ExportToExcel: \n" + ex.Message);
}
}