1

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

Rajneesh
  • 2,185
  • 4
  • 20
  • 30
  • what do you mean by **not getting the exact excel**? – Michal Klouda Oct 15 '12 at 13:55
  • 1
    Just my gut feeling, but does writing `xlWorkSheet` to the response actually do anything? At best I can see it sending the `.ToString()` of the object, not the contents of the object. You probably want to try and save the work book into a memory stream, and send that instead – freefaller Oct 15 '12 at 14:02

1 Answers1

6
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)