Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export view to excel with razor without losing the style

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 ?

like image 616
kbaccouche Avatar asked Sep 11 '12 22:09

kbaccouche


2 Answers

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.

like image 192
mnsr Avatar answered Oct 22 '22 13:10

mnsr


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;
}
like image 36
Craig Avatar answered Oct 22 '22 14:10

Craig