Html to excel with styles

table of contents

html-to-xlsx recipe generates Excel xslx files from HTML tables. This isn’t a full HTML -> Excel conversion but a rather pragmatic and fast way to create Excel files from jsreport. The recipe reads input table and extract a couple of CSS style properties using a specific HTML engine (which defaults to chrome), and finally uses the styles to create the Excel cells.

Examples

  • Basic table
  • Cells with data types
  • Cell with line break
  • Cell with format
  • Cell with formula
  • Merged cells
  • Multiple sheets
  • Conversion JS trigger
  • Insert output into xlsx template
  • Postprocess using xlsx

The following CSS properties are supported:

  • background-color — cell background color
  • color — cell foreground color
  • border — all the border-[left|right|top|bottom]-width, border-[left|right|top|bottom]-style, border-[left|right|top|bottom]-color will be transformed into Excel cells borders.
  • text-align — text horizontal align in the Excel cell
  • vertical-align — vertical align in the Excel cell
  • width — the Excel column will get the highest width; it can be little bit inaccurate because of pixel to Excel points conversion
  • height — the Excel row will get the highest height
  • font-family — font family, defaults to Calibri
  • font-size — font size, defaults to 16px
  • font-stylenormal, and italic styles are supported
  • font-weight — control whether the cell’s text should be bold or not
  • text-decorationunderline and line-through are supported
  • overflow — the Excel cell will have text wrap enabled if this is set to scroll.

The following HTML attributes are supported:

  • colspan — numeric value that merges current column with columns to the right
  • rowspan — numeric value that merges current row with rows below.

Options

  • htmlEngineString (supported values here depends on the HTML engines that you have available in your jsreport installation, by default just chrome is available but you can additionally install better performing cheerio as HTML engine too)
  • waitForJSBoolean whether to wait for the JavaScript trigger to be enabled before trying to read the HTML tables on the page or not. defaults to false.
  • insertToXlsxTemplateBoolean controls if the result of the HTML to Excel tables conversion should be added as new sheets of existing xlsx template, it needs you to set an xlsx template to work. Default is false.

Sheets

Each table detected on the HTML source is converted to a new sheet in the final xlsx file. The sheets names are by default Sheet1, Sheet2 etc. However, you can specify a custom sheet name using the name or data-sheet-name attribute on the table element where the data-sheet-name has precedence.

<table name="Data1">
    <tr>
        <td>1</td>
    </tr>
</table>
<table data-sheet-name="Data2">
    <tr>
        <td>2</td>      
    </tr>
</table>

Cells with data types

To produce a cell with specific data type you need to use the data-cell-type on the td element. The supported data types are number, boolean, date, datetime and formula:

<table>
    <tr>
        <td data-cell-type="number">10</td>
        <td data-cell-type="boolean" style="width: 85px">1</td>
        <td data-cell-type="date">2019-01-22</td>
        <td data-cell-type="datetime">2019-01-22T17:31:36.000-05:00</td>
    </tr>
</table>

Format

Excel supports setting cell string format. Add the following attributes to the td element:

  • data-cell-format-str -> Specify the raw string format
  • data-cell-format-enum -> Select an existing format

Possible values of the data-cell-format-enum are:

  • 0 -> format equal to general
  • 1 -> format equal to 0
  • 2 -> format equal to 0.00
  • 3 -> format equal to #,##0
  • 4 -> format equal to #,##0.00
  • 9 -> format equal to 0%
  • 10 -> format equal to 0.00%
  • 11 -> format equal to 0.00e+00
  • 12 -> format equal to # ?/?
  • 13 -> format equal to # ??/??
  • 14 -> format equal to mm-dd-yy
  • 15 -> format equal to d-mmm-yy
  • 16 -> format equal to d-mmm
  • 17 -> format equal to mmm-yy
  • 18 -> format equal to h:mm am/pm
  • 19 -> format equal to h:mm:ss am/pm
  • 20 -> format equal to h:mm
  • 21 -> format equal to h:mm:ss
  • 22 -> format equal to m/d/yy h:mm
  • 37 -> format equal to #,##0 ;(#,##0)
  • 38 -> format equal to #,##0 ;[red](#,##0)
  • 39 -> format equal to #,##0.00;(#,##0.00)
  • 40 -> format equal to #,##0.00;[red](#,##0.00)
  • 41 -> format equal to _(* #,##0_);_(* (#,##0);_(* "-"_);_(@_)
  • 42 -> format equal to _("$"* #,##0_);_("$* (#,##0);_("$"* "-"_);_(@_)
  • 43 -> format equal to _(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
  • 44 -> format equal to _("$"* #,##0.00_);_("$"* (#,##0.00);_("$"* "-"??_);_(@_)
  • 45 -> format equal to mm:ss
  • 46 -> format equal to [h]:mm:ss
  • 47 -> format equal to mmss.0
  • 48 -> format equal to ##0.0e+0
  • 49 -> format equal to @
<style>
    td {
        width: 60px;
        padding: 5px;
    }
</style>
<table>
    <tr>
        <td data-cell-type="number" data-cell-format-str="0.00">10</td>
        <td data-cell-type="number" data-cell-format-enum="3">100000</td>
        <td data-cell-type="date" data-cell-format-str="m/d/yyy">2019-01-22</td>
    </tr>
</table>

Setting the format is also required when the cell needs to have a specific format category which depends on the computer locale. The cell is otherwise categorized by Excel as General.

For example, using data-cell-type="date" makes the cell a date and you can use it in the date-based calculations. However, the cell format category in Excel is displayed as General and not Date. To rectify this, you need to use data-cell-format-str to match your locale.

Formula

A formula cell can be specified using data-cell-type="formula" on the td element.

<table>
    <tr>
        <td data-cell-type="number">10</td>
        <td data-cell-type="number">10</td>
        <td data-cell-type="formula">=SUM(A1, B1)</td>
    </tr>
</table>

Font family

You can use the following CSS styles to change the default font-family for all cells in table.

td  { 
  font-family: 'Verdana'; 
  font-size: 18px; 
}

Insert output into xlsx template

The table to xlsx conversion can be enough for some cases. However, for more complex cases (like producing pivot tables or complex charts using Excel) there is an option to insert the produced tables into an existing xlsx template (as new sheets) instead of producing a new xlsx file.

The flow is the following:

  • Open your desktop Excel application and prepare file with pivot tables and charts on the one sheet and with static data on the second.
  • Upload the xlsx to jsreport studio and link it with your html-to-xlsx template generating dynamic table.
  • Make sure the table name matches with the data sheet name in your Excel.

Running the template now produces dynamic Excel with charts or pivots based on the data assembled by jsreport.

See this example to get an idea of what can be possible with this feature.

Conversion triggers

You may need to postpone conversion of tables until some JavaScript async tasks are processed. If this is the case; set htmlToXlsx.waitForJS = true in the API options or Wait for conversion trigger in the studio menu. When set, the conversion won’t start until you set window.JSREPORT_READY_TO_START = true inside your template’s JavaScript.

...
<script>
    // do some calculations or something async
    setTimeout(function() {
        window.JSREPORT_READY_TO_START = true; //this will start the conversion and read the existing tables on the page
    }, 500);
    ...
</script>

Issues with row height being larger than actual the content

When using phantomjs as the engine there are cases when a row height ends with a larger height than the actual content. This is caused by a phantomjs bug that retrieves a larger height when the content of cells contains white space characters.

There are two possible workarounds:

  • use letter-spacing CSS property with some negative value (demo)
<!-- without "letter-spacing" the row would be more larger -->
<table style="letter-spacing: -4px">
    <tr>
        <td> From Date: N/A</td>
        <td> To Date: N/A </td>
        <td> Search Text: N/A </td>
        <td> Sort Order: N/A </td>
        <td> Sort Key: N/A </td>
        <td> Filter: N/A </td>
    </tr>
</table>
  • use line-height: 0 with a specific height (demo)
<!-- without "line-height" and "height" the row would be more larger -->
<table style="line-height: 0">
    <tr style="height: 20px">
        <td> From Date: N/A</td>
        <td> To Date: N/A </td>
        <td> Search Text: N/A </td>
        <td> Sort Order: N/A </td>
        <td> Sort Key: N/A </td>
        <td> Filter: N/A </td>
    </tr>
</table>

Performance

The chrome engine can have performance problems when evaluating huge tables with many cells. For these cases the recipe provides an additional helper which splits large tables into chunks and runs evaluation in batches. Usage is like each or jsrender for handlebar helpers.

<table>
    {{#htmlToXlsxEachRows people}}
      <tr>
        <td>{{name}}</td>
        <td>{{address}}</td>
      </tr>
    {{/htmlToXlsxEachRows}}
</table>

Cheerio HTML engine

Although the htmlToXlsxEachRows helper prevents Chrome from hanging, the rendering can still be slow. This is because Chrome needs to create DOM elements for the whole table and evaluate every single cell. Fortunately, there is a better option for large tables – using the custom HTML engine cheerio-page-eval.

This custom engine is experimental and requires manual installation through NPM.

npm i cheerio-page-eval
restart jsreport

Afterward, you can select it in the studio HTML to xlsx menu and start using it. This engine doesn’t create DOM representation like Chrome, so it has much better performance. However, the lack of DOM also introduces some limitations.

  • The cheerio engine doesn’t support global CSS styles in the <style> tag. You need to use in-line styles on cells.
  • It also doesn’t evaluate JavaScript in the <script> tags. The helpers and templating engines aren’t limited.

htmlToXlsxEachRows helper also works with the cheerio engine and can significantly improve rendering memory footprint on long tables.

Preview in studio

See general documentation for office preview in studio here.

Postprocess using xlsx recipe

The html-to-xlsx will be always limited and you may miss some features that aren’t yet implemented in it. In this case you can use xlsx recipe and postprocess the html-to-xlsx and modify what you need using low level xlsx helpers.

Demo in playground

API

You can specify the template the standard way by using name or shortid, or alternatively you can also send it in the API request. If you have the Excel template stored as an asset you can also reference it in the request.

{  
  "template":  {  
    "recipe":  "html-to-xlsx",  
    "engine":  "handlebars",  
    "content": "<table></table>",
    "htmlToXlsx":  {  
      "templateAssetShortid":  "xxxx"  
    }  
  },  
  "data":  {}
}

If you don’t have the xlsx template stored as an asset you can send it directly in the API request.

{  
  "template":  {  
    "recipe":  "html-to-xlsx",  
    "engine":  "handlebars",  
    "content": "<table></table>",
    "htmlToXlsx":  {  
      "templateAsset":  {  
        "content": "base64 encoded word file",
        "encoding":"base64"
       }
    }  
  },  
  "data":  {}
}

Table to Excel 2

Build Status

Export HTML table to valid excel file effortlessly.
This library uses exceljs/exceljs under the hood to create the excel.
(Initial version of this library was using protobi/js-xlsx, it can be found here)

Installation

Browser

Just add a script tag:

<script type="text/javascript" src="../dist/tableToExcel.js"></script>

Node

npm install @linways/table-to-excel --save
import TableToExcel from "@linways/table-to-excel";

Usage

Create your HTML table as normal.
To export content of table #table1 run:

TableToExcel.convert(document.getElementById("table1"));

or

TableToExcel.convert(document.getElementById("table1"), {
  name: "table1.xlsx",
  sheet: {
    name: "Sheet 1"
  }
});

Check this pen for working example.

Cell Types

Cell types can be set using the following data attributes:

Attribute Description Possible Values
data-t To specify the data type of a cell s : String (Default)
n : Number
b : Boolean
d : Date
data-hyperlink To add hyper link to cell External URL or hyperlink to another sheet
data-error To add value of a cell as error

Example:

<!-- for setting a cell type as number -->
<td data-t="n">2500</td>
<!-- for setting a cell type as date -->
<td data-t="d">05-23-2018</td>
<!-- for setting a cell type as boolean. String "true/false" will be accepted as Boolean-->
<td data-t="b">true</td>
<!-- for setting a cell type as boolean using integer. 0 will be false and any non zero value will be true -->
<td data-t="b">0</td>
<!-- For adding hyperlink -->
<td data-hyperlink="https://google.com">Google</td>

Cell Styling

All styles are set using data attributes on td tags.
There are 5 types of attributes: data-f-*, data-a-*, data-b-*, data-fill-* and data-num-fmt which corresponds to five top-level attributes font, alignment, border, fill and numFmt.

Category Attribute Description Values
font data-f-name Font name «Calibri» ,»Arial» etc.
data-f-sz Font size «11» // font size in points
data-f-color Font color A hex ARGB value. Eg: FFFFOOOO for opaque red.
data-f-bold Bold true or false
data-f-italic Italic true or false
data-underline Underline true or false
data-f-strike Strike true or false
Alignment data-a-h Horizontal alignment left, center, right, fill, justify, centerContinuous, distributed
data-a-v Vertical alignment bottom, middle, top, distributed, justify
data-a-wrap Wrap text true or false
data-a-indent Indent Integer
data-a-rtl Text direction: Right to Left true or false
data-a-text-rotation Text rotation 0 to 90
-1 to -90
vertical
Border data-b-a-s Border style (all borders) Refer BORDER_STYLES
data-b-t-s Border top style Refer BORDER_STYLES
data-b-b-s Border bottom style Refer BORDER_STYLES
data-b-l-s Border left style Refer BORDER_STYLES
data-b-r-s Border right style Refer BORDER_STYLES
data-b-a-c Border color (all borders) A hex ARGB value. Eg: FFFFOOOO for opaque red.
data-b-t-c Border top color A hex ARGB value.
data-b-b-c Border bottom color A hex ARGB value.
data-b-l-c Border left color A hex ARGB value.
data-b-r-c Border right color A hex ARGB value.
Fill data-fill-color Cell background color A hex ARGB value.
numFmt data-num-fmt Number Format «0»
«0.00%»
«0.0%» // string specifying a custom format
«0.00%;(0.00%);-;@» // string specifying a custom format, escaping special characters

BORDER_STYLES: thin, dotted, dashDot, hair, dashDotDot, slantDashDot, mediumDashed, mediumDashDotDot, mediumDashDot, medium, double, thick

Exclude Cells and rows

To exclude a cell or a row from the exported excel add data-exclude="true" to the corresponding td or tr.
Example:

<!-- Exclude entire row -->
<tr data-exclude="true">
  <td>Excluded row</td>
  <td>Something</td>
</tr>

<!-- Exclude a single cell -->
<tr>
  <td>Included Cell</td>
  <td data-exclude="true">Excluded Cell</td>
  <td>Included Cell</td>
</tr>

Column Width

Column width’s can be set by specifying data-cols-width in the <table> tag.
data-cols-width accepts comma separated column widths specified in character count .
data-cols-width="10,20" will set width of first coulmn as width of 10 charaters and second column as 20 characters wide.
Example:

<table data-cols-width="10,20,30">
  ...
</table>

Row Height

Row Height can be set by specifying data-height in the <tr> tag.
Example:

<tr data-height="42.5">
  <td>Cell 1</td>
  <td>Cell 2</td>
</tr>

Release Changelog

1.0.0

Migration Guide for migrating from V0.2.1 to V1.0.0

  • Changed the backend to Exceexceljs/exceljslJS
  • Added border color
  • Option to set style and color for all borders
  • Exclude row
  • Added text underline
  • Added support for hyperlinks
  • Text intent
  • RTL support
  • Extra alignment options
  • String «true/false» will be accepted as Boolean
  • Changed border style values
  • Text rotation values changed

1.0.2

  • Fixed bug in handling multiple columns merges in a sheet

1.0.3

  • Option to specify row height

I’m using excel web queries to export an html table (mvc view) to excel. How do I get it to carry across the css styles? If I set class="redLabel" it doesn’t interpret that and make the label red. I have to use inline styles in my table for this to work. Any ideas?

Nightfirecat's user avatar

Nightfirecat

11.4k6 gold badges35 silver badges51 bronze badges

asked Aug 2, 2011 at 9:17

newbie_86's user avatar

As far as I know, most Office programs do NOT support included styling, but only inline styling.

It’s likely that you’ll be required to include your styling inline (exporting sucks, almost like mail styling).

answered Aug 4, 2011 at 20:51

Madara's Ghost's user avatar

Madara’s GhostMadara’s Ghost

171k50 gold badges264 silver badges309 bronze badges

0

Excel does support using css styling, but only if there is one class on the element. If there are multiple classes then it will not do any style on the element, see CSS style class not combining in Excel

Having said that, this is the code I put together to grab all the styles on a page and export an HTML table. It’s a brute force, grab everything approach, but you could probably pair it down if you know the specifics. The function returns a jQuery Promise. From that you can do whatever with the result.

function excelExportHtml(table, includeCss) {

    if (includeCss) {
        var styles = [];

        //grab all styles defined on the page
        $("style").each(function (index, domEle) {
            styles.push($(domEle).html());
        });

        //grab all styles referenced by stylesheet links on the page
        var ajaxCalls = [];
        $("[rel=stylesheet]").each(function () {
            ajaxCalls.push($.get(this.href, '', function (data) {
                styles.push(data);
            }));
        });

        return $.when.apply(null, ajaxCalls)
                .then(function () {
                    return "<html><style type='text/css'>" + styles.join("n") + "</style>n" + table.outerHTML + "</html>";
                });
    }
    else {
        return $.when({ owcHtml: table.outerHTML })
                .then(function (result) {
                    return "<html>" + result.owcHtml + "</html>";
                });
    }
}

Community's user avatar

answered Sep 17, 2013 at 18:15

Homer's user avatar

HomerHomer

7,56214 gold badges71 silver badges109 bronze badges

You can export table with outer css style. Here is my solution declare a document template:

var e = this;
var style = "<style></style"; //You can write css or get content of .css file

e.template = {
            head: "<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
            sheet: {
                head: "<x:ExcelWorksheet><x:Name>",
                tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
            },
            mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->>"+style+"</head><body>",
            table: {
                head: "<table>",
                tail: "</table>"
            },
            foot: "</body></html>"
        };

answered Feb 10, 2016 at 12:38

rdabrowski's user avatar

rdabrowskirdabrowski

1891 gold badge6 silver badges16 bronze badges

1

Содержание

  1. Converting html to xlsx
  2. table of contents
  3. Examples
  4. Options
  5. Sheets
  6. Cells with data types
  7. Format
  8. Formula
  9. Font family
  10. Insert output into xlsx template
  11. Conversion triggers
  12. Issues with row height being larger than actual the content
  13. Performance
  14. Cheerio HTML engine
  15. Export Html Table to Excel with CSS
  16. 2 Answers 2
  17. Related
  18. Hot Network Questions
  19. Subscribe to RSS
  20. linways/table-to-excel
  21. Sign In Required
  22. Launching GitHub Desktop
  23. Launching GitHub Desktop
  24. Launching Xcode
  25. Launching Visual Studio Code
  26. Latest commit
  27. Git stats
  28. Files
  29. README.md
  30. About

Converting html to xlsx

table of contents

html-to-xlsx recipe generates Excel xslx files from HTML tables. This isn’t a full HTML -> Excel conversion but a rather pragmatic and fast way to create Excel files from jsreport. The recipe reads input table and extract a couple of CSS style properties using a specific HTML engine (which defaults to chrome), and finally uses the styles to create the Excel cells.

Examples

The following CSS properties are supported:

  • background-color — cell background color
  • color — cell foreground color
  • border — all the border-[left|right|top|bottom]-width , border-[left|right|top|bottom]-style , border-[left|right|top|bottom]-color will be transformed into Excel cells borders.
  • text-align — text horizontal align in the Excel cell
  • vertical-align — vertical align in the Excel cell
  • width — the Excel column will get the highest width; it can be little bit inaccurate because of pixel to Excel points conversion
  • height — the Excel row will get the highest height
  • font-family — font family, defaults to Calibri
  • font-size — font size, defaults to 16px
  • font-style — normal , and italic styles are supported
  • font-weight — control whether the cell’s text should be bold or not
  • text-decoration — underline and line-through are supported
  • overflow — the Excel cell will have text wrap enabled if this is set to scroll.

The following HTML attributes are supported:

  • colspan — numeric value that merges current column with columns to the right
  • rowspan — numeric value that merges current row with rows below.

Options

  • htmlEngine — String (supported values here depends on the HTML engines that you have available in your jsreport installation, by default just chrome is available but you can additionally install better performing cheerio as HTML engine too)
  • waitForJS — Boolean whether to wait for the JavaScript trigger to be enabled before trying to read the HTML tables on the page or not. defaults to false .
  • insertToXlsxTemplate — Boolean controls if the result of the HTML to Excel tables conversion should be added as new sheets of existing xlsx template, it needs you to set an xlsx template to work. Default is false .

Sheets

Each table detected on the HTML source is converted to a new sheet in the final xlsx file. The sheets names are by default Sheet1 , Sheet2 etc. However, you can specify a custom sheet name using the name or data-sheet-name attribute on the table element where the data-sheet-name has precedence.

Cells with data types

To produce a cell with specific data type you need to use the data-cell-type on the td element. The supported data types are number , boolean , date , datetime and formula :

Format

Excel supports setting cell string format. Add the following attributes to the td element:

  • data-cell-format-str -> Specify the raw string format
  • data-cell-format-enum -> Select an existing format

Possible values of the data-cell-format-enum are:

  • 0 -> format equal to general
  • 1 -> format equal to 0
  • 2 -> format equal to 0.00
  • 3 -> format equal to #,##0
  • 4 -> format equal to #,##0.00
  • 9 -> format equal to 0%
  • 10 -> format equal to 0.00%
  • 11 -> format equal to 0.00e+00
  • 12 -> format equal to # ?/?
  • 13 -> format equal to # ??/??
  • 14 -> format equal to mm-dd-yy
  • 15 -> format equal to d-mmm-yy
  • 16 -> format equal to d-mmm
  • 17 -> format equal to mmm-yy
  • 18 -> format equal to h:mm am/pm
  • 19 -> format equal to h:mm:ss am/pm
  • 20 -> format equal to h:mm
  • 21 -> format equal to h:mm:ss
  • 22 -> format equal to m/d/yy h:mm
  • 37 -> format equal to #,##0 ;(#,##0)
  • 38 -> format equal to #,##0 ;[red](#,##0)
  • 39 -> format equal to #,##0.00;(#,##0.00)
  • 40 -> format equal to #,##0.00;[red](#,##0.00)
  • 41 -> format equal to _(* #,##0_);_(* (#,##0);_(* «-«_);_(@_)
  • 42 -> format equal to _(«$»* #,##0_);_(«$* (#,##0);_(«$»* «-«_);_(@_)
  • 43 -> format equal to _(* #,##0.00_);_(* (#,##0.00);_(* «-«??_);_(@_)
  • 44 -> format equal to _(«$»* #,##0.00_);_(«$»* (#,##0.00);_(«$»* «-«??_);_(@_)
  • 45 -> format equal to mm:ss
  • 46 -> format equal to [h]:mm:ss
  • 47 -> format equal to mmss.0
  • 48 -> format equal to ##0.0e+0
  • 49 -> format equal to @

Setting the format is also required when the cell needs to have a specific format category which depends on the computer locale. The cell is otherwise categorized by Excel as General .

For example, using data-cell-type=»date» makes the cell a date and you can use it in the date-based calculations. However, the cell format category in Excel is displayed as General and not Date . To rectify this, you need to use data-cell-format-str to match your locale.

Formula

A formula cell can be specified using data-cell-type=»formula» on the td element.

Font family

You can use the following CSS styles to change the default font-family for all cells in table.

Insert output into xlsx template

The table to xlsx conversion can be enough for some cases. However, for more complex cases (like producing pivot tables or complex charts using Excel) there is an option to insert the produced tables into an existing xlsx template (as new sheets) instead of producing a new xlsx file.

The flow is the following:

  • Open your desktop Excel application and prepare file with pivot tables and charts on the one sheet and with static data on the second.
  • Upload the xlsx to jsreport studio and link it with your html-to-xlsx template generating dynamic table.
  • Make sure the table name matches with the data sheet name in your Excel.

Running the template now produces dynamic Excel with charts or pivots based on the data assembled by jsreport.

Conversion triggers

You may need to postpone conversion of tables until some JavaScript async tasks are processed. If this is the case; set htmlToXlsx.waitForJS = true in the API options or Wait for conversion trigger in the studio menu. When set, the conversion won’t start until you set window.JSREPORT_READY_TO_START = true inside your template’s JavaScript.

Issues with row height being larger than actual the content

When using phantomjs as the engine there are cases when a row height ends with a larger height than the actual content. This is caused by a phantomjs bug that retrieves a larger height when the content of cells contains white space characters.

There are two possible workarounds:

  • use letter-spacing CSS property with some negative value (demo)
  • use line-height: 0 with a specific height (demo)

Performance

The chrome engine can have performance problems when evaluating huge tables with many cells. For these cases the recipe provides an additional helper which splits large tables into chunks and runs evaluation in batches. Usage is like each or jsrender for handlebar helpers.

Cheerio HTML engine

Although the htmlToXlsxEachRows helper prevents Chrome from hanging, the rendering can still be slow. This is because Chrome needs to create DOM elements for the whole table and evaluate every single cell. Fortunately, there is a better option for large tables – using the custom HTML engine cheerio-page-eval.

This custom engine is experimental and requires manual installation through NPM.

Afterward, you can select it in the studio HTML to xlsx menu and start using it. This engine doesn’t create DOM representation like Chrome, so it has much better performance. However, the lack of DOM also introduces some limitations.

  • The cheerio engine doesn’t support global CSS styles in the tag. You need to use in-line styles on cells.
  • It also doesn’t evaluate JavaScript in the —>

Источник

Export Html Table to Excel with CSS

I’m trying to export a HTML table to Excel by keeping table style. I have searched the web and found a few examples, but none of them work as expected. They have problems like CSS not working or headers not supported.

This is the code I have, but the file gets downloaded without an XLS extension.

2 Answers 2

This is the code I use. it makes a Xls and gives a warning but it works and gets the data and css. Might be almost 2 years after you posted the question but I thought why not.

Export the HTML table in Excel file to offline view and more Excel editing work. This turns more tricky when we need the CSS of the table too. Here is the sample application demonstrating the Excel export. Put the below code in your Head part of the page.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

linways/table-to-excel

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Table to Excel 2

Export HTML table to valid excel file effortlessly. This library uses exceljs/exceljs under the hood to create the excel.
(Initial version of this library was using protobi/js-xlsx, it can be found here)

Just add a script tag:

Create your HTML table as normal.
To export content of table #table1 run:

Check this pen for working example.

Cell types can be set using the following data attributes:

Attribute Description Possible Values
data-t To specify the data type of a cell s : String (Default)
n : Number
b : Boolean
d : Date
data-hyperlink To add hyper link to cell External URL or hyperlink to another sheet
data-error To add value of a cell as error

All styles are set using data attributes on td tags. There are 5 types of attributes: data-f-* , data-a-* , data-b-* , data-fill-* and data-num-fmt which corresponds to five top-level attributes font , alignment , border , fill and numFmt .

Category Attribute Description Values
font data-f-name Font name «Calibri» ,»Arial» etc.
data-f-sz Font size «11» // font size in points
data-f-color Font color A hex ARGB value. Eg: FFFFOOOO for opaque red.
data-f-bold Bold true or false
data-f-italic Italic true or false
data-underline Underline true or false
data-f-strike Strike true or false
Alignment data-a-h Horizontal alignment left , center , right , fill , justify , centerContinuous , distributed
data-a-v Vertical alignment bottom , middle , top , distributed , justify
data-a-wrap Wrap text true or false
data-a-indent Indent Integer
data-a-rtl Text direction: Right to Left true or false
data-a-text-rotation Text rotation 0 to 90
-1 to -90
vertical
Border data-b-a-s Border style (all borders) Refer BORDER_STYLES
data-b-t-s Border top style Refer BORDER_STYLES
data-b-b-s Border bottom style Refer BORDER_STYLES
data-b-l-s Border left style Refer BORDER_STYLES
data-b-r-s Border right style Refer BORDER_STYLES
data-b-a-c Border color (all borders) A hex ARGB value. Eg: FFFFOOOO for opaque red.
data-b-t-c Border top color A hex ARGB value.
data-b-b-c Border bottom color A hex ARGB value.
data-b-l-c Border left color A hex ARGB value.
data-b-r-c Border right color A hex ARGB value.
Fill data-fill-color Cell background color A hex ARGB value.
numFmt data-num-fmt Number Format «0»
«0.00%»
«0.0%» // string specifying a custom format
«0.00%;(0.00%);-;@» // string specifying a custom format, escaping special characters

BORDER_STYLES: thin , dotted , dashDot , hair , dashDotDot , slantDashDot , mediumDashed , mediumDashDotDot , mediumDashDot , medium , double , thick

Exclude Cells and rows

To exclude a cell or a row from the exported excel add data-exclude=»true» to the corresponding td or tr .
Example:

Column width’s can be set by specifying data-cols-width in the

tag. data-cols-width accepts comma separated column widths specified in character count . data-cols-width=»10,20″ will set width of first coulmn as width of 10 charaters and second column as 20 characters wide.

Row Height can be set by specifying data-height in the

Migration Guide for migrating from V0.2.1 to V1.0.0

  • Changed the backend to Exceexceljs/exceljslJS
  • Added border color
  • Option to set style and color for all borders
  • Exclude row
  • Added text underline
  • Added support for hyperlinks
  • Text intent
  • RTL support
  • Extra alignment options
  • String «true/false» will be accepted as Boolean
  • Changed border style values
  • Text rotation values changed
  • Fixed bug in handling multiple columns merges in a sheet

About

Javascript library to create «valid» excel file from html table with styles

Источник

Adblock
detector

Example: tag. Example:

  • Download demo — 135.3 KB

Introduction

Many times, we have to export the HTML table in Excel file to offline view and more Excel editing work. This turns more tricky when we need the CSS of the table too. Here is the sample application demonstrating the Excel export.

Background

To start with this, you need a little knowledge of JavaScript.

Using the Code

Put the below code in your Head part of the page.

JavaScript

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var tableToExcel = (function () {
            var uri = 'data:application/vnd.ms-excel;base64,'
                , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" 
                xmlns:x="urn:schemas-microsoft-com:office:excel" 
                xmlns="http://www.w3.org/TR/REC-html40"><head>
                <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>
                <x:ExcelWorksheet><x:Name>{worksheet}</x:Name>
                <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>
                </x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>
                </xml><![endif]--></head><body>
                <table>{table}</table></body></html>'
                , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
                , format = function (s, c) { return s.replace(/{(w+)}/g, function (m, p) { return c[p]; }) }
                return function (table, name) {
                if (!table.nodeType) table = document.getElementById(table)
                var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()
    </script> 

In the above code, we are converting the table to the Excel Sheet standard.

Sample HTML Code

<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">
<table id="testTable" summary="Code page support in different versions of MS Windows."
    rules="groups" frame="hsides" border="2">
    <caption>
        CODE-PAGE SUPPORT IN MICROSOFT WINDOWS</caption>
    <colgroup align="center">
    </colgroup>
    <colgroup align="left">
    </colgroup>
    <colgroup span="2" align="center">
    </colgroup>
    <colgroup span="3" align="center">
    </colgroup>
    <thead valign="top">
        <tr>
            <th>Code-Page<br>ID</th>
            <th>Name</th>
            <th>ACP</th>
            <th>OEMCP</th>
            <th>Windows<br>NT 3.1</th>
            <th>Windows<br>NT 3.51</th>
            <th>Windows<br>95</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1200</td>
            <td style="background-color: #00f; color: #fff">Unicode (BMP of ISO/IEC-10646)</td>
            <td></td>
            <td></td>
            <td>X</td>
            <td>X</td>
            <td>*</td>
        </tr>
        <tr>
            <td>1250</td>
            <td style="font-weight: bold">
                <a href="http://www.jquery2dotnet.com/">http://www.jquery2dotnet.com/</a>
            </td>
            <td>X</td>
            <td></td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
        </tr>
        <tr>
            <td>1255</td>
            <td>Hebrew</td>
            <td>X</td>
            <td></td>
            <td></td>
            <td></td>
            <td>X</td>
        </tr>
        <tr>
            <td>437</td>
            <td>MS-DOS United States</td>
            <td></td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
            <td>X</td>
        </tr>
        <tr>
            <td>708</td>
            <td>Arabic (ASMO 708)</td>
            <td></td>
            <td>X</td>
            <td></td>
            <td></td>
            <td>X</td>
        </tr>
        <tr>
            <td>709</td>
            <td>Arabic (ASMO 449+, BCON V4)</td>
            <td></td>
            <td>X</td>
            <td></td>
            <td></td>
            <td>X</td>
        </tr>
        <tr>
            <td>710</td>
            <td>Arabic (Transparent Arabic)</td>
            <td></td>
            <td>X</td>
            <td></td>
            <td></td>
            <td>X</td>
        </tr>
    </tbody>
</table>

Points of Interest

The file is converted and saved as Excel on the client side without any postbacks that is also very quick.

License

Written By

Software Developer

India India

Puneet Goel is an IT Professional with 8+ years. He is specialized in Microsoft Technologies (Asp.NET, SQL Server, Ajax, Jquery, JavaScript, MVC, and Angular). He is an avid member of several development communities and a serial blogger.He loves to learn new technology, do experiments with existing ones, and always happy to help the community.

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Понравилась статья? Поделить с друзьями:
  • Html to excel with css
  • Html to excel utf 8
  • Html to excel laravel
  • Html from word 2010
  • Html from word 2007