Export view to excel with razor without losing the style

19,933

Solution 1

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.

Solution 2

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;
}
Share:
19,933

Related videos on Youtube

kbaccouche
Author by

kbaccouche

Problem Exists Between Keyboard And Chair [PEBKAC]

Updated on September 15, 2022

Comments

  • kbaccouche
    kbaccouche 8 months

    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 ?

    • Tim Williams
      Tim Williams over 10 years
      You'll either have to serve up an actual Excel file, or if you're just sending an HTML table then include the styles in the HTML rather than linking them.
  • kbaccouche
    kbaccouche over 10 years
    But in my view I am collecting data from the controller and making stats on them. Can I do the same with an Excel file ?
  • Carles Company
    Carles Company about 8 years
    @the_ruby_racer Yes, use some library like EPPlus to create the Excel file dynamically.