exportExcel.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
  2. function sheet2blob(sheet, sheetName) {
  3. sheetName = sheetName || 'sheet1';
  4. var workbook = {
  5. SheetNames: [sheetName],
  6. Sheets: {}
  7. };
  8. workbook.Sheets[sheetName] = sheet;
  9. // 生成excel的配置项
  10. var wopts = {
  11. bookType: 'xlsx', // 要生成的文件类型
  12. bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
  13. type: 'binary'
  14. };
  15. var wbout = XLSX.write(workbook, wopts);
  16. var blob = new Blob([s2ab(wbout)], {type:"application/octet-stream"});
  17. // 字符串转ArrayBuffer
  18. function s2ab(s) {
  19. var buf = new ArrayBuffer(s.length);
  20. var view = new Uint8Array(buf);
  21. for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  22. return buf;
  23. }
  24. return blob;
  25. }
  26. function openDownloadDialog(url, saveName)
  27. {
  28. if(typeof url == 'object' && url instanceof Blob)
  29. {
  30. url = URL.createObjectURL(url); // 创建blob地址
  31. }
  32. var aLink = document.createElement('a');
  33. aLink.href = url;
  34. aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
  35. var event;
  36. if(window.MouseEvent) event = new MouseEvent('click');
  37. else
  38. {
  39. event = document.createEvent('MouseEvents');
  40. event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  41. }
  42. aLink.dispatchEvent(event);
  43. }