简体   繁体   中英

How to download Excel object in ASP.Net

Please consider this code:

Microsoft.Office.Interop.Excel.Application objApp;
    Microsoft.Office.Interop.Excel._Workbook objBook;
    Microsoft.Office.Interop.Excel.Workbooks objBooks;
    Microsoft.Office.Interop.Excel.Sheets objSheets;
    Microsoft.Office.Interop.Excel._Worksheet objSheet;
    Microsoft.Office.Interop.Excel.Range range;

    int ColumnsCount = dt.Columns.Count;
    int RowsCount = dt.Rows.Count;

    objApp = new Microsoft.Office.Interop.Excel.Application();
    objBooks = objApp.Workbooks;
    objBook = objBooks.Add(System.Reflection.Missing.Value);
    objSheets = objBook.Worksheets;
    objSheet = (Microsoft.Office.Interop.Excel._Worksheet)objSheets.get_Item(1);

    for (int i = 1; i < ColumnsCount + 1; i++)
    {
        objSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
    }

    range = objSheet.get_Range("A2", System.Reflection.Missing.Value);
    range = range.get_Resize(RowsCount, ColumnsCount);

    string[,] saRet = new string[RowsCount, ColumnsCount];

    for (int iRow = 0; iRow < RowsCount; iRow++)
    {
        for (int iCol = 0; iCol < ColumnsCount; iCol++)
        {
            saRet[iRow, iCol] = dt.Rows[iRow][iCol].ToString();
        }
    }

    //Set the range value to the array.
    range.set_Value(Missing.Value, saRet);

I want to download Excel object that I created. The problem is Microsoft.Office.Interop.Excel._Workbook is not serializable and until I save it I can't access Excel file. How I can download Excel that created in memory?

thanks

This seems like one of the many problems related to Microsoft KB: Considerations for server-side Automation of Office . Using Excel Interop server-side isn't supported.

I'd recommend you export csv files or look into OpenXML or the easier version ClosedXML to generate xslx files on the server.

See the other methods in this MSDN guide: How To Asp.Net Export Excel

您的工作簿上应该有一个SaveAs方法,可用于另存为xls文件。

objBook.SaveAs("my-workbook.xls");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM