浏览器端JS导出EXCEL

浏览器端JS导出EXCEL

       FileSaver.js 实现了在本身不支持 HTML5 W3C saveAs() FileSaver 接口的浏览器支持文件保存。FileSaver.js 在客户端保存文件的解决方案,并且可以让 Web 应用完美的生成文件, 或者保存不应该发送到外部服务器的一些敏感信息。是一种简单易用实现的利用 JavaScript/JS 在浏览器端保存文件的方案。

实现浏览器端生成并保存文件的 JavaScript 库 FileSaver.js 使用说明:

一、引入 JavaScript 文件:

 

[javascript] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <script src="path/FileSaver.js"/>  

二、例子:

保存成文本文件

[javascript] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});  
  2. saveAs(blob, "hello world.txt");  
保存成图片

 

[javascript] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. var canvas = document.getElementById("my-canvas"), ctx = canvas.getContext("2d");// draw to canvas...canvas.toBlob(function(blob) {  
  2.     saveAs(blob, "pretty image.png");  
  3. });  
支持的浏览器:

最简单的完整示例:

通过使用FileSave.js实现FileSave.js插件https://github.com/eligrey/FileSaver.js/

注意点:

1.FileSaver.js实现浏览器写入文件到本地磁盘,对于不支持Blob的浏览器需要使用Blob.js。

2.输出内容包含中文的话,内容前面加上?来防止中文乱码。

完整(各种文件格式下载)DEMO源代码下载(包含所有Demo和用到的Js文件):http://download.csdn.net/detail/pplsunny/9673540

html页面代码如下:

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
    1. <!DOCTYPE html>  
    2. <html>  
    3. <head>  
    4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
    5. <title>IE导出CSV</title>  
    6. <script src="FileSaver.js"></script>  
    7. <script>  
    8. window.onload = function(){  
    9.     function exportCsv2(){  
    10.         //Excel打开后中文乱码添加如下字符串解决  
    11.         var exportContent = "uFEFF";  
    12.         var blob = new Blob([exportContent+"标题,标题,标题 1,2,3 4,5,6"],{type: "text/plain;charset=utf-8"});  
    13.         saveAs(blob, "hello world.csv");  
    14.     }  
    15.     document.getElementById("J_export").onclick = function(){  
    16.         exportCsv2();  
    17.     }  
    18. }  
    19. </script>  
    20. </head>  
    21. <body>  
    22.     <href="javascript:;" id="J_export">导出</a>  
    23. </body>  
    24. </html>  
原文地址:https://www.cnblogs.com/zxtceq/p/6678136.html