使用自定义布局导出excel

时间:2016-10-27 05:34:41

标签: angularjs excel

我想在导出之前控制布局这个文件。例如:我想在导出之前通过代码修复宽度列,标题颜色,边框表或高行一行或 wordwrap 。可以给我一些建议库控制这个? 像这样: image excel file

当我尝试使用alasql设置宽度列时,我收到了这个错误。如何解决这个问题?:bug when using alasql lib

1 个答案:

答案 0 :(得分:0)

您可以使用javascript通过自定义模板创建Excel。请查看此http://jsfiddle.net/kmqz9/223/ <a id="test" href="" onclick="downloadReport();">Test.xls</a>

// Test script to generate a file from JavaScript such that MS Excel will honor non-ASCII characters..


testJson = [
{
    "name": "First Name",
    "city": "City",
    "country":" Country of Manas",
    "birthdate": "Birth Date",
    "amount": "Paisa Ketey"
},
{
    "name": "Tony Peña",
    "city": "New York",
    "country": "United States",
    "birthdate": "1978-03-15",
    "amount": 42

},
{
    "name": "Ζαλώνης Thessaloniki",
    "city": "Athens",
    "country": "Greece",
    "birthdate": "1987-11-23",
    "amount": 42
}
];

// Simple type mapping; dates can be hard
// and I would prefer to simply use `datevalue`
// ... you could even add the formula in here.
testTypes = {
    "name": "String",
    "city": "String",
    "country": "String",
    "birthdate": "String",
    "amount": "String"
};

emitXmlHeader = function () {
    return '<?xml version="1.0"?>\n' +
           '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' +
           '<ss:Worksheet ss:Name="Sheet1">\n' +
           '<ss:Table>\n\n';
};

emitXmlFooter = function() {
    return '\n</ss:Table>\n' +
           '</ss:Worksheet>\n' +
           '</ss:Workbook>\n';
};

jsonToSsXml = function (jsonObject) {
    var row;
    var col;
    var xml;
    var data = typeof jsonObject != "object" 
             ? JSON.parse(jsonObject) 
             : jsonObject;

    xml = emitXmlHeader();

    for (row = 0; row < data.length; row++) {
        xml += '<ss:Row>\n';

        for (col in data[row]) {
            xml += '  <ss:Cell>\n';
            xml += '    <ss:Data ss:Type="' + testTypes[col]  + '">';
            xml += data[row][col] + '</ss:Data>\n';
            xml += '  </ss:Cell>\n';
        }

        xml += '</ss:Row>\n';
    }

    xml += emitXmlFooter();
    return xml;  
};

console.log(jsonToSsXml(testJson));

function download (content, filename, contentType) {
    if (!contentType) contentType = 'application/octet-stream';
    var a = document.getElementById('test');
    var blob = new Blob([content], {
        'type': contentType
    });
    a.href = window.URL.createObjectURL(blob);
    a.download = filename;
    window.navigator.msSaveOrOpenBlob(blob,filename);
};

function downloadReport()
{
    download(jsonToSsXml(testJson), 'test.xls',       'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
};