简体   繁体   English

如何发送Excel工作簿作为答复?

[英]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. 我正在尝试在代码隐藏区中创建一个Excel工作表,然后将其下载。 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. 如何发送excel工作表对象作为响应。 So, that user will be prompted to download the excel file 因此,系统将提示该用户下载excel文件

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. 尝试上面的代码,如果您正在从excel中读取内容,然后编写它,则无需在此处创建excel对象。

well the different code to read and write the excel file to the browser is by 很好的不同的代码来读取和写入excel文件到浏览器是

Response.BinaryWrite(yourexcelstream)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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