js js knowledge summary table to achieve export Excel, reserved table style

A, js export Excel

(1) js pure distal export data Excel ( Transfer: HTTPS: //blog.csdn.net/hhzzcc_/article/details/80419396 )

1. The export json data to excel spreadsheet, compatible with chrome no problem.

method one

The tag table, comprising tr, td stitching so on json data, the output to the form table implementation, the drawbacks of this method is that the output is a pseudo-excel, although generate xls file with the extension, but the file form or html, code show as below

<HTML>
<head>
<P style = "font-size: 20px; Color: Red;"> using table tags manner json export xls file </ P>
<Button the onclick = 'tableToExcel ()'> derived </ button >
</ head>
<body>
<Script>

function tableToExcel () {
// the data to be exported json
const jsonData = [
{
name: 'passerby',
Phone: '123456',
in Email: '[email protected] '
},
{
name: 'fodder b',
Phone: '123456',
In Email: '[email protected] '
},
{
name:' prop-bandit ',
Phone:' 123456 ',
In Email: '[email protected]'
},
{
name: 'rogue D',
Phone: '123456',
In Email: '[email protected] '
},
]
// column heading
let str = '<tr> < td> Name </ td> <td> Phone </ td> <td> mailbox </ TD> </ tr>';
// Loop through each row was added tr tag, each cell plus td tag
for (the let I = 0; I <jsonData.length; I ++) {
STR + = '<TR>';
for (Item in the let jsonData [I]) {
// increase \ t display table in order to prevent scientific notation, or other formats
STR + = `<TD> $ {jsonData [I] [Item] + '\ T'} </ TD>`;
}
STR + = '</ TR>';
}
// the Worksheet name
let worksheet = 'Sheet1'
the let URI = 'data: file application / vnd.ms-Excel; Base64,';

// form template data downloaded
let template = `<html xmlns: o =" urn: schemas-microsoft-com: office: Office "
xmlns: the X-=" URN: schemas-in the 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>${str}</table></body></html>`;
//下载模板
window.location.href = uri + base64(template)
}
//输出base64编码
function base64 (s) { return window.btoa(unescape(encodeURIComponent(s))) }
</script>
</body>
</html>

 

Method Two

Json string by traversing the stitching, the character string output to csv file, as follows

<HTML>
<head>
<P style = "font-size: 20px; Color: Red;"> using a tag manner json export csv file </ P>
<Button the onclick = 'tableToExcel ()'> derived </ button >
</ head>
<body>
<Script>

function tableToExcel () {
// the data to be exported json
const jsonData = [
{
name: 'passerby',
Phone: '123456789',
in Email: '[email protected] '
},
{
name: 'fodder b',
Phone: '123456789',
In Email: '[email protected] '
},
{
name:' prop-bandit ',
Phone:' 123456789 ',
In Email: '[email protected]'
},
{
name: 'rogue D',
phone:'123456789',
email:'[email protected]'
},
]
// column headers, separated by commas, each separated by a comma is a cell
let str = `name, phone, email \ n`;
// increase \ t To keep table shows the scientific notation or other formats
for (let I = 0; I <jsonData.length; I ++) {
for (the let Item in jsonData [I]) {
STR + = `$ {jsonData [I] [Item] + '\ T'},`;
}
STR + = '\ n-';
}
// the encodeURIComponent Chinese distortion solve
the let URI =' Data: text / CSV; charset = UTF-. 8, \ ufeff '+ the encodeURIComponent (STR);
// achieved by creating a label
let link = document.createElement ( " a ");
link.href = URI;
// name of the file downloaded
link.download =" json Datasheet .csv ";
document.body.appendChild (Link);
link.click ();
document.body.removeChild ( Link);
}

</ Script>
</ body>
</ HTML>

 

Include a reference link:

https://blog.csdn.net/oscar999/article/details/16342699
https://blog.csdn.net/aa122273328/article/details/50388673

(2) JS table to achieve export Excel, reserved table style ( Transfer: HTTPS: //www.cnblogs.com/heihei-haha/p/7921432.html )

 

Save js table to excel file

Browser environment: Google browser

1. When the export of Excel, save the table styles, there are two ways, ① is written in a style style table rows, ② is in templates to add style

2. The first way: add inline style

<Td style = "font-size: 18px"> a company </ td>

effect:

Complete code:

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table td {
            font-size: 12px;
            width: 200px;
            height: 30px;
            text-align: center;
            background-color: #4f891e;
            color: #ffffff;
        }
    </style>
</head>
<body>
<a download="table导出Excel" id="excelOut" href="#">table导出Excel</a>
<table cellspacing="0" cellpadding="0" border="1" id="tableToExcel">
        <TD> Company III </ td>
        <TD> Company twenty-one </ td>
    <TR>
    <thead>
        <td style="font-size: 18px">公司一</td>
    </ TR> 
    </ thead> 
    <tbody> 
    <TR> 
        <TD> A company </ TD> 
        <TD> B Company </ TD> 
        <TD> C Company </ TD> 
    </ TR> 
    <TR> 
        <TD > A company </ td> 
        <TD> B company </ td> 
        <TD> C company </ td> 
    </ TR> 
    <TR> 
        <TD> A company </ td> 
        <TD> B company </ td> 
        <td> C company </ TD> 
    </ TR> 
    <TR> 
        <TD colspan = ". 3"> total </ TD> 
    </ TR> 
    </ tbody> 
</ Table> 
<Script>
    = function the window.onload () { 
        tableToExcel ( 'tableToExcel', 'download templates')  
    };
    // Base64 transcoding 
    var base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    //替换table数据和worksheet名字
    var format = function (s, c) {
        return s.replace(/{(\w+)}/g,
            function (m, p) {
                return c[p];
            });
    }
    function tableToExcel(tableid, sheetName) {
        var uri = 'data:application/vnd.ms-excel;base64,';
        var 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]-->' +
            ' <style type="text/css">' +
            'table td {' +
            'border: 1px solid #000000;' +
            'width: 200px;' +
            'height: 30px;' +
            ' text-align: center;' +
            '' +
            'color: #ffffff;' +
            ' }' +
            '</style>' +
            '</head><body ><table class="excelTable">{table}</table></body></html>';
        if (!tableid.nodeType) tableid = document.getElementById(tableid);
        var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
        document.getElementById("excelOut").href = uri + base64(format(template, ctx));
    }

</script>
</body>
</html>
Copy the code

3. The second way: Add style template inside inside

You will be able to find and identify the style excel there to add a

Copy the code
var 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]-->' +
            ' <style type="text/css">' +
            'table td {' +
            'border: 1px solid #000000;' +
            'width: 200px;' +
            'height: 30px;' +
            ' text-align: center;' +
            'background-color: #4f891e;' +
            'color: #ffffff;' +
            ' }' +
            '</style>' +
            '</head><body ><table class="excelTable">{table}</table></body></html>';
Copy the code

完整代码:

Copy the code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        table td {
            font-size: 12px;
            width: 200px;
            height: 30px;
            text-align: center;
            background-color: #4f891e;
            color: #ffffff;
        }
    </style>
</head>
<body>
<a download="table导出Excel" id="excelOut" href="#">table导出Excel</a>
<table cellspacing="0" cellpadding="0" border="1" id="tableToExcel">
    <thead>
    <tr>
        <td >公司一</td>
        <td>公司二一</td>
        <td>公司三</td>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td>A公司</td>
        <td>B公司</td>
        <td>C公司</td>
    </tr>
    <tr>
        <td colspan="3">共计</td>
    </tr>
    </tbody>
</table>
<script>
    window.onload = function () {
        tableToExcel('tableToExcel', '下载模板')
    };
    //base64转码
    var base64 = function (s) {
        return window.btoa(unescape(encodeURIComponent(s)));
    };
    //替换table数据和worksheet名字
    var format = function (s, c) {
        return s.replace(/{(\w+)}/g,
            function (m, p) {
                return c[p];
            });
    }
    function tableToExcel(tableid, sheetName) {
        var uri = 'data:application/vnd.ms-excel;base64,';
        var 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]-->' +
            ' <style type="text/css">' +
            'table td {' +
            'border: 1px solid #000000;' +
            'width: 200px;' +
            'height: 30px;' +
            ' text-align: center;' +
            '' +
            'color: #ffffff;' +
            ' }' +
            '</style>' +
            '</head><body ><table class="excelTable">{table}</table></body></html>';
        if (!tableid.nodeType) tableid = document.getElementById(tableid);
        var ctx = {worksheet: sheetName || 'Worksheet', table: tableid.innerHTML};
        document.getElementById("excelOut").href = uri + base64(format(template, ctx));
    }

</script>
</body>
</html>
Copy the code

Note: If while adding inline styles and template styles, the style in the guild cover template style

Guess you like

Origin www.cnblogs.com/newcapecjmc/p/11278770.html