0

i've written this code which will generate an excel spreadsheet and save it to a specified location. I want to then display a "Save as" dialogue box by reading the file from the stored location and then asking then user where they want to store it.

Excel.Application excelApp = null;
            Excel.Workbook wb = null;
            Excel.Worksheet ws = null;
            Excel.Range range = null;

excelApp = new Excel.Application();
            wb = excelApp.Workbooks.Add();
            ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;

for(int i = 0; i< 10;++i) {
    ws.Cells[i, 1] = i+
}

wb.SaveAs(@"C:\test.xls", Excel.XlFileFormat.xlWorkbookNormal);
wb.Close(true);
excelApp.Quit();

How to download in the following format?

string str = "Hello, world"; 

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str); 

return File(bytes, "text/plain"); 
RB.
  • 36,301
  • 12
  • 91
  • 131
user2143331
  • 1
  • 1
  • 1
  • Please read [this question](http://stackoverflow.com/questions/974079/setting-mime-type-for-excel-document) for a discussion on the correct MIME type to use - `text/plain` is not correct for an Excel document. – RB. Mar 07 '13 at 09:24

1 Answers1

0

Given that is an Excel doc saved at c:\temp\excelDoc.xls and given that you have a WebForm that has a link like this

<asp:LinkButton runat="server" ID="GetExcel" OnClick="GetExcel_Click">Download</asp:LinkButton>

In your code-behind you can read the file from disk and send to the user by something like this

    protected void GetExcel_Click(object sender, EventArgs e)
    {
        var fileName = "excelDoc.xls";
        using (var cs = new FileStream(@"c:\temp\" + fileName, FileMode.Open))
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/vnd.ms-excel";


            byte[] buffer = new byte[32768];
            int read;
            while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
            {
                Response.OutputStream.Write(buffer, 0, read);
            }

            Response.End();
            Response.Flush();
        }
    }
Community
  • 1
  • 1
Joe
  • 5,389
  • 7
  • 41
  • 63