Poi实例
程序员文章站
2022-05-29 22:53:10
...
1. 利用poi技术实现使用模版批量导出数据
创建数据库 create table t_user ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(20) DEFAULT NULL, phone varchar(20) DEFAULT NULL, email varchar(20) DEFAULT NULL, qq varchar(20) DEFAULT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB AUTO_INCREMENT=55 DEFAULT CHARSET=utf8; 插入数据 insert into t_user(id,name,phone,email,qq) values (1,'张三12233','12345672233','1234567@qq2233.com','12345672233'), (7,'张三7','1234567','1234567@qq.com','1234567'), (9,'张三9','1234567','1234567@qq.com','1234567'), (12,'张三12','1234567','1234567@qq.com','1234567'), (13,'张三13','1234567','1234567@qq.com','1234567'), (14,'张三14','1234567','1234567@qq.com','1234567'), (15,'张三15','1234567','1234567@qq.com','1234567'); 导入jar包 commons-beanutils-1.8.0.jar commons-collections-3.2.jar commons-fileupload-1.2.2.jar commons-io-2.0.1.jar commons-lang-2.4.jar commons-lang3-3.1.jar commons-logging-1.1.1.jar ezmorph-1.0.3.jar freemarker-2.3.19.jar javassist-3.11.0.GA.jar json-lib-2.2.3-jdk15.jar mysql-connector-java-3.1.12-bin.jar ognl-3.0.6.jar poi-3.9-20121203.jar struts2-core-2.3.14.1.jar xwork-core-2.3.14.1.jar UserAction.java package com.andrew.action; import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.ResultSet; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Workbook; import org.apache.struts2.ServletActionContext; import com.andrew.dao.UserDao; import com.andrew.model.PageBean; import com.andrew.model.User; import com.andrew.util.DbUtil; import com.andrew.util.ExcelUtil; import com.andrew.util.JsonUtil; import com.andrew.util.ResponseUtil; import com.andrew.util.StringUtil; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private static final long serialVersionUID = 1L; private String page; private String rows; private String id; private User user; private String delId; private File userUploadFile; public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getRows() { return rows; } public void setRows(String rows) { this.rows = rows; } public String getDelId() { return delId; } public void setDelId(String delId) { this.delId = delId; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getId() { return id; } public void setId(String id) { this.id = id; } public File getUserUploadFile() { return userUploadFile; } public void setUserUploadFile(File userUploadFile) { this.userUploadFile = userUploadFile; } DbUtil dbUtil = new DbUtil(); UserDao userDao = new UserDao(); public String list() throws Exception { Connection con = null; PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows)); try { con = dbUtil.getCon(); JSONObject result = new JSONObject(); JSONArray jsonArray = JsonUtil.formatRsToJsonArray(userDao.userList(con, pageBean)); int total = userDao.userCount(con); result.put("rows", jsonArray); result.put("total", total); ResponseUtil.write(ServletActionContext.getResponse(), result); } catch (Exception e) { e.printStackTrace(); } finally { try { dbUtil.closeCon(con); } catch (Exception e) { e.printStackTrace(); } } return null; } public String save() throws Exception { if (StringUtil.isNotEmpty(id)) { user.setId(Integer.parseInt(id)); } Connection con = null; try { con = dbUtil.getCon(); int saveNums = 0; JSONObject result = new JSONObject(); if (StringUtil.isNotEmpty(id)) { saveNums = userDao.userModify(con, user); } else { saveNums = userDao.userAdd(con, user); } if (saveNums > 0) { result.put("success", "true"); } else { result.put("success", "true"); result.put("errorMsg", "保存失败"); } ResponseUtil.write(ServletActionContext.getResponse(), result); } catch (Exception e) { e.printStackTrace(); } finally { try { dbUtil.closeCon(con); } catch (Exception e) { e.printStackTrace(); } } return null; } public String delete() throws Exception { Connection con = null; try { con = dbUtil.getCon(); JSONObject result = new JSONObject(); int delNums = userDao.userDelete(con, delId); if (delNums == 1) { result.put("success", "true"); } else { result.put("errorMsg", "删除失败"); } ResponseUtil.write(ServletActionContext.getResponse(), result); } catch (Exception e) { e.printStackTrace(); } finally { try { dbUtil.closeCon(con); } catch (Exception e) { e.printStackTrace(); } } return null; } public String export() throws Exception { Connection con = null; try { con = dbUtil.getCon(); Workbook wb = new HSSFWorkbook(); String headers[] = { "编号", "姓名", "电话", "Email", "QQ" }; ResultSet rs = userDao.userList(con, null); ExcelUtil.fillExcelData(rs, wb, headers); ResponseUtil.export(ServletActionContext.getResponse(), wb, "导出excel.xls"); } catch (Exception e) { e.printStackTrace(); } finally { try { dbUtil.closeCon(con); } catch (Exception e) { e.printStackTrace(); } } return null; } public String export2() throws Exception { Connection con = null; try { con = dbUtil.getCon(); ResultSet rs = userDao.userList(con, null); Workbook wb = ExcelUtil.fillExcelDataWithTemplate(userDao.userList(con, null), "userExporTemplate.xls"); ResponseUtil.export(ServletActionContext.getResponse(), wb, "利用模版导出excel.xls"); } catch (Exception e) { e.printStackTrace(); } finally { try { dbUtil.closeCon(con); } catch (Exception e) { e.printStackTrace(); } } return null; } public String upload() throws Exception { POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(userUploadFile)); HSSFWorkbook wb = new HSSFWorkbook(fs); HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页 if (hssfSheet != null) { for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) { HSSFRow hssfRow = hssfSheet.getRow(rowNum); if (hssfRow == null) { continue; } User user = new User(); user.setName(ExcelUtil.formatCell(hssfRow.getCell(0))); user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1))); user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2))); user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3))); Connection con = null; try { con = dbUtil.getCon(); userDao.userAdd(con, user); } catch (Exception e) { e.printStackTrace(); } finally { dbUtil.closeCon(con); } } } JSONObject result = new JSONObject(); result.put("success", "true"); ResponseUtil.write(ServletActionContext.getResponse(), result); return null; } } UserDao.java package com.andrew.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.andrew.model.PageBean; import com.andrew.model.User; public class UserDao { public ResultSet userList(Connection con, PageBean pageBean) throws Exception { StringBuffer sb = new StringBuffer("select * from t_user"); if (pageBean != null) { sb.append(" limit ?,?"); } PreparedStatement pstmt = con.prepareStatement(sb.toString()); if (pageBean != null) { pstmt.setInt(1, pageBean.getStart()); pstmt.setInt(2, pageBean.getRows()); } return pstmt.executeQuery(); } public int userCount(Connection con) throws Exception { String sql = "select count(*) as total from t_user"; PreparedStatement pstmt = con.prepareStatement(sql); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt("total"); } else { return 0; } } public int userDelete(Connection con, String delId) throws Exception { String sql = "delete from t_user where id=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, delId); return pstmt.executeUpdate(); } public int userAdd(Connection con, User user) throws Exception { String sql = "insert into t_user values(null,?,?,?,?)"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, user.getName()); pstmt.setString(2, user.getPhone()); pstmt.setString(3, user.getEmail()); pstmt.setString(4, user.getQq()); return pstmt.executeUpdate(); } public int userModify(Connection con, User user) throws Exception { String sql = "update t_user set name=?,phone=?,email=?,qq=? where id=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, user.getName()); pstmt.setString(2, user.getPhone()); pstmt.setString(3, user.getEmail()); pstmt.setString(4, user.getQq()); pstmt.setInt(5, user.getId()); return pstmt.executeUpdate(); } } PageBean.java package com.andrew.model; public class PageBean { private int page; // 第几页 private int rows; // 每页的记录数 private int start; // 起始页 public PageBean(int page, int rows) { super(); this.page = page; this.rows = rows; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getStart() { return (page - 1) * rows; } } User.java package com.andrew.model; public class User { private int id; private String name; private String phone; private String email; private String qq; public User() { } public User(String name, String phone, String email, String qq) { this.name = name; this.phone = phone; this.email = email; this.qq = qq; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } } DbUtil.java package com.andrew.util; import java.sql.Connection; import java.sql.DriverManager; public class DbUtil { private String dbUrl = "jdbc:mysql://localhost:3306/db_poi"; private String dbUserName = "root"; private String dbPassword = "root"; private String jdbcName = "com.mysql.jdbc.Driver"; public Connection getCon() throws Exception { Class.forName(jdbcName); Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword); return con; } public void closeCon(Connection con) throws Exception { if (con != null) { con.close(); } } } ExcelUtil.java package com.andrew.util; import java.io.InputStream; import java.sql.ResultSet; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ExcelUtil { public static void fillExcelData(ResultSet rs, Workbook wb, String[] headers) throws Exception { int rowIndex = 0; Sheet sheet = wb.createSheet(); Row row = sheet.createRow(rowIndex++); for (int i = 0; i < headers.length; i++) { row.createCell(i).setCellValue(headers[i]); } while (rs.next()) { row = sheet.createRow(rowIndex++); for (int i = 0; i < headers.length; i++) { row.createCell(i).setCellValue(rs.getObject(i + 1).toString()); } } } public static Workbook fillExcelDataWithTemplate(ResultSet rs, String templateFileName) throws Exception { InputStream inp = ExcelUtil.class.getResourceAsStream("/com/andrew/template/" + templateFileName); POIFSFileSystem fs = new POIFSFileSystem(inp); Workbook wb = new HSSFWorkbook(fs); Sheet sheet = wb.getSheetAt(0); // 获取列数 int cellNums = sheet.getRow(0).getLastCellNum(); int rowIndex = 1; while (rs.next()) { Row row = sheet.createRow(rowIndex++); for (int i = 0; i < cellNums; i++) { row.createCell(i).setCellValue(rs.getObject(i + 1).toString()); } } return wb; } public static String formatCell(HSSFCell hssfCell) { if (hssfCell == null) { return ""; } else { if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { return String.valueOf(hssfCell.getBooleanCellValue()); } else if (hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { return String.valueOf(hssfCell.getNumericCellValue()); } else { return String.valueOf(hssfCell.getStringCellValue()); } } } } JsonUtil.java package com.andrew.util; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonUtil { /** * 把ResultSet集合转换成JsonArray数组 * * @param rs * @return * @throws Exception */ public static JSONArray formatRsToJsonArray(ResultSet rs) throws Exception { ResultSetMetaData md = rs.getMetaData(); int num = md.getColumnCount(); JSONArray array = new JSONArray(); while (rs.next()) { JSONObject mapOfColValues = new JSONObject(); for (int i = 1; i <= num; i++) { mapOfColValues.put(md.getColumnName(i), rs.getObject(i)); } array.add(mapOfColValues); } return array; } } ResponseUtil.java package com.andrew.util; import java.io.OutputStream; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Workbook; public class ResponseUtil { public static void write(HttpServletResponse response, Object o) throws Exception { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print(o.toString()); out.flush(); out.close(); } public static void export(HttpServletResponse response, Workbook wb, String fileName) throws Exception { response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso8859-1")); response.setContentType("application/ynd.ms-excel;charset=UTF-8"); OutputStream out = response.getOutputStream(); wb.write(out); out.flush(); out.close(); } } StringUtil.java package com.andrew.util; public class StringUtil { public static boolean isEmpty(String str) { if ("".equals(str) || str == null) { return true; } else { return false; } } public static boolean isNotEmpty(String str) { if (!"".equals(str) && str != null) { return true; } else { return false; } } } struts.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="userInfo" namespace="/" extends="struts-default"> <action name="user" class="com.andrew.action.UserAction"> </action> </package> </struts> web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>PoiTest3</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>StrutsPrepareAndExecuteFilter</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>StrutsPrepareAndExecuteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app> crud1.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Basic DataGrid - jQuery EasyUI Demo</title> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="jquery-easyui-1.3.3/themes/icon.css"> <script type="text/javascript" src="jquery-easyui-1.3.3/jquery.min.js"></script> <script type="text/javascript" src="jquery-easyui-1.3.3/jquery.easyui.min.js"></script> <script type="text/javascript" src="jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script> <script> var url; function deleteUser(){ var row=$('#dg').datagrid('getSelected'); if(row){ $.messager.confirm("系统提示","您确定要删除这条记录吗?",function(r){ if(r){ $.post('user!delete',{delId:row.id},function(result){ if(result.success){ $.messager.alert("系统提示","已成功删除这条记录!"); $("#dg").datagrid("reload"); }else{ $.messager.alert("系统提示",result.errorMsg); } },'json'); } }); } } function newUser(){ $("#dlg").dialog('open').dialog('setTitle','添加用户'); $('#fm').form('clear'); url='user!save'; } function editUser(){ var row=$('#dg').datagrid('getSelected'); if(row){ $("#dlg").dialog('open').dialog('setTitle','编辑用户'); $("#name").val(row.name); $("#phone").val(row.phone); $("#email").val(row.email); $("#qq").val(row.qq); url='user!save?id='+row.id; } } function saveUser(){ $('#fm').form('submit',{ url:url, onSubmit:function(){ return $(this).form('validate'); }, success:function(result){ var result=eval('('+result+')'); if(result.errorMsg){ $.messager.alert("系统提示",result.errorMsg); return; }else{ $.messager.alert("系统提示","保存成功"); $('#dlg').dialog('close'); $("#dg").datagrid("reload"); } } }); } function exportUser(){ window.open('user!export'); } function exportUser2(){ window.open('user!export2'); } function openUploadFileDialog(){ $("#dlg2").dialog('open').dialog('setTitle','批量导入数据'); } function downloadTemplate(){ window.open('template/userExporTemplate.xls'); } function uploadFile(){ $("#uploadForm").form("submit",{ success:function(result){ var result=eval('('+result+')'); if(result.errorMsg){ $.messager.alert("系统提示",result.errorMsg); }else{ $.messager.alert("系统提示","上传成功"); $("#dlg2").dialog("close"); $("#dg").datagrid("reload"); } } }); } </script> </head> <body> <table id="dg" title="用户管理" class="easyui-datagrid" style="width:700px;height:365px" url="user!list" toolbar="#toolbar" pagination="true" rownumbers="true" fitColumns="true" singleSelect="true"> <thead> <tr> <th field="id" width="50" hidden="true">编号</th> <th field="name" width="50">姓名</th> <th field="phone" width="50">电话</th> <th field="email" width="50">Email</th> <th field="qq" width="50">QQ</th> </tr> </thead> </table> <div id="toolbar"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">添加用户</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">编辑用户</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="deleteUser()">删除用户</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-export" plain="true" onclick="exportUser()">导出用户</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-export" plain="true" onclick="exportUser2()">用模版导出用户</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-import" plain="true" onclick="openUploadFileDialog()">用模版批量导入数据</a> </div> <div id="dlg" class="easyui-dialog" style="width:400px;height:250px;padding:10px 20px" closed="true" buttons="#dlg-buttons"> <form id="fm" method="post"> <table cellspacing="10px;"> <tr> <td>姓名:</td> <td><input id="name" name="user.name" class="easyui-validatebox" required="true" style="width: 200px;"></td> </tr> <tr> <td>联系电话:</td> <td><input id="phone" name="user.phone" class="easyui-validatebox" required="true" style="width: 200px;"></td> </tr> <tr> <td>Email:</td> <td><input id="email" name="user.email" class="easyui-validatebox" validType="email" required="true" style="width: 200px;"></td> </tr> <tr> <td>QQ:</td> <td><input id="qq" name="user.qq" class="easyui-validatebox" required="true" style="width: 200px;"></td> </tr> </table> </form> </div> <div id="dlg-buttons"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">保存</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">关闭</a> </div> <div id="dlg2" class="easyui-dialog" style="width:400px;height:180px;padding:10px 20px" closed="true" buttons="#dlg-buttons2"> <form id="uploadForm" action="user!upload" method="post" enctype="multipart/form-data"> <table> <tr> <td>下载模版:</td> <td><a href="javascript:void(0)" class="easyui-linkbutton" onclick="downloadTemplate()">导入模版</a></td> </tr> <tr> <td>上传文件:</td> <td><input type="file" name="userUploadFile"></td> </tr> </table> </form> </div> <div id="dlg-buttons2"> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" onclick="uploadFile()">上传</a> <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg2').dialog('close')">关闭</a> </div> </body> </html> 运行结果: http://localhost:8080/PoiDemo2/crud1.html
上一篇: ResultSet结果集
下一篇: Github 编辑器 Atom 已开源