Browse Source

插件化和gulp打包

zhuwei 5 years ago
parent
commit
17227a7989
10 changed files with 294 additions and 223 deletions
  1. 5 0
      .babelrc
  2. 1 0
      .gitignore
  3. 36 0
      css/excel-preview.css
  4. 13 0
      gulpfile.js
  5. 6 51
      index.html
  6. 0 0
      js/dist/excel-preview.min.js
  7. 0 169
      js/index.js
  8. 221 0
      js/src/excel-preview.js
  9. 0 0
      js/src/util.js
  10. 12 3
      package.json

+ 5 - 0
.babelrc

@@ -0,0 +1,5 @@
+  {
+    "presets": [
+      "env"
+    ]
+  }

+ 1 - 0
.gitignore

@@ -1 +1,2 @@
+package-lock.json
 node_modules/

+ 36 - 0
css/excel-preview.css

@@ -0,0 +1,36 @@
+		.excel-box {
+			min-height: 700px;
+		}
+		.box.box-default {
+		    border-top-color: #d2d6de;
+		}
+		.box {
+		    position: relative;
+		    border-radius: 3px;
+		    background: #ffffff;
+		    border-top: 3px solid #d2d6de;
+		    margin-bottom: 20px;
+		    width: 100%;
+		    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
+		    margin-top: 20px;
+		}
+		.content {
+			margin-top: 20px;
+		}
+		.excel-box {
+			padding: 20px;
+		}
+		.excel-box .nav-tabs > li.active {
+			border-top: 3px solid #d12610;
+			margin-top: 0;
+			position: relative;
+		}
+		.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
+			margin-right: 0px;
+		}
+		.nav-tabs>li>a {
+			border-radius: 0;
+		}
+		.tab-pane{
+			padding: 20px;
+		}

+ 13 - 0
gulpfile.js

@@ -0,0 +1,13 @@
+
+
+var gulp = require('gulp');
+var uglify = require('gulp-uglify'); //压缩
+var concat = require('gulp-concat');//合并
+var babel = require('gulp-babel');
+gulp.task('compressJS', function () {
+  return gulp.src(["js/src/*.js"])//原路径
+  	.pipe(babel()) //转换ES6代码
+    .pipe(concat("excel-preview.min.js"))//合并
+    .pipe(uglify({compress:true}))//压缩
+    .pipe(gulp.dest("js/dist"));//目标路径
+});

+ 6 - 51
index.html

@@ -6,44 +6,7 @@
 	<title>Excel Preview</title>
 	<link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
 	<link rel="stylesheet" href="node_modules/bootstrap-table/dist/bootstrap-table.min.css">
-	<style>
-		.excel-box {
-			min-height: 700px;
-		}
-		.box.box-default {
-		    border-top-color: #d2d6de;
-		}
-		.box {
-		    position: relative;
-		    border-radius: 3px;
-		    background: #ffffff;
-		    border-top: 3px solid #d2d6de;
-		    margin-bottom: 20px;
-		    width: 100%;
-		    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
-		    margin-top: 20px;
-		}
-		.content {
-			margin-top: 20px;
-		}
-		.excel-box {
-			padding: 20px;
-		}
-		.excel-box .nav-tabs > li.active {
-			border-top: 3px solid #d12610;
-			margin-top: 0;
-			position: relative;
-		}
-		.nav-tabs>li.active>a, .nav-tabs>li.active>a:focus, .nav-tabs>li.active>a:hover {
-			margin-right: 0px;
-		}
-		.nav-tabs>li>a {
-			border-radius: 0;
-		}
-		.tab-pane{
-			padding: 20px;
-		}
-	</style>
+	<link rel="stylesheet" href="css/excel-preview.css">
 </head>
 <body>
 
@@ -51,17 +14,7 @@
 		<section>
 			<div class="content">
 				<input type="file" name="file" id="file">
-				<div class="box box-default">
-					<div class="excel-box">
-						<ul class="nav nav-tabs" role="tablist" id="tabNav">
-						</ul>
-						<div class="tab-content" id="tabContent">
-							<div role="tabpanel" class="tab-pane active" id="tabPanel">
-								
-							</div>
-						</div>
-					</div>
-				</div>				
+				<div id="excelTable"></div>
 			</div>			
 		</section> 
 	</div>
@@ -71,7 +24,9 @@
 	<script src="node_modules/bootstrap-table/dist/bootstrap-table.min.js" type="text/javascript"></script>
 	<script src="node_modules/bootstrap-table/dist/locale/bootstrap-table-zh-CN.min.js" type="text/javascript"></script>
 	<script src="node_modules/xlsx-style/dist/xlsx.full.min.js" type="text/javascript"></script>
-	<script src="js/util.js"></script>
-	<script src="js/index.js"></script>
+	<script src="js/dist/excel-preview.min.js"></script>
+	<script type="text/javascript">
+	 	$("#excelTable").excelPreview({});
+	</script>
 </body>
 </html>

File diff suppressed because it is too large
+ 0 - 0
js/dist/excel-preview.min.js


+ 0 - 169
js/index.js

@@ -1,169 +0,0 @@
-(function() {
-	'use strict';
-	function getTableData(sheet) {
-		const headers = []
-		const range = XLSX.utils.decode_range(sheet['!ref'])
-		let C
-		const R = range.s.r /* start in the first row */
-		for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
-			var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
-			headers.push({
-				field: 'column_' + C,
-				title: 'column_' + C
-			})
-		}
-		let datas = [];
-		for(let rowIndex = range.s.r; rowIndex <= range.e.r; ++rowIndex) {
-			let data = {};
-			for (let colIndex = range.s.c; colIndex <= range.e.c; ++colIndex) { /* walk every column in the range */
-				var cell = sheet[XLSX.utils.encode_cell({ c: colIndex, r: rowIndex })]; /* find the cell in the first row */
-				data['column_' + colIndex] = XLSX.utils.format_cell(cell);
-			}
-			datas.push(data);
-		}
-
-		return {
-			columns: headers,
-			data: datas
-		}
-	}
-
-	function mergeCell(merge) {
-		let rowspan = Math.abs(merge.e.r - merge.s.r + 1);
-		let colspan = Math.abs(merge.e.c - merge.s.c + 1);
-		$('#table').bootstrapTable('mergeCells', {
-			index: merge.s.r, 
-			field: 'column_' + merge.s.c,
-			rowspan: rowspan, 
-			colspan: colspan
-		});
-	}
-
-	function mergeCells(worksheet) {
-		var merges = worksheet['!merges'];
-		if (!merges) { return; }
-		merges.forEach((merge, index) => {
-			mergeCell(merge);
-		})
-	}
-
-	//TODO 
-	/**
-	 * key = AA2, start: A1, end = AA8, return {r: 1, c: 26}
-	 * @param {*} key 
-	 * @param {*} start 
-	 * @param {*} end 
-	 */
-	function getRowColIndex(key, start) {
-		start = CUSTOM_UTIL.splitRC(start);
-		key = CUSTOM_UTIL.splitRC(key);
-		let col = key.c - start.c ;
-		let row = CUSTOM_UTIL.computeR(key.r, start.r);
-		return {
-			r: col,
-			c: row
-		}
-	}
-
-	function setCellStyle(rowColIndex, style) {
-		var cellDom = $("#table > tbody").find('tr:eq(' + rowColIndex.r + ')').find('td:eq(' + rowColIndex.c + ')');
-		if(style.font) {
-			cellDom.css('fontWeight', style.font.bold ? 'bold' : 'normal');
-			if(style.font.color) {
-				style.font.color.rgb = style.font.color.rgb == 'FFFFFF' ? 'FF000000' : style.font.color.rgb;
-				cellDom.css('color', CUSTOM_UTIL.rgbaToRgb(style.font.color.rgb));
-			}
-		}
-		if (style.fill && style.fill.fgColor) {
-			cellDom.css('backgroundColor', CUSTOM_UTIL.rgbaToRgb(style.fill.fgColor));
-		}
-		if (style.alignment && style.alignment.horizontal) {
-			let alignMap = {'bottom': 'left', 'center': 'center', 'top': 'right'};
-			cellDom.css('textAlign', alignMap[style.alignment.horizontal]);
-		}
-	}
-
-	function setStyles(worksheet) {
-		var range = worksheet['!ref'].split(":");
-		var start = range[0], end = range[1];
-		for(let key in worksheet) {
-			if(key >= start && key <= end) {
-				var rowColIndex = getRowColIndex(key, start, end);
-				var style = worksheet[key].s;
-				if(!style) {return;}
-				setCellStyle(rowColIndex, style);
-			}
-		}
-	}
-
-	function loadTabContent(sheetName, workbook) {
-		var worksheet = workbook.Sheets[sheetName];
-		var tableConf = {
-			height: 600,
-			showHeader: false
-		};
-		var tableData = getTableData(worksheet);
-		$.extend(tableConf, tableData)
-		$('#table').bootstrapTable(tableConf);
-		setStyles(worksheet);
-		mergeCells(worksheet);
-	}
-
-
-	function tabChange(target, workbook) {
-		let sheetName = target.html();
-		$("#tabNav > li").removeClass('active');
-		target.parent('li').addClass('active');
-		$("#tabPanel").empty().append('<div class="table-container"><table id="table"></table></div>');
-		loadTabContent(sheetName, workbook);
-		// $("#tabPanel").html(sheetName);
-	}
-
-	function initTabs(sheetNames, workbook) {
-		$("#tabNav").empty();
-		$("#tabPanel").empty();
-		sheetNames.forEach(sheet => {
-			let nav = $(`<li role="presentation"><a role="tab" data-toggle="tab">${sheet}</a></li>`);
-			nav.find('a').on('click', (e) => {
-				tabChange($(e.target), workbook);
-			});
-			$("#tabNav").append(nav);
-			tabChange($("#tabNav > li:first > a"), workbook);
-			$("#tabNav > li:first").addClass('active');
-		})
-	}
-
-	function loadFile(e) {
-		let file = e.target.files;
-		var fileReader = new FileReader();
-		fileReader.onload = (ev) => {
-		    try {
-		      var data = ev.target.result,
-		        workbook = XLSX.read(data, {
-							type: 'binary',
-							cellStyles: true
-		        }), // 以二进制流方式读取得到整份excel表格对象
-		        persons = []; // 存储获取到的数据
-		    } catch (e) {
-		      console.log('文件类型不正确');
-		      return;
-		    }
-
-		    //所有表名
-		    var sheetNames = workbook.SheetNames; // 返回 ['sheet1', 'sheet2']
-
-			initTabs(sheetNames, workbook);
-
-		    // //根据表名获取对应某张表
-		    // var worksheet = workbook.Sheets[sheetNames[0]];
-		}
- 		fileReader.readAsBinaryString(file[0]);
-	}
-
-	$(function() {
-		$("#file").on('change', function(e) {
-			loadFile(e);
-		})	
-	})
-
-})()

+ 221 - 0
js/src/excel-preview.js

@@ -0,0 +1,221 @@
+//excelPreview.js
+;(function ( $, window, document, undefined ) {
+    var pluginName = "excelPreview",
+
+    defaults = {
+        // name: "excelPreview"
+    };
+
+    // The actual plugin constructor
+    function Plugin ( element, options ) {
+            this.element = element;
+            // jQuery has an extend method which merges the contents of two or
+            // more objects, storing the result in the first object. The first object
+            // is generally empty as we don't want to alter the default options for
+            // future instances of the plugin
+            //
+            this.settings = $.extend( {}, defaults, options );
+            this._defaults = defaults;
+            this._name = pluginName;
+            this.init();
+    }
+
+    Plugin.prototype = {
+        init: function () {
+            var e = this;
+            $(e.element).prev('input[type=file]').on('change', function(file) {
+                e.excelPreview(file);
+            })  
+        },
+
+        excelPreview: function (file) {
+            var e = this;
+            loadFile(file, e.element);
+            return true;
+        }
+    };
+
+    function loadFile(event, ele) {
+        let file = event.target.files;
+        var fileReader = new FileReader();
+        fileReader.onload = (ev) => {
+            try {
+              var data = ev.target.result,
+                workbook = XLSX.read(data, {
+                            type: 'binary',
+                            cellStyles: true
+                }), // 以二进制流方式读取得到整份excel表格对象
+                persons = []; // 存储获取到的数据
+            } catch (e) {
+              console.log('文件类型不正确');
+              return;
+            }
+
+            //所有表名
+            var sheetNames = workbook.SheetNames; // 返回 ['sheet1', 'sheet2']
+
+            initTabs(ele, sheetNames, workbook);
+
+            // //根据表名获取对应某张表
+            // var worksheet = workbook.Sheets[sheetNames[0]];
+        }
+        fileReader.readAsBinaryString(file[0]);
+    }
+
+    function initTabs(ele, sheetNames, workbook) {
+        $(ele).empty().append(`<div class="box box-default">
+                    <div class="excel-box">
+                        <ul class="nav nav-tabs" role="tablist">
+                        </ul>
+                        <div class="tab-content" >
+                            <div role="tabpanel" class="tab-pane active">
+                                
+                            </div>
+                        </div>
+                    </div>
+                </div>`);
+
+        sheetNames.forEach(sheet => {
+            let tabNav = $(ele).find(".nav-tabs");
+            let nav = $(`<li role="presentation"><a role="tab" data-toggle="tab">${sheet}</a></li>`);
+            nav.find('a').on('click', (e) => {
+                tabChange($(e.target), workbook, tabNav);
+            });
+            tabNav.append(nav);
+            tabChange(tabNav.find(' li:first > a'), workbook, tabNav);
+            tabNav.find("li:first").addClass('active');
+        })
+    }
+
+    function getTableData(sheet) {
+        const headers = []
+        const range = XLSX.utils.decode_range(sheet['!ref'])
+        let C
+        const R = range.s.r /* start in the first row */
+        for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
+            var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
+            headers.push({
+                field: 'column_' + C,
+                title: 'column_' + C
+            })
+        }
+        let datas = [];
+        for(let rowIndex = range.s.r; rowIndex <= range.e.r; ++rowIndex) {
+            let data = {};
+            for (let colIndex = range.s.c; colIndex <= range.e.c; ++colIndex) { /* walk every column in the range */
+                var cell = sheet[XLSX.utils.encode_cell({ c: colIndex, r: rowIndex })]; /* find the cell in the first row */
+                data['column_' + colIndex] = XLSX.utils.format_cell(cell);
+            }
+            datas.push(data);
+        }
+
+        return {
+            columns: headers,
+            data: datas
+        }
+    }
+
+    function mergeCell(merge, $table) {
+        let rowspan = Math.abs(merge.e.r - merge.s.r + 1);
+        let colspan = Math.abs(merge.e.c - merge.s.c + 1);
+        $table.bootstrapTable('mergeCells', {
+            index: merge.s.r, 
+            field: 'column_' + merge.s.c,
+            rowspan: rowspan, 
+            colspan: colspan
+        });
+    }
+
+    function mergeCells(worksheet, $table) {
+        var merges = worksheet['!merges'];
+        if (!merges) { return; }
+        merges.forEach((merge, index) => {
+            mergeCell(merge, $table);
+        })
+    }
+
+    /**
+     * key = AA2, start: A1, end = AA8, return {r: 1, c: 26}
+     * @param {*} key 
+     * @param {*} start 
+     * @param {*} end 
+     */
+    function getRowColIndex(key, start) {
+        start = CUSTOM_UTIL.splitRC(start);
+        key = CUSTOM_UTIL.splitRC(key);
+        let col = key.c - start.c ;
+        let row = CUSTOM_UTIL.computeR(key.r, start.r);
+        return {
+            r: col,
+            c: row
+        }
+    }
+
+    function setCellStyle(rowColIndex, style, $table) {
+        var cellDom = $table.find("tbody").find('tr:eq(' + rowColIndex.r + ')').find('td:eq(' + rowColIndex.c + ')');
+        if(style.font) {
+            cellDom.css('fontWeight', style.font.bold ? 'bold' : 'normal');
+            if(style.font.color) {
+                style.font.color.rgb = style.font.color.rgb == 'FFFFFF' ? 'FF000000' : style.font.color.rgb;
+                cellDom.css('color', CUSTOM_UTIL.rgbaToRgb(style.font.color.rgb));
+            }
+        }
+        if (style.fill && style.fill.fgColor) {
+            cellDom.css('backgroundColor', CUSTOM_UTIL.rgbaToRgb(style.fill.fgColor));
+        }
+        if (style.alignment && style.alignment.horizontal) {
+            let alignMap = {'bottom': 'left', 'center': 'center', 'top': 'right'};
+            cellDom.css('textAlign', alignMap[style.alignment.horizontal]);
+        }
+    }
+
+    function setStyles(worksheet, $table) {
+        var range = worksheet['!ref'].split(":");
+        var start = range[0], end = range[1];
+        for(let key in worksheet) {
+            if(key >= start && key <= end) {
+                var rowColIndex = getRowColIndex(key, start, end);
+                var style = worksheet[key].s;
+                if(!style) {return;}
+                setCellStyle(rowColIndex, style, $table);
+            }
+        }
+    }
+
+    function loadTabContent(sheetName, workbook, $table) {
+        var worksheet = workbook.Sheets[sheetName];
+        var tableConf = {
+            height: 600,
+            showHeader: false
+        };
+        var tableData = getTableData(worksheet);
+        $.extend(tableConf, tableData)
+        $table.bootstrapTable(tableConf);
+        setStyles(worksheet, $table);
+        mergeCells(worksheet, $table);
+    }
+
+
+    function tabChange(target, workbook, tabNav) {
+        let sheetName = target.html();
+        tabNav.find("li").removeClass('active');
+        target.parent('li').addClass('active');
+        let $table = $(`<div class="table-container"><table></table></div>`);
+        tabNav.next('div.tab-content').find('.tab-pane').empty().append($table);
+        loadTabContent(sheetName, workbook, $table.find('table'));
+    }
+
+
+    $.fn[ pluginName ] = function ( options ) {
+        var e = this;
+            e.each(function() {
+                if ( !$.data( e, "plugin_" + pluginName ) ) {
+                    $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
+                }
+            });
+
+        // chain jQuery functions
+        return e;
+    };
+
+})( jQuery, window, document );

+ 0 - 0
js/util.js → js/src/util.js


+ 12 - 3
package.json

@@ -4,7 +4,8 @@
   "description": "Preview Excel online",
   "main": "index.js",
   "scripts": {
-    "test": "echo \"Error: no test specified\" && exit 1"
+    "test": "echo \"Error: no test specified\" && exit 1",
+    "build": "gulp compressJS"
   },
   "repository": {
     "type": "git",
@@ -21,10 +22,18 @@
   },
   "homepage": "https://github.com/sumile-ting/excelPreview#readme",
   "dependencies": {
-    "bootstrap": "^3.4.0",
+    "bootstrap": "^3.4.1",
     "bootstrap-table": "^1.13.1",
-    "jquery": "^3.3.1",
+    "jquery": "^3.4.0",
     "xlsx": "^0.14.1",
     "xlsx-style": "^0.8.13"
+  },
+  "devDependencies": {
+    "babel-core": "6.26.0",
+    "babel-preset-env": "^1.7.0",
+    "gulp": "^4.0.2",
+    "gulp-babel": "^7.0.0",
+    "gulp-concat": "^2.6.1",
+    "gulp-uglify": "^3.0.2"
   }
 }

Some files were not shown because too many files changed in this diff