如何在jQuery Datatable中自定义导出的Excel文件

时间:2016-09-26 18:09:02

标签: jquery html excel datatable

我有一个显示一些数据的jQuery数据表。

我需要将内容导出到excel文件并为文件设置样式:(以粗体编写标题,在标题中添加coor背景,为表格添加边框...) 我尝试了两种解决方案,但我遇到了问题

第一个解决方案:

    function fnExcelReportfile(id, name) {   
            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 border='1px'>";

            var exportTable = $('#' + id).clone();
            exportTable.find('input').each(function (index, elem) { $(elem).remove(); });
            tab_text = tab_text + exportTable.html();
            //console.log('export==' + exportTable.html());
            tab_text = tab_text + '</table></body></html>';
            var fileName = name + '_' + parseInt(Math.random() * 10000000000) + '.xls';
           // console.log('tab_text=' + tab_text);
            //Save the file

            var blob = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" });//application/octet-stream
            //var blob = new Blob([tab_text], { type: "application/vnd.openxmlformats-package.relationships+xml" });//application/octet-stream
           // var blob = new Blob([tab_text], { type: "application/octet-stream" }); 
       //use //http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js 
            window.saveAs(blob, fileName);
        }

调用此函数我使用fnExcelReportfile('MyTable','MyFileName');

当我点击导出按钮时,文件已创建,当我尝试打开它时会出现一个带有消息的弹出窗口:

  

您尝试打开的文件'name.ext'的格式与文件扩展名指定的格式不同。在打开文件之前,请验证文件是否已损坏且是否来自受信任的源。你想现在打开文件吗?

当我单击确定时,应用了样式,但问题是弹出消息

第二次解决方案:

我从buton.html5.js

复制了这段代码
        var excelStrings = {
            "_rels/.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
            <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\
                <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>\
            </Relationships>',

                            "xl/_rels/workbook.xml.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
            <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\
                <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>\
            </Relationships>',

                            "[Content_Types].xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
            <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\
                <Default Extension="xml" ContentType="application/xml"/>\
                <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\
                <Default Extension="jpeg" ContentType="image/jpeg"/>\
                <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>\
                <Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>\
            </Types>',

                            "xl/workbook.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
            <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">\
                <fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="24816"/>\
                <workbookPr showInkAnnotation="0" autoCompressPictures="0"/>\
                <bookViews>\
                    <workbookView xWindow="0" yWindow="0" windowWidth="25600" windowHeight="19020" tabRatio="500"/>\
                </bookViews>\
                <sheets>\
                    <sheet name="Sheet1" sheetId="1" r:id="rId1"/>\
                </sheets>\
            </workbook>',

                            "xl/worksheets/sheet1.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\
            <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">\
                <sheetData>\
                    __DATA__\
                </sheetData>\
            </worksheet>'
        };

        function fnExcelTest() {
            var dt = $('#MyTable').DataTable();
            var data = dt.buttons.exportData();

            var xml = '';//"<table border='1px'>";

                xml += addRow(data.header);


            for (var i = 0, ien = data.body.length ; i < ien ; i++) {
                xml += addRow(data.body[i]);
            }

            //if (config.footer) {
            //    xml += addRow(data.footer);
            //}
            //xml += '</table>';

            var zip = new window.JSZip();
            var _rels = zip.folder("_rels");
            var xl = zip.folder("xl");
            var xl_rels = zip.folder("xl/_rels");
            var xl_worksheets = zip.folder("xl/worksheets");

            zip.file('[Content_Types].xml', excelStrings['[Content_Types].xml']);
            _rels.file('.rels', excelStrings['_rels/.rels']);
            xl.file('workbook.xml', excelStrings['xl/workbook.xml']);
            xl_rels.file('workbook.xml.rels', excelStrings['xl/_rels/workbook.xml.rels']);
            xl_worksheets.file('sheet1.xml', excelStrings['xl/worksheets/sheet1.xml'].replace('__DATA__', xml));               

              //using http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js 
            window.saveAs(zip.generate({ type: "blob" }),
            'MyFileName.xlsx'
           );                
        }

        var addRow = function (row) {
            var cells = [];

            for (var i = 0, ien = row.length ; i < ien ; i++) {                   

                cells.push(                       
                    '<c t="inlineStr"><is><t>' + row[i] + '</t></is></c>'                       
                );
            }

            return '<row>' + cells.join('') + '</row>';               
        };

当我点击导出按钮时,数据得到支持,当我打开文件时,它已正确打开但没有应用样式

是否有方法在第二个解决方案中应用某种样式 或者消除第一种解决方案中出现的警告?

由于

0 个答案:

没有答案