我正在学习angular2,我想在我的项目中使用js-xlsx库.
我安装了xlsx npm install xlsx 和jszip npm install jszip并将它们添加到我的index.html中
<script src="node_modules/xlsx/dist/xlsx.core.min.js"></script>
<script src="node_modules/jszip/dist/jszip.min.js"></script>
并添加了打字稿定义 tsd install xlsx
我正在使用webpack
但是当我用它时
import * as xlsx from 'xlsx';
Run Code Online (Sandbox Code Playgroud)
但我得到错误
module build failed: error: cannot resolve module 'xlsx'
以下是使用Angular 2/4上的js-xlsx lib从对象数组导出xlsx文件的工作组件:
import { Component, OnInit } from '@angular/core';
import { utils, write, WorkBook } from 'xlsx';
import { saveAs } from 'file-saver';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
table = [
{
First: 'one',
Second: 'two',
Third: 'three',
Forth: 'four',
Fifth: 'five'
},
{
First: 'un',
Second: 'deux',
Third: 'trois',
Forth: 'quatre',
Fifth: 'cinq'
},
];
ngOnInit() {
const ws_name = 'SomeSheet';
const wb: WorkBook = { SheetNames: [], Sheets: {} };
const ws: any = utils.json_to_sheet(this.table);
wb.SheetNames.push(ws_name);
wb.Sheets[ws_name] = ws;
const wbout = write(wb, { bookType: 'xlsx', bookSST: true, type:
'binary' });
function s2ab(s) {
const buf = new ArrayBuffer(s.length);
const view = new Uint8Array(buf);
for (let i = 0; i !== s.length; ++i) {
view[i] = s.charCodeAt(i) & 0xFF;
};
return buf;
}
saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), 'exported.xlsx');
}
}
Run Code Online (Sandbox Code Playgroud)
您必须安装xlsx和文件保护程序才能工作.
有关从Angular2/4上的jsons数组导出xlsx文件的工作示例:
https://github.com/bogdancar/xlsx-json-to-xlsx-demo-Angular2
小智 5
一种更简单的方法是根本不使用打字:
像往常一样将xlsx.core.min.js添加到index.html文件中.(我正在使用angular-cli,所以我的js文件被复制到dist/vendor目录)
<script src="vendor/xlsx/dist/xlsx.core.min.js"></script>
在您的模块中,不要使用导入,而是在您的导入块下声明XLSX.
declare var XLSX: any;
如果您正在使用angular-cli,则需要将xlsx添加到angular-cli-build.js文件中.
module.exports = function(defaults) {
return new Angular2App(defaults, {
vendorNpmFiles: [
'systemjs/dist/system-polyfills.js',
'systemjs/dist/system.src.js',
'zone.js/dist/**/*.+(js|js.map)',
'es6-shim/es6-shim.js',
'reflect-metadata/**/*.+(ts|js|js.map)',
'rxjs/**/*.+(js|js.map)',
'@angular/**/*.+(js|js.map)',
'moment/moment.js',
....
'xlsx/**/*.+(js|js.map)'
]})
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20946 次 |
| 最近记录: |