我正在尝试在代码隐藏中创建一个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文件
答案 0 :(得分: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)