Angular 2 使用 FileSaver.js 的最佳方法 [英] Angular 2 Best approach to use FileSaver.js

查看:24
本文介绍了Angular 2 使用 FileSaver.js 的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 FileSaver.js (https://github.com/eligrey/FileSaver.js/) 在我的 Angular2 应用程序中.

I need to use the FileSaver.js (https://github.com/eligrey/FileSaver.js/) in my Angular2 application.

我知道我可以将它作为脚本文件添加到主 html 页面中,它会起作用.但我想知道在 Angular 2 (TypeScript) 应用程序的情况下最好的方法是什么,这样我就可以调用 window.saveAs 来保存文件.

I know I can add it as a script file in main html page and it will work. But I was wondering what would be the best approach in case of an Angular 2 (TypeScript) application so that I can just call window.saveAs to save file.

推荐答案

我设法使用这种方法 (Angular-CLI) 使其工作:

I managed to get it work using this approach (Angular-CLI):

npm install file-saver --save
npm install @types/file-saver --save

在组件中导入 Filesaver 之后:

After that import Filesaver in component:

import * as FileSaver from 'file-saver';

你可以这样使用它:

    let blob = new Blob([document.getElementById('exportDiv').innerHTML], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-16le"
        });
    FileSaver.saveAs(blob, "export.xls");    

如您所见,您无需在 angular-cli.json 中添加任何内容.只需安装库及其类型,导入它,您就可以开始使用了.

As you can see, you don't have to add anything in angular-cli.json. Just install library and it's types, import it and you are ready to go.

这篇关于Angular 2 使用 FileSaver.js 的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆