I have a razor view which I want to export to excel.
I am using this line in my view to do it :
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
When I comment this line, I can see the view with the style I want. When I uncomment it and ask for it, the browser asks me to download the Excel file like it should. But the problem is when I open the file, I get this error
Missing file c:\scrips\excel.css
which is the css I am using to display the page.
So how can I make the file be saved WITH its layout ?
You will probably need to create a separate "EXPORT" view. This means, it's own controller Action
, and View
itself. The view will need to be identical to what you want the resulting Excel file to look like. It has to be standalone. No layout, and a style tag that holds the css within (no linking of styles/scripts/etc).
Here's a simple example:
Lets say you have a Controller
called "Home".
Action inside HomeController
:
public ActionResult Export()
{
Response.AddHeader("Content-Type", "application/vnd.ms-excel");
return View();
}
View (Home\Export.cshtml):
@{
Layout = "";
}
<style type="text/css">
body {font-family: Tahoma;}
h2 {color:red}
table {border:1px solid black; border-spacing:0}
td {color:green; font-size:.8em; padding:5px}
.heading {background:#ccc}
</style>
<h2>Test</h2>
<table>
<tr class="heading">
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>Test1</td>
<td>15</td>
</tr>
<tr>
<td>Test2</td>
<td>16</td>
</tr>
</table>
Once you load this page, it'll pop up with a download box, and it'll open in excel with the appropriate styles.
Your controller should have an action that actually serves the Excel file, not a web page containing the Excel file. The controller action should be something like.
public ActionResult Export()
{
byte[] doc = GetExcelFileSomehow();
var file = File(doc, "application/vnd.ms-excel");
file.FileDownloadName = "MyFile.xlsx";
return file;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With