在angularjs中使用Json数组生成Word文档

时间:2019-06-10 04:32:38

标签: json angularjs file

我有一个对象的Json数组,如下所示

[{name: test1, age:20},{name: test2, age:23},{name: test3, age:30}]

我想将这些值打印到Microsoft Word文档中的表中。换句话说,我想使用angularjs生成具有以上值的Word文档,该值显示在表格中。我该怎么办?

1 个答案:

答案 0 :(得分:1)

我可以在不使用任何第三方库的情况下实现以下目的。在这里,我在HTML表中显示值,该表将转换为Word文档。

<script>
$scope.arrayValFunc = function()
{
$scope.arrayVal =[];
//some code to assign values to the json array

}

$scope.downloadWordDoc = Export2Doc(element, filename = ''){
    var preHtml = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>";
    var postHtml = "</body></html>";
    var html = preHtml+document.getElementById(element).innerHTML+postHtml;

    var blob = new Blob(['\ufeff', html], {
        type: 'application/msword'
    });

    // Specify link url
    var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);

    // Specify file name
    filename = filename?filename+'.doc':'document.doc';

    // Create download link element
    var downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = url;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }

    document.body.removeChild(downloadLink);
}

</script>

<html>
<div id="divOne">
<table>
<tr ng-repeat="record in arrayVal">
<th>Name</th>
<th>Age</th>
<tr>
<td>{{record.name}}</td>
<td>{{record.age}}</td>
</tr>
</div>
<input type="submit" ng-click="downloadWordDoc('divOne');"/>
</html>