1

How to download an excel in a chrome browser having options as Open, Save and Cancel as I used closed Xml in C#?

public FileResult ExportToExcel(List<MyStudentList_Result> StudentList)
{
    List<string[]> titles = new List<string[]> { new string[] { "name", "Number", "Type", "syllabus", "Title", "Added" } };
    byte[] fileStream = ExportToExcel(StudentList, "StudentList", titles);
    string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AppendHeader("Content-Disposition", "inline; filename=" + "StudentList.xlsx");
    return File(fileStream, mimeType);
}

public byte[] ExportToExcel(List<MystudentList_Result> StudentList, string worksheetTitle, List<string[]> titles)
{
    var wb = new XLWorkbook(); //create workbook
    var ws = wb.Worksheets.Add(worksheetTitle); //add worksheet to workbook

    var rangeTitle = ws.Cell(1, 1).InsertData(titles); //insert titles to first row
    rangeTitle.AddToNamed("Titles");
    var titlesStyle = wb.Style;
    titlesStyle.Font.Bold = true; //font must be bold
    // titlesStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; //align text to center
    wb.NamedRanges.NamedRange("Titles").Ranges.Style = titlesStyle; //attach style to the range
    if (StudentList!= null && StudentList.Count() > 0)
    {
        //insert data to from second row on
        ws.Cell(2, 1).InsertData(StudentList);
        ws.Columns().AdjustToContents();
    }
    //save file to memory stream and return it as byte array
    using (var ms = new MemoryStream())
    {
        wb.SaveAs(ms);

        return ms.ToArray();
    }
}
Diado
  • 2,229
  • 3
  • 18
  • 21

1 Answers1

2

You can guide what the browser does with the Content-Disposition header. For saving the file you should use attachment:

Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Raidri
  • 17,258
  • 9
  • 62
  • 65