1.導入導出功能操作步驟
導入:"下載導入模板" -->保存文件到本地-->在模板中輸入要導入的數據行-->"導入"-->選擇錄入數據的模板文件-->"確定"
導出:"導出"-->保存Excel文件到本地。
2.功能實現原理
2.1.外部組件依賴說明
(1)數據庫訪問相關:mysql-connector-jaca-5.0.8-bin.jar
c3p0-0.9.1.2.jar
commons-dbutils-1.4.jar
commons-io-2.6.jar
commons-logging-1.1.1.jar
(2)前端jsp頁面jstl相關:jstl.jar
standard.jar
(3)導入功能相關:jquery-EasyUI(前端組件)
commons-fileupload.jar
poi-3.17.jar
poi-ooxml-3.17.jar
poi-ooxml-schemas-3.17.jar
xmlbeans-2.6.0.jar
commons-collections4-4.1.jar
commons-beanutils-1.8.0.jar
slf4j-api-1.7.5.jar
(4)導出功能相關:jquery-table2excel(前端組件)
如果是maven工程,pom相關依賴:
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>commons-collections4</groupId> <artifactId>commons-collections4</artifactId> <version>4.1</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency>
2.2.功能實現原理說明:
(1)導入:利用jquery-EasyUI組件展示上傳文件對話框,選擇目標excel文件;利用commons-fileupload組件解析和處理前端傳遞過來
的excel文件流數據;利用poi組件解析excel文件內容,轉換成數據庫表對象結構,利用c3p0、dbutils組件保存到數據庫表中。
(2)導出:利用table2excel組件導出表格內容到目標excel文件。
3.功能實現步驟
(1)拷貝需要引入的依賴組件包和util包下的工具類代碼到工程中。
(2)在需要導入導出的目標庫表對象類中,將excel文件相關的幾個字段屬性,增加"@ExcelCell"注解。參考(Product.java)。
注意:類中屬性的數據類型只能為包裝類型(如String,Double等,不包含Integer),不能為基本類型(int,double等)。
index屬性值必須與excel文件中的數據記錄順序一致。
(3)根據對象類結構,創建和上傳導入模板文件到服務器文件夾,參考(WEB-INF/template/product.xlsx),
修改DownloadImportTemplateServlet里對應的文件名。
(4)增加導入excel功能代碼,參考(ProductService.java中importProductDataFromExcel方法)。
(5)增加導出功能代碼,參考(pagination.jsp中export2Excel方法)。
下面是前端頁面pageination.jsp代碼

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <link rel="stylesheet" href="./resource/css/pagination.css"> <link rel="stylesheet" type="text/css" href="./jquery-EasyUI/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="./jquery-EasyUI/themes/icon.css"> <script type="text/javascript" src="./resource/js/jquery-2.1.1.js"></script> <script type="text/javascript" src="./resource/js/jquery-table2excel/src/jquery.table2excel.js"></script> <script type="text/javascript" src="./jquery-EasyUI/js/jquery.easyui.min.js"></script> <script type="text/javascript" src="./resource/js/jquery.form.js"></script> <script type="text/javascript"> function importExcel() { var options = { type: 'post', url: 'importExcelData', dataType: 'json', success: function (json) { alert(json.message); location.reload(); }, error: function() { alert("error"); } }; $('#uploadfile-form').ajaxSubmit(options); $('#import-dialog').dialog('close'); } function export2Excel() { $("#table").table2excel({ // exclude CSS class exclude: ".noExl", sheetName: "product", filename: "product.xls" }); } </script> </head> <body> <div> <a href="DownloadImportTemplate" class="easyui-linkbutton">下載導入模板</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#import-dialog').dialog('open')">導入</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="export2Excel()">導出</a> </div> <table id="table" border="1" cellspacing="" cellpadding="" width="100%"> <tr> <th>序號</th> <th>名稱</th> <th>價格</th> <th>分類</th> <th>庫存數量</th> </tr> <c:forEach var="product" items="${pageBean.ps}" varStatus="vs"> <tr> <td>${vs.count}</td> <td>${product.name}</td> <td>${product.price}</td> <td>${product.category}</td> <td>${product.pnum}</td> </tr> </c:forEach> </table> <div align="center"> <ul class="pagination"> <c:if test="${pageBean.currentPage==1}"> <li class="disabled"><a href="#">«上一頁</a></li> </c:if> <c:if test="${pageBean.currentPage!=1}"> <li><a href="FindProductByPage?currentPage=${pageBean.currentPage-1}¤tCount=20">«上一頁</a></li> </c:if> <c:forEach begin="1" end="${pageBean.totalPage}" var="pageNum"> <c:if test="${pageNum==pageBean.currentPage}"> <li class="active"><a href="#">${pageNum}</a></li> </c:if> <c:if test="${pageNum!=pageBean.currentPage}"> <li><a href="FindProductByPage?currentPage=${pageNum}¤tCount=20">${pageNum}</a></li> </c:if> </c:forEach> <c:if test="${pageBean.currentPage==pageBean.totalPage || pageBean.totalPage==0}"> <li class="disabled"><a href="#">»下一頁</a></li> </c:if> <c:if test="${pageBean.currentPage!=pageBean.totalPage && pageBean.totalPage!=0}"> <li><a href="FindProductByPage?currentPage=${pageBean.currentPage+1}¤tCount=20">»下一頁</a></li> </c:if> </ul> </div> <%--導入對話框--%> <div id="import-dialog" class="easyui-dialog" title="Basic Dialog" data-options="iconCls:'icon-save',closed:true,buttons:'#import-dialog-button'" style="width:400px;height:200px;padding:10px"> <form id="uploadfile-form" method="post" action="" enctype="multipart/form-data"> 選擇文件:<input type="file" name="UPLOAD_FILE"> </form> </div> <%--導入對話框底部按鈕--%> <div id="import-dialog-button"> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="importExcel()">Save</a> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="$('#import-dialog').dialog('close')">Close</a> </div> </body> </html>
實體類Product.java代碼

package graduation.sample.entity; import graduation.sample.util.excel.ExcelCell; public class Product { private String id; @ExcelCell(index = 2) private String name; @ExcelCell(index = 3) private Double price; @ExcelCell(index = 4) private String category; public Double getPnum() { return pnum; } public void setPnum(Double pnum) { this.pnum = pnum; } @ExcelCell(index = 5) private Double pnum; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
模板下載DownloadImportTemplateServlet代碼

package graduation.sample.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; @WebServlet("/DownloadImportTemplate") public class DownloadImportTemplateServlet extends HttpServlet { private static final String FILE_PATH = "/WEB-INF/template/"; private static final String FILE_NAME = "product.xlsx"; private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置ContentType字段值 response.setContentType("text/html;charset=utf-8"); //設置相應消息編碼 response.setCharacterEncoding("utf-8"); //設置請求消息編碼 request.setCharacterEncoding("utf-8"); //獲取所要下載的文件名稱 //對文件名稱編碼 String filename = new String(FILE_NAME.trim().getBytes("iso8859-1"), "UTF-8"); // 通知瀏覽器以下載的方式打開 response.addHeader("Content-Type", "application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8")); // 通過文件流讀取文件 InputStream in = getServletContext().getResourceAsStream(FILE_PATH + FILE_NAME); // 獲取response對象的輸出流 OutputStream out = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; //循環取出流中的數據 while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
導入到Excel,ImportExcelDataServlet代碼

package graduation.sample.servlet; import graduation.sample.service.ProductService; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; /** * 導入Excel文件內容到數據庫表實現步驟: * 1.接收上傳的文件輸入流 * 2.將文件內容拷貝到 WEB-INF/upload文件夾下 * 3.解析WEB-INF/upload下對應的文件內容,保存至數據庫表 */ @WebServlet("/importExcelData") public class ImportExcelDataServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/json;charset=UTF-8"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); String str = "{\"code\":\"0\",\"message\":\"success\"}"; try { ProductService productService = new ProductService(); boolean result = productService.importProductDataFromExcel(req); if (!result) { str = "{\"code\":\"-1\",\"message\":\"failed\"}"; } } catch (Exception e) { e.printStackTrace(); str = "{\"code\":\"-2\",\"message\":\"error\"}"; } //返回響應結果到前端頁面 out.println(str); out.flush(); out.close(); } }
service層代碼

package graduation.sample.service; import graduation.sample.dao.ProductDao; import graduation.sample.dao.ProductDaoImpl; import graduation.sample.util.FileUploadFormParam; import graduation.sample.entity.PageBean; import graduation.sample.entity.Product; import graduation.sample.util.FileUploadRequestUtil; import graduation.sample.util.excel.ExcelLogs; import graduation.sample.util.excel.ExcelUtil; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.http.HttpServletRequest; import java.io.*; import java.sql.SQLException; import java.util.Collection; import java.util.List; import java.util.UUID; public class ProductService { public PageBean findProductByPage(int currentPage, int currentCount) throws SQLException { PageBean pageBean = new PageBean(); pageBean.setCurrentPage(currentPage); pageBean.setCurrentCount(currentCount); ProductDaoImpl imp = new ProductDaoImpl(); List<Product> products = imp.findByProductPage(currentCount, currentPage); pageBean.setPs(products); int totalCount = imp.findProductCount(); pageBean.setTotalCount(totalCount); int totalPage = (int) Math.ceil(totalCount * 1.0 / currentCount); pageBean.setTotalPage(totalPage); return pageBean; } public boolean importProductDataFromExcel(HttpServletRequest request) throws IOException, SQLException { //判斷表單屬性enctype,值是否為"multipart/form-data" if (!ServletFileUpload.isMultipartContent(request)) { return false; } //調用工具類解析請求參數 FileUploadFormParam formParam = FileUploadRequestUtil.parseParam(request); //獲取請求參數中的file類型的item值 FileItem fileItem = formParam.getFileMap().get("UPLOAD_FILE"); if (fileItem == null) { return false; } //解析file類型的item內容值,生成文件保存在服務器upload文件夾中 String filePath = this.uploadFile(request, fileItem); //將保存到服務器的文件內容解析,導入到數據庫表tv_product中 File file = new File(filePath); InputStream inputStream = new FileInputStream(file); ExcelLogs logs = new ExcelLogs(); //將上傳到服務器的文件內容加載解析 Collection<Product> importExcel = ExcelUtil.importExcel(Product.class, inputStream, "yyyy/MM/dd HH:mm:ss", logs, 0); //文件解析內容保存到數據庫表 ProductDao productDao = new ProductDaoImpl(); for (Product p : importExcel) { try { productDao.addProduct(p); } catch (SQLException e) { //TODO: e.printStackTrace(); throw e; } } return true; } /** * 上傳文件到服務器指定路徑 * * @param fileItem * @return 文件保存路徑 * @throws IOException */ private String uploadFile(HttpServletRequest request, FileItem fileItem) throws IOException { String filePath = null; //上傳的完整文件路徑名 String uploadFilePath = fileItem.getName(); if (uploadFilePath == null || uploadFilePath.equals("")) { return filePath; } //獲取文件名 String uploadFileName = uploadFilePath.substring(uploadFilePath.lastIndexOf("\\") + 1); //保存到服務器上的文件名 String fileName = new StringBuffer(UUID.randomUUID().toString().replace("-", "")) .append("_").append(uploadFileName).toString(); //保存到服務器上的文件路徑 filePath = request.getServletContext().getRealPath("/WEB-INF/upload/" + fileName); //讀取和寫入文件內容 InputStream in = null; FileOutputStream out = null; try { File file = new File(filePath); file.getParentFile().mkdirs(); file.createNewFile(); //輸入流 in = fileItem.getInputStream(); //輸出流 out = new FileOutputStream(file); // 流的對拷 byte[] buffer = new byte[1024];//每次讀取1個字節 int len; //開始讀取上傳文件的字節,並將其輸出到服務端的上傳文件輸出流中 while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); throw e; } finally { // 關閉文件輸入輸出流 if (in != null) { in.close(); } if (out != null) { out.close(); } } return filePath; } }
導出功能代碼:
$("#table").table2excel({ // exclude CSS class exclude: ".noExl", sheetName: "product", filename: "product.xls" });
4.table2excel插件介紹
jquery-table2excel是一款可以將HTML表格的內容導出到微軟Excel電子表格中的jQuery插件。該插件可以根據你的需要導出表格中的內容,不需要的行可以不導出。 它文件體積小,使用非常方便。
先寫好前端按鈕,還需要一個table
<input type="button" value="導出" class="Button" onclick="Export();" /> <table id='exceltable'><td>內容內容內容</td></table>
初始化js
function Export(){
$("#exceltable").table2excel({ //exceltable為存放數據的table // 不被導出的表格行的CSS class類 exclude: ".noExl", // 導出的Excel文檔的名稱 name: "表格-" + new Date().getTime(), // Excel文件的名稱 filename: "表格-" + new Date().getTime() + ".xls", bootstrap: false }); }
table2excel插件的可用配置參數有:
exclude:不被導出的表格行的CSS class類。
name:導出的Excel文檔的名稱。
filename:Excel文件的名稱。
exclude_img:是否導出圖片。
exclude_links:是否導出超鏈接
exclude_inputs:是否導出輸入框中的內容。