I'm having a little bit of a trouble doing this task, I'm using MVC 4 and I have the following code:
//I'll use this to return the byte array to a view as a download
//Not mine, got this code from a post here at stackoverflow
public class BinaryContentResult : ActionResult
{
public string ContentType { get; set; }
public string FileName { get; set; }
public byte[] Content { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.ClearContent();
context.HttpContext.Response.ContentType = ContentType;
context.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
context.HttpContext.Response.BinaryWrite(Content);
context.HttpContext.Response.End();
}
}
And I have this method at my controller:
using System.Data;
using System.IO;
using System.Web.Mvc;
using Excel = Microsoft.Office.Interop.Excel;
public ActionResult Download()
{
DataTable dt = GetDataTableWithMyData;
dt.TableName = "mytable";
var wsheet = GetExcel(dt);
var mstream = new MemoryStream();
var swriter = new StreamWriter(mstream);
swriter.Write(wsheet);
return new BinaryContentResult
{
FileName = "test1.xls",
ContentType = "application/vnd.ms-excel",
Content = mstream.ToArray()
};
}
And the GetExcel method:
public static Excel._Worksheet GetExcel(DataTable Tbl)
{
// load excel, and create a new workbook
Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;
// column headings
for (int i = 0; i < Tbl.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = Tbl.Columns[i].ColumnName;
}
// rows
for (int i = 0; i < Tbl.Rows.Count; i++)
{
for (int j = 0; j < Tbl.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = Tbl.Rows[i][j];
}
}
return workSheet;
}
It gives the file to download but it returns a corrupted and empty xls file... What could I be doing wrong, or could someone show another way to do it?