【问题标题】:How to send an excel workbook as an response?如何发送 Excel 工作簿作为响应?
【发布时间】:2012-10-15 21:59:57
【问题描述】:

我正在尝试在代码隐藏中创建一个 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 文件

【问题讨论】:

  • 你说的没有得到准确的excel是什么意思
  • 只是我的直觉,但是在回复中写xlWorkSheet 真的有什么作用吗?充其量我可以看到它发送对象的.ToString(),而不是对象的内容。您可能想尝试将工作簿保存到内存流中,然后将其发送

标签: c# asp.net excel excel-2007


【解决方案1】:
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)

【讨论】:

  • 是的,我知道这种方法。但我也想对单元格进行格式化,所以我想我只能选择 excel
  • 您在寻找什么样的格式?如果它只是样式,那么您可以使用 td(cell) 的 css 属性
  • 你能告诉我如何从我创建的 xlWorkSheet 对象中获取字节数组吗?
  • 看看这个stackoverflow.com/questions/8201774/…,请明天再来,把我的答案标记为正确,因为我今天已经获得了足够的积分!
猜你喜欢
  • 2014-04-05
  • 1970-01-01
  • 2015-09-07
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-01
  • 1970-01-01
相关资源
最近更新 更多