[ACCEPTED]-Download .xlsx file using Response.TransmitFile()-mime-types

Accepted answer
Score: 18

I can't definitely say that there's anything 19 wrong with your approach, but I'll just 18 share some observations from doing something 17 similar.

Headers are Pascal Case, most browsers 16 shouldn't care but I would change your content-disposition 15 to Content-Disposition. Changing the Charset 14 shouldn't be necessary or relevant. Your 13 content type should be fine, I would only 12 use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 11 and .xlsx if that is actually the content 10 of the file, otherwise stick with application/vnd.ms-excel 9 and .xls.

Another thing you should consider 8 is sending the browser the Content-Length:

Response.AddHeader("Content-Length", new System.IO.FileInfo("FileName.xlsx").Length);

Also 7 have you tried this with multiple browsers? Just 6 wondering if it's a vendor-specific problem.

As 5 a last ditch effort, you can set your Content-Type 4 to application/octet-stream, and any browser 3 should offer to download it, and then most 2 browsers will let you open it after it's 1 downloaded based on the extension.

Score: 3

use this

HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"filename + ".zip" + "\"");
                Response.TransmitFile(zipPath);
                Response.Flush();
                Response.Close();
                Response.End();

in your code is

Response.AddHeader("content-disposition", "attachment;filename=\FileName.xlsx\");

0

Score: 0

Try like this

public void DataTableToExcel(DataTable dt, string Filename)
{
    MemoryStream ms = DataTableToExcelXlsx(dt, "Sheet1");
    ms.WriteTo(HttpContext.Current.Response.OutputStream);
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + Filename);
    HttpContext.Current.Response.StatusCode = 200;
    HttpContext.Current.Response.End();
}

public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
{
    MemoryStream result = new MemoryStream();
    ExcelPackage excelpack = new ExcelPackage();
    ExcelWorksheet worksheet = excelpack.Workbook.Worksheets.Add(sheetName);
    int col = 1;
    int row = 1;
    foreach (DataColumn column in table.Columns)
    {
        worksheet.Cells[row, col].Value = column.ColumnName.ToString();
        col++;
    }
    col = 1;
    row = 2;
    foreach (DataRow rw in table.Rows)
    {
        foreach (DataColumn cl in table.Columns)
        {
            if (rw[cl.ColumnName] != DBNull.Value)
                worksheet.Cells[row, col].Value = rw[cl.ColumnName].ToString();
            col++;
        }
        row++;
        col = 1;
    }
    excelpack.SaveAs(result);
    return result;
}

0

More Related questions