部署.net C#MVC应用程序后保存/打开文件出错

时间:2013-08-30 05:23:21

标签: c# asp.net-mvc excel

在我的MVC应用程序中,我使用Microsoft.Office.Interop.Excel将数据导出到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); 
            }

}

2 个答案:

答案 0 :(得分:0)

IIS用户帐户必须具有写入文件的权限。

在以下文章How to Create Excel file in ASP.NET C#

中搜索0x800A03EC

答案 1 :(得分:0)

HRESULT:0x800A03EC是一个未知(对VB.Net)COM错误。这通常发生在Excel抛出一些错误,因为您的输入或参数错误。如果您在Excel VBA中尝试代码,通常可以更容易地找出问题。