简体   繁体   中英

How to send an excel workbook as an response?

I am trying to create an excel sheet in a code-behind and then download it. I don't want to save the file on the disk, I want to directly send it as a response, I tried the following code. But im not getting the exact excel.

Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;


            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            for (int i = 1; i <= 100; i++)
                for (int j = 1; j < 100; j++)
                    xlWorkSheet.Cells[i, j] = i + "  : " + j;

            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=translationText.xls");
            this.EnableViewState = false;
            Response.Write(xlWorkSheet);
            Response.End();

            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);

How to send the excel worksheet object as the response. So, that user will be prompted to download the excel file

Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=translationText.xls");
Response.Write("<table>");
for (int i = 1; i <= 100; i++)
{
    Response.Write("<tr>");
    for (int j = 1; j < 100; j++)
    {
        Response.Write("<td>"+i + "  : " + j+"</td>");            
    }
    Response.Write("</tr>");
}
Response.Write("</table>");
Response.Flush();
Response.End();

try the above code, you dont need to create an excel object here, if you are reading from an excel and then writing it is different code.

well the different code to read and write the excel file to the browser is by

Response.BinaryWrite(yourexcelstream)

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