下载 CSV 以便从表中获取 JSON 数据。整个 div
打印在 CSV 文件中
我已经在其他网站上尝试过解决方案
$scope.record=function(){
console.log("Export Records");`enter code here`
$http({
url: _BASE_URL_+'/get_records',
method:"GET"
})
.then(function(response) {
console.log(response.data);
$scope.reprtData=response.data;
//$scope.exportExcel();
/*document.getElementById('exportable').table2excel({
filename: "Table.xls"
});*/
var blob = new Blob([document.getElementById('exportable').innerHTML], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
});
saveAs(blob, "Report.csv");
});
}
这是我的maincontroller.js
<div>
<a type="button" ng-click="record()" class="btn btn-success" href="">
<i class="fa fa-file-excel-o" style="font-size: 16px;"></i>
Export Records
</a>
</div>
<div id="exportable" style="display">
<table width="100%" >
<thead>
<tr>
<th>Name</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in reprtData">
<td>{{item.name}}</td>
<td>{{item.date}}</td>
</tr>
</tbody>
</table>
</div>
这是示例数据
[0 … 99]
0:
$$hashKey: "object:13",
chapterName: "Light",
className: "VIII",
duration: null,
endTime: null,
id: 0,
ondate: "2018-03-12",
section: null,
startTime: null,
subjectName: null,
teacherName: "Editorial User1",
__proto__: Object
1:
$$hashKey: "object:14",
chapterName: "Light",
className: "VIII",
duration: null,
endTime: null,
id: 0,
ondate: "2018-03-12",
section: null,
startTime: null,
subjectName: null,
teacherName: "Editorial User1"
最佳答案
创建数据的可读 CSV 字符串并将其保存在变量中。
var data = 'chapterName,className,duration,endTime,id,ondate,section,startTime,subjectName,teacherName\n';
angular.forEach(response.data, function(e) {
data += (e.chapterName || '') + ','
+ (e.className || '') + ','
+ (e.duration || '') + ','
+ (e.endTime || '') + ','
+ (e.id || '') + ','
+ (e.ondate || '') + ','
+ (e.section || '') + ','
+ (e.startTime || '') + ','
+ (e.subjectName || '') + ','
+ (e.teacherName || '') + '\n';
});
然后使用这个函数
function downloadFile(filename, data) {
var link;
link = document.createElement('a');
link.setAttribute('href', data.replace(/#/g, '%23'));
link.setAttribute('download', filename);
link.style = 'visibility:hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
关于javascript - 将 json 导出到 CSV 在 angularjs 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292744/