Reputation: 879
I have asp.net MVC app in c# and I get query results(from Entity Framework) and I need to put the data in Excel sheet which user can download. So this is what I am trying to do and I want to know how to write each row of data into excel sheet? Any other approach I should take is welcome too.
var certs = CertificateService.ReadAllSentCertificates();
Application excel = new Application();
string filePath = "C:/ToDoList/SentStats_" + DateTime.Now.ToString() + ".xls";
Workbook mybook = excel.Workbooks.Add();
excel.Visible = true;
try
{
mybook.Activate();
Worksheet mysheet = mybook.Worksheets.Add();
foreach (var x in certs)
{
// How to write each row in excel??
}
//mybook.SaveAs(Filename: filepath);
mybook.Save();
}
catch (Exception ex)
{
}
finally
{
mybook.Close();
}
Upvotes: 1
Views: 1710
Reputation: 1039230
Don't use Office interop in a web application. MS Office was never designed to run on a server. If you want to build an Excel sheet you could use OpenXML on the server.
As an alternative you could return a view containing the results in a <table>
and serve this view with the application/vnd.ms-excel
Content-Type
response header. You will have far less control over the formatting of the resulting sheet compared to using the OpenXML SDK which gives you full control.
Upvotes: 2