最近在作一個導入導出Excel的功能,導出其餘類型的文件都比較熟悉,可是導入跟導出一個Excel仍是稍微特殊點。根據此次的經驗,寫了個導出的小樣例。html
整體思路就是json數據的key,value跟Excel的行列轉換,還有就是解決數據在Excel表格中存放的位置,區域問題。git
這裏要用到的兩個小插件,一個是xslx.js,一個是FileSaver.js,前者是來處理生成Excel的,後者是用來把文件下載保存到本地的。github
下載地址:json
https://github.com/eligrey/FileSaver.jsspa
https://github.com/SheetJS/js-xlsx/tree/028d7010a516383cb9a2fdd0f0a919392e77600a/demos/angular插件
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>導出生成excel</title> 7 <script src="js/xlsx.full.min.js"></script> 8 <script src="js/FileSaver.min.js"></script> 9 </head> 10 11 <body> 12 <button onclick="downloadExl(students)">導出</button> 13 <script> 14 var students = [{ 15 "name": "小明1", 16 "age": "6", 17 "sex": "男", 18 "height": "60" 19 }, { 20 "name": "小明2", 21 "age": "7", 22 "sex": "男", 23 "height": "70" 24 }, { 25 "name": "小明3", 26 "age": "8", 27 "sex": "男", 28 "height": "80" 29 }]; 30 function downloadExl(data, type) { 31 32 var keys = Object.keys(data[0]); 33 var firstRow = {}; 34 keys.forEach(function (item) { 35 firstRow[item] = item; 36 }); 37 data.unshift(firstRow); 38 39 var content = {}; 40 41 // 把json格式的數據轉爲excel的行列形式 42 var sheetsData = data.map(function (item, rowIndex) { 43 return keys.map(function (key, columnIndex) { 44 return Object.assign({}, { 45 value: item[key], 46 position: (columnIndex > 25 ? getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1), 47 }); 48 }); 49 }).reduce(function (prev, next) { 50 return prev.concat(next); 51 }); 52 53 sheetsData.forEach(function (item, index) { 54 content[item.position] = { v: item.value }; 55 }); 56 57 //設置區域,好比表格從A1到D10,SheetNames:標題, 58 var coordinate = Object.keys(content); 59 var workBook = { 60 SheetNames: ["helloSheet"], 61 Sheets: { 62 "helloSheet": Object.assign({}, content, { "!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1] }), 63 } 64 }; 65 //這裏的數據是用來定義導出的格式類型 66 var excelData = XLSX.write(workBook, { bookType: "xlsx", bookSST: false, type: "binary" }); 67 var blob = new Blob([string2ArrayBuffer(excelData)], { type: "" }); 68 saveAs(blob, "hello.xlsx"); 69 } 70 //字符串轉字符流 71 function string2ArrayBuffer(s) { 72 var buf = new ArrayBuffer(s.length); 73 var view = new Uint8Array(buf); 74 for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF; 75 return buf; 76 } 77 // 將指定的天然數轉換爲26進製表示。映射關係:[0-25] -> [A-Z]。 78 function getCharCol(n) { 79 let temCol = "", 80 s = "", 81 m = 0 82 while (n > 0) { 83 m = n % 26 + 1 84 s = String.fromCharCode(m + 64) + s 85 n = (n - m) / 26 86 } 87 return s 88 } 89 </script> 90 </body> 91 92 </html>