xlsx Excel 操作
xlsx Excel 操作
一个基于 SheetJS 的Excel文件操作,它是目前在浏览器中包含最全的Excel操作的脚本库。
注:你也可以使用 js-xlsx 是另一个 Fork sheetjs 的类库,它提供包括:图片、样式等额外选项。最后你利用 callback 选项重要渲染你的 excel。
依赖
yarn add file-saver
由于 sheetjs 脚本大小以及对 Excel 的操作并不是刚需的原因,因此采用一种延迟加载脚本的形式,可以通过全局配置配置来改变默认 CDN 路径(或使用本地路径),默认情况下使用 //cdn.bootcss.com/xlsx/0.15.6/xlsx.full.min.js。
import { XlsxModule } from '@delon/abc/xlsx';
代码演示
导入
导入Excel并输出JSON,支持 File、URL 格式。
import { Component } from '@angular/core';import { XlsxService } from '@delon/abc/xlsx';@Component({ selector: 'components-xlsx-import', template: ` <button nz-button (click)="url()">Via Url</button> <input type="file" (change)="change($event)" multiple="false" class="ml-sm" /> <p class="mt-sm">result: {{data | json}}</p> `,})export class ComponentsXlsxImportComponent { constructor(private xlsx: XlsxService) {} data: any; url() { this.xlsx.import(`./assets/demo.xlsx`).then(res => this.data = res); } change(e: Event) { const node = e.target as HTMLInputElement; this.xlsx.import(node.files![0]).then(res => this.data = res); node.value = ''; }}
导出
导出Excel并自动弹出保存对话框。
import { Component } from '@angular/core';import { STColumn } from '@delon/abc/st';import { XlsxService } from '@delon/abc/xlsx';@Component({ selector: 'components-xlsx-export', template: ` <button nz-button (click)="download()">Export</button> <st [data]="users" [ps]="3" [columns]="columns" class="mt-sm"></st> `,})export class ComponentsXlsxExportComponent { constructor(private xlsx: XlsxService) {} users: any[] = Array(100) .fill({}) .map((_item: any, idx: number) => { return { id: idx + 1, name: `name ${idx + 1}`, age: Math.ceil(Math.random() * 10) + 20, }; }); columns: STColumn[] = [ { title: '编号', index: 'id', type: 'checkbox' }, { title: '姓名', index: 'name' }, { title: '年龄', index: 'age' }, ]; download() { const data = [this.columns.map(i => i.title)]; this.users.forEach(i => data.push(this.columns.map(c => i[c.index as string])), ); this.xlsx.export({ sheets: [ { data: data, name: 'sheet name', }, ], }); }}
API
LazyService
| 成员 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| import(fileOrUrl: File | string) | 导入Excel,返回 JSON | Promise<{ [key: string]: any[][] }> | - | |---|---|---|---|
| export(options: XlsxExportOptions) | 导出Excel | Promise<void> | - |
|---|---|---|---|
XlsxExportOptions
| 成员 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| [sheets] | 数据源 | { [sheet: string]: WorkSheet } | XlsxExportSheet[] | - | |---|---|---|---|
| [filename] | Excel文件名 | string | export.xlsx |
|---|---|---|---|
| [opts] | Excel写入选项,见 WritingOptions | WritingOptions | - |
|---|---|---|---|
| [callback] | 保存前触发 | (wb: WorkBook) => void | - |
|---|---|---|---|
xlsx
xlsx 指令。
<div [xlsx]="XlsxExportOptions">导出</div>
常见问题
csv格式
文件编码格式必须是 UTF8 with BOM 才能解析。
