- 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
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.
Содержание
- Converting html to xlsx
- table of contents
- Examples
- Options
- Sheets
- Cells with data types
- Format
- Formula
- Font family
- Insert output into xlsx template
- Conversion triggers
- Issues with row height being larger than actual the content
- Performance
- Cheerio HTML engine
- Export Html Table to Excel with CSS
- 2 Answers 2
- Related
- Hot Network Questions
- Subscribe to RSS
- linways/table-to-excel
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- 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:
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.
$(function() {
$("#btnExport").click(function(e) {
window.open('data:application/vnd.ms-excel,' + $('#dvData').html());
e.preventDefault();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="dvData">
<table>
<tr>
<th>Column One</th>
<th>Column Two</th>
<th>Column Three</th>
</tr>
<tr>
<td>row1 Col1</td>
<td>row1 Col2</td>
<td>row1 Col3</td>
</tr>
<tr>
<td style="background-color: #ff0000">row2 Col1</td>
<td>row2 Col2</td>
<td>row2 Col3</td>
</tr>
<tr>
<td>row3 Col1</td>
<td>row3 Col2</td>
<td><a href="http://www.jquery2dotnet.com/">http://www.jquery2dotnet.com/</a>
</td>
</tr>
</table>
</div>
https://jsfiddle.net/lesson8/jWAJ7/
I used code from this link, but it didn’t work: https://www.codeproject.com/Tips/755203/Export-HTML-table-to-Excel-With-CSS
table2excel.js plugin also not working
https://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html
asked Jun 6, 2019 at 9:51
webpicwebpic
4431 gold badge10 silver badges23 bronze badges
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.
<a href="#" id="tests" onClick="javascript:fnExcelReport();">Download</a><br><br>
<table id="myTable">
<tr style="background-color: black; color: white; font-size: 10px;">
<th>Name</th>
<th>Last name</th>
<th>age</th>
</tr>
<tr>
<td>Bob</td>
<td>John</td>
<td>21</td>
</tr>
</table>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
function fnExcelReport() {
var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
tab_text = tab_text + '<x:Name>Test Sheet</x:Name>';
tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
tab_text = tab_text + "<table>";
tab_text = tab_text + $('#myTable').html();
tab_text = tab_text + '</table></body></html>';
var data_type = 'data:application/vnd.ms-excel';
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11./)) {
if (window.navigator.msSaveBlob) {
var blob = new Blob([tab_text], {
type: "application/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, 'Test file.xls');
}
} else {
$('#tests').attr('href', data_type + ', ' + encodeURIComponent(tab_text));
$('#tests').attr('download', 'Test file.xls');
}
}
</script>
answered Mar 8, 2021 at 15:35
1
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.
<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>
answered Jun 6, 2019 at 10:13
0
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 colorcolor
— cell foreground colorborder
— all theborder-[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 cellvertical-align
— vertical align in the Excel cellwidth
— the Excel column will get the highest width; it can be little bit inaccurate because of pixel to Excel points conversionheight
— the Excel row will get the highest heightfont-family
— font family, defaults toCalibri
font-size
— font size, defaults to16px
font-style
—normal
, anditalic
styles are supportedfont-weight
— control whether the cell’s text should be bold or nottext-decoration
—underline
andline-through
are supportedoverflow
— 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 rightrowspan
— 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 justchrome
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 tofalse
.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 isfalse
.
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 formatdata-cell-format-enum
-> Select an existing format
Possible values of the data-cell-format-enum
are:
0
-> format equal togeneral
1
-> format equal to0
2
-> format equal to0.00
3
-> format equal to#,##0
4
-> format equal to#,##0.00
9
-> format equal to0%
10
-> format equal to0.00%
11
-> format equal to0.00e+00
12
-> format equal to# ?/?
13
-> format equal to# ??/??
14
-> format equal tomm-dd-yy
15
-> format equal tod-mmm-yy
16
-> format equal tod-mmm
17
-> format equal tommm-yy
18
-> format equal toh:mm am/pm
19
-> format equal toh:mm:ss am/pm
20
-> format equal toh:mm
21
-> format equal toh:mm:ss
22
-> format equal tom/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 tomm:ss
46
-> format equal to[h]:mm:ss
47
-> format equal tommss.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 specificheight
(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": {}
}
Обычно экспорт в txt, csv или excel. txt и csv обычно используются для обмена данными между системами,
Однако, как правило, Excel имеет лучший эффект отображения и может быть экспортирован в соответствии с определенным шаблоном. Экспорт не нужно набирать. Он прост в использовании. Если он используется в качестве отчета, он обычно экспортируется в файл Excel. .
Однако экспорт данных в Excel с использованием компонентов com очень медленный. Другой способ создания файлов Excel — это быстро экспортировать данные через html и css и одновременно установить стиль. У использования этого метода есть два преимущества: 1 — быстрый, 2 — Нет необходимости устанавливать поддержку Excel.
Реализация заключается в том, что его можно напрямую преобразовать в excel через html. Есть два основных момента: один — отображать строку таблицы, например, ASP.net напрямую экспортирует excel через Gridview, он не отображает таблицу
Второй — установить формат данных.
1. Отображается строка таблицы:
Добавьте следующий код в тег заголовка html:
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Заголовок рабочего листа</x:Name>
<x:WorksheetOptions>
<x:Print>
<x:ValidPrinterInfo />
</x:Print>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
2. Установите формат данных:
Добавить определение css в заголовок
<style type=»text/css»>
.spercent
{
background-color:#ffff99;
mso-number-format:0.00%;
}
</style>
Добавить в css: mso-number-format определяет формат данных. Формат можно просмотреть в Excel. Для получения дополнительной информации см.
mso-number-format:»0″ NO Decimals
mso-number-format:»0.000″ 3 Decimals
mso-number-format:»#,##0.000″ Comma with 3 dec
mso-number-format:»mm/dd/yy» Date7
mso-number-format:»mmmm d, yyyy» Date9
mso-number-format:»m/d/yy h:mm AM/PM» D -T AMPM
mso-number-format:»Short Date» 01/03/1998
mso-number-format:»Medium Date» 01-mar-98
mso-number-format:»d-mmm-yyyy» 01-mar-1998
mso-number-format:»Short Time» 5:16
mso-number-format:»Medium Time» 5:16 am
mso-number-format:»Long Time» 5:16:21:00
mso-number-format:»Percent» Percent — two decimals
mso-number-format:»0%» Percent — no decimals
mso-number-format:»0.E+00″ Scientific Notation
mso-number-format:»@» Text
mso-number-format:»# ???/???» Fractions — up to 3 digits (312/943)
Экспортированный Excel можно открыть напрямую через Excel, эффект будет следующим:
Полный код:
{
protected const string HEADER = «<html xmlns:x=»urn:schemas-microsoft-com:office:excel»>» +
«<meta http-equiv=Content-Type content=»text/html; charset=»gb2312″>» +
«<head>» +
«<!—[if gte mso 9]><xml>» +
«<x:ExcelWorkbook>» +
«<x:ExcelWorksheets>» +
«<x:ExcelWorksheet>» +
«<x: Name> Название рабочего листа </ x: Name>» +
«<x:WorksheetOptions>» +
«<x:Print>» +
&n bsp; «<x:ValidPrinterInfo />» +
«</x:Print>» +
«</x:WorksheetOptions>» +
«</x:ExcelWorksheet>» +
«</x:ExcelWorksheets>» +
«</x:ExcelWorkbook>» +
«</xml>» +
«<![endif]—>» ;
const string STYLE=»<style type=»text/css»>» +
«.spercent» +
» {» +
» background-color:#ffff99;» +
» mso-number-format:0.00%;» +
» }» +
«.sId» http://msnpiki.msnfanatic.com/index.php/Main_Page—>
0;»>+
» {» +
» background-color:#ff6633;» +
» mso-number-format:0;» +
» }» +
«.sName» +
» {» +
» color:red;» +
» }» +
«.sValue» +
» {» +
» color:blue;» +
» mso-number-format:0;» +
» }» +
«</style>»;
static void Main(string[] args)
{
using (StreamWriter writer = new StreamWriter(@»C:1.xls», true, System.Text.Encoding.GetEncoding(«gb2312»
style=»color: #000000;»>), 512))
{
writer.WriteLine(HEADER);
writer.WriteLine(STYLE);
writer.WriteLine(«</head><body><table border=»1″ style=»font-size:9pt»><tr>»);
writer.WriteLine («<th>ID</th>»);
writer.WriteLine («<th>Name</th>»);
writer.WriteLine («<th>Value</th>»);
writer.WriteLine («<th>Percent</th>»);
for (int row = 1; row < 50; row++)
{
writer.WriteLine(«<tr>»);
writer.WriteLine(«<td class=»sId»>{0}</td», row);
writer.WriteLine(«<td class=»sName»>{0}</td», Guid.NewGuid ().ToString ());
writer.WriteLine(«<td class=»sValue»>{0}</td», new Random().Next());
writer.WriteLine(«<td class=»spercent»>{0}</td», new Random().NextDouble());
writer.WriteLine(«</tr>»);
}
writer.WriteLine(«</table></body>»);
}
}
}