Angular4 导出Excel文件

*.ts

把json数据导出到Excel文件

import * as FileSaver from 'file-saver';
import * as XLSX from 'xlsx';

exportAsExcelFile() {
let json = [{
"姓名": "***", "工號": "***", "英文名": "***", "部门": "**", "性别": "1", "手机": "+861**********",
"个人邮箱": "****@**.com"
}];
const worksheet : XLSX. WorkSheet = XLSX. utils. json_to_sheet( json);
const workbook : XLSX. WorkBook = { Sheets: { 'data': worksheet }, SheetNames: [ 'data'] };
const excelBuffer : any = XLSX. write( workbook, { bookType: 'xlsx', type: 'array' });
        //这里类型如果不正确,下载出来的可能是类似xml文件的东西或者是类似二进制的东西等
this. saveAsExcelFile( excelBuffer, "模板");
}

private saveAsExcelFile(buffer : any, fileName : string) {
const data : Blob = new Blob([ buffer], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
});
FileSaver. saveAs( data, fileName + '_export_' + new Date(). getTime() + '.xls');
         // 如果写成.xlsx,可能不能打开下载的文件,这可能与Excel版本有关
}


使用http服务下载Excel文件到本地

import { Http } from '@angular/http';
constructor(
private http : Http
) { }

exportService(){
let downloadUrl = `../../assets/模板.xls`;
return this. http. get( downloadUrl,{responseType: 3})
. map(res => {
return res;
});
}
exportAsExcelFile() {
// 下载时, 需将副档名改为 *. xls,否则可能打不开文件
this. exportService(). subscribe(res => {
// let res=res.json();可能要转化类型
var blob = new Blob([ res. json()], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var objectUrl = URL. createObjectURL( blob);
var a = document. createElement( 'a');
document.body. appendChild( a);
a. setAttribute( 'style', 'display:none');
a. setAttribute( 'href', objectUrl);
a. setAttribute( 'download', '模板.xls');
a. click();
document.body. removeChild( a);
//释放URL地址
URL. revokeObjectURL( objectUrl);
});
}

你可能感兴趣的:(angular)