Bill Software Engineer
Bill Software Engineer

Reputation: 7782

How do I send Excel file created in Interop to browser in Razor MVC?

So here is my code for generating the excel file in C# and Interop:

         Dictionary<Item, Shift_ItemSales> data = getData(curPage, depID);

         Application excelapp = new Application();
         excelapp.Visible = false;

         _Workbook workbook = (_Workbook)(excelapp.Workbooks.Add(Type.Missing));
         _Worksheet worksheet = (_Worksheet)workbook.ActiveSheet;

         worksheet.Cells[0, 1] = "ID";
         worksheet.Cells[0, 2] = "Description";

         int row = 1;
         foreach (Item curItem in data.Keys) {
             Shift_ItemSales curIS = data[curItem];
             worksheet.Cells[row, 0] = curItem.ID;
             worksheet.Cells[row, 1] = curItem.Description;
             row++;
         }

How do I send it to the browser and have the user download it?

Upvotes: 3

Views: 2482

Answers (1)

Bhushan Firake
Bhushan Firake

Reputation: 9448

You should use FileResult for this purpose.

    [HttpPost]
    public FileResult ExcelDownload(ReportDownloadRequest reportRequest)
    {
           //Code to generate Excel file with GemBox.Spreadsheet

           return new FileStreamResult(report, "application/ms-excel")
           {
               FileDownloadName = "SalesReport.xls"
           };
    }

For Excel sheets, you can use GemBox.Spreadsheet Free version delivers the same performance and set of features as the Professional version. However, the following limitations are imposed:

  • Maximum number of rows per sheet is 150.
  • Maximum number of sheets per workbook is 5.

GemSheet Sample Code:

 // Set license key to use GemBox.Spreadsheet in a Free mode.
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

// Create new empty Excel file.
var workbook = new ExcelFile();

// Create new worksheet and set cell A1 value to 'Hello world!'.
workbook.Worksheets.Add("Test").Cells["A1"].Value = "Hello world!";

// Save to XLSX file.
workbook.Save("Test.xlsx");

Upvotes: 3

Related Questions