0

我正在尝试在代码隐藏中创建一个 excel 表,然后下载它。我不想将文件保存在磁盘上,我想直接将其作为响应发送,我尝试了以下代码。但我没有得到确切的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);

如何将 excel 工作表对象作为响应发送。因此,将提示该用户下载 excel 文件

4

1 回答 1

5
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();

试试上面的代码,你不需要在这里创建一个 excel 对象,如果你从一个 excel 中读取然后编写它是不同的代码。

那么读取和写入excel文件到浏览器的不同代码是

Response.BinaryWrite(yourexcelstream)
于 2012-10-15T13:59:57.170 回答