excel-preview.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. ;(function (factory) {
  2. if (typeof define === 'function' && define.amd) {
  3. define(['jquery'], factory);
  4. } else {
  5. factory(jQuery);
  6. }
  7. }(function ($) {
  8. 'use strict';
  9. // Default options
  10. var pluginName = "excelPreview",
  11. defaults = {
  12. height: 500
  13. };
  14. // Constructor, initialise everything you need here
  15. var Plugin = function (element, options) {
  16. this.element = element;
  17. this.settings = $.extend({}, defaults, options);
  18. this._defaults = defaults;
  19. this._name = pluginName;
  20. defaults = this.settings;
  21. this.init();
  22. };
  23. // Plugin methods and shared properties
  24. Plugin.prototype = {
  25. // Reset constructor - http://goo.gl/EcWdiy
  26. constructor: Plugin,
  27. init: function () {
  28. var e = this;
  29. $(e.element).prev('input[type=file]').fileinput({
  30. language: 'zh',
  31. showUpload: false,
  32. dropZoneEnabled: false,
  33. hideThumbnailContent: true,
  34. showPreview: false,
  35. allowedFileExtensions: ['xlsx'],
  36. elErrorContainer: '#kartik-file-errors',
  37. // showRemove: false
  38. }).on('change', function (file) {
  39. e.excelPreview(file);
  40. })
  41. },
  42. excelPreview: function (file) {
  43. var e = this;
  44. loadFile(file, e.element);
  45. $(e.element).prev('input[type=file]').fileinput('refresh');
  46. return true;
  47. }
  48. }
  49. function loadFile(event, ele) {
  50. let file = event.target.files;
  51. if(file.length == 0)return;
  52. var fileReader = new FileReader();
  53. fileReader.onload = (ev) => {
  54. try {
  55. var data = ev.target.result,
  56. workbook = XLSX.read(data, {
  57. type: 'binary',
  58. cellStyles: true
  59. }), // 以二进制流方式读取得到整份excel表格对象
  60. persons = []; // 存储获取到的数据
  61. } catch (e) {
  62. console.log('文件类型不正确');
  63. return;
  64. }
  65. //所有表名
  66. var sheetNames = workbook.SheetNames; // 返回 ['sheet1', 'sheet2']
  67. initTabs(ele, sheetNames, workbook);
  68. // //根据表名获取对应某张表
  69. // var worksheet = workbook.Sheets[sheetNames[0]];
  70. }
  71. fileReader.readAsBinaryString(file[0]);
  72. }
  73. function initTabs(ele, sheetNames, workbook) {
  74. $(ele).empty().append(`<div class="box box-default">
  75. <div class="excel-box">
  76. <ul class="nav nav-tabs" role="tablist">
  77. </ul>
  78. <div class="tab-content" >
  79. <div role="tabpanel" class="tab-pane active">
  80. </div>
  81. </div>
  82. </div>
  83. </div>`);
  84. sheetNames.forEach(sheet => {
  85. let tabNav = $(ele).find(".nav-tabs");
  86. let nav = $(`<li role="presentation"><a role="tab" data-toggle="tab">${sheet}</a></li>`);
  87. nav.find('a').on('click', (e) => {
  88. tabChange($(e.target), workbook, tabNav);
  89. });
  90. tabNav.append(nav);
  91. tabChange(tabNav.find(' li:first > a'), workbook, tabNav);
  92. tabNav.find("li:first").addClass('active');
  93. })
  94. }
  95. function getTableData(sheet) {
  96. const headers = []
  97. const range = XLSX.utils.decode_range(sheet['!ref'])
  98. let C
  99. const R = range.s.r /* start in the first row */
  100. for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
  101. var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
  102. headers.push({
  103. field: 'column_' + C,
  104. title: 'column_' + C
  105. })
  106. }
  107. let datas = [];
  108. for(let rowIndex = range.s.r; rowIndex <= range.e.r; ++rowIndex) {
  109. let data = {};
  110. for (let colIndex = range.s.c; colIndex <= range.e.c; ++colIndex) { /* walk every column in the range */
  111. var cell = sheet[XLSX.utils.encode_cell({ c: colIndex, r: rowIndex })]; /* find the cell in the first row */
  112. data['column_' + colIndex] = XLSX.utils.format_cell(cell);
  113. }
  114. datas.push(data);
  115. }
  116. return {
  117. columns: headers,
  118. data: datas
  119. }
  120. }
  121. function mergeCell(merge, $table) {
  122. let rowspan = Math.abs(merge.e.r - merge.s.r + 1);
  123. let colspan = Math.abs(merge.e.c - merge.s.c + 1);
  124. $table.bootstrapTable('mergeCells', {
  125. index: merge.s.r,
  126. field: 'column_' + merge.s.c,
  127. rowspan: rowspan,
  128. colspan: colspan
  129. });
  130. }
  131. function mergeCells(worksheet, $table) {
  132. var merges = worksheet['!merges'];
  133. if (!merges) { return; }
  134. merges.forEach((merge, index) => {
  135. mergeCell(merge, $table);
  136. })
  137. }
  138. /**
  139. * key = AA2, start: A1, end = AA8, return {r: 1, c: 26}
  140. * @param {*} key
  141. * @param {*} start
  142. * @param {*} end
  143. */
  144. function getRowColIndex(key, start) {
  145. start = CUSTOM_UTIL.splitRC(start);
  146. key = CUSTOM_UTIL.splitRC(key);
  147. let col = key.c - start.c ;
  148. let row = CUSTOM_UTIL.computeR(key.r, start.r);
  149. return {
  150. r: col,
  151. c: row
  152. }
  153. }
  154. function setCellStyle(rowColIndex, style, $table) {
  155. var cellDom = $table.find("tbody").find('tr:eq(' + rowColIndex.r + ')').find('td:eq(' + rowColIndex.c + ')');
  156. if(style.font) {
  157. cellDom.css('fontWeight', style.font.bold ? 'bold' : 'normal');
  158. if(style.font.color) {
  159. style.font.color.rgb = style.font.color.rgb == 'FFFFFF' ? 'FF000000' : style.font.color.rgb;
  160. cellDom.css('color', CUSTOM_UTIL.rgbaToRgb(style.font.color.rgb));
  161. }
  162. }
  163. if (style.fill && style.fill.fgColor) {
  164. cellDom.css('backgroundColor', CUSTOM_UTIL.rgbaToRgb(style.fill.fgColor));
  165. }
  166. if (style.alignment && style.alignment.horizontal) {
  167. let alignMap = {'bottom': 'left', 'center': 'center', 'top': 'right'};
  168. cellDom.css('textAlign', alignMap[style.alignment.horizontal]);
  169. }
  170. }
  171. function setStyles(worksheet, $table) {
  172. var range = worksheet['!ref'].split(":");
  173. var start = range[0], end = range[1];
  174. for(let key in worksheet) {
  175. if(key >= start && key <= end) {
  176. var rowColIndex = getRowColIndex(key, start, end);
  177. var style = worksheet[key].s;
  178. if(!style) {return;}
  179. setCellStyle(rowColIndex, style, $table);
  180. }
  181. }
  182. }
  183. function loadTabContent(sheetName, workbook, $table) {
  184. var worksheet = workbook.Sheets[sheetName];
  185. var tableConf = {
  186. height: defaults.height,
  187. showHeader: false
  188. };
  189. var tableData = getTableData(worksheet);
  190. $.extend(tableConf, tableData)
  191. $table.bootstrapTable(tableConf);
  192. setStyles(worksheet, $table);
  193. mergeCells(worksheet, $table);
  194. }
  195. function tabChange(target, workbook, tabNav) {
  196. let sheetName = target.html();
  197. tabNav.find("li").removeClass('active');
  198. target.parent('li').addClass('active');
  199. let $table = $(`<div class="table-container"><table></table></div>`);
  200. tabNav.next('div.tab-content').find('.tab-pane').empty().append($table);
  201. loadTabContent(sheetName, workbook, $table.find('table'));
  202. }
  203. // Create the jQuery plugin
  204. $.fn[ pluginName ] = function (options) {
  205. // Do a deep copy of the options - http://goo.gl/gOSSrg
  206. options = $.extend(true, {}, defaults, options);
  207. return this.each(function () {
  208. var $this = $(this);
  209. // Create a new instance for each element in the matched jQuery set
  210. // Also save the instance so it can be accessed later to use methods/properties etc
  211. // e.g.
  212. // var instance = $('.element').data('plugin');
  213. // instance.someMethod();
  214. if ( !$.data( $this, "plugin_" + pluginName ) ) {
  215. $.data( $this, "plugin_" + pluginName, new Plugin( this, options ) );
  216. }
  217. });
  218. };
  219. // Expose defaults and Constructor (allowing overriding of prototype methods for example)
  220. $.fn[ pluginName ].defaults = defaults;
  221. $.fn[ pluginName ].Plugin = Plugin;
  222. }));