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"); 
1
  • Please read this question for a discussion on the correct MIME type to use - text/plain is not correct for an Excel document. Commented Mar 7, 2013 at 9:24

1 Answer 1

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();
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.