1. 程式人生 > >java之poi操作excel-批量匯入匯出

java之poi操作excel-批量匯入匯出

    上一篇博文介紹了poi操作excel的基本讀寫操作後,接下來,介紹一下在專案中的實際用途:批量匯入、批量匯出功能。因為重點知識介紹批量匯入匯出excel功能,故而專案整體的搭建後臺用jdbc與struts2,前端頁面用jquery-easyui實現(其實也可以整合到ssm或者ssh中,而這一點現在我已經實現了,即基於SSM的部落格以及視訊教程我已經發布在我最新的部落格中,歡迎觀看,其中,視訊教程地址:https://edu.csdn.net/course/detail/8894  歡迎支援!!)。

    首先,看一下,專案的整體結構圖:

       

     首先,當然是放入jar包啦,可以來這我這裡下載:

poi批量匯入匯出的jar包

     加入jquery-easyui-1.3.3,可以到easyui官網下載,配置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"
	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>PoiDemo</display-name>
	<welcome-file-list>
		<welcome-file>index.htm</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>


    src目錄下建立各個包,具體我就不說了,看上面的圖即可。新建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.steadyjack.action.UserAction">
		</action>

	</package>
     
</struts>

    接下來,介紹com.steadyjack.util下的各個工具類,有一些比較簡單,我就不詳細說了,註釋寫得很清楚了!

    DateUtil.java:

package com.steadyjack.util;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 簡單日期處理工具
 * @author 鍾林森
 *
 */
public class DateUtil {

	public static String formatDate(Date date,String format){
		String result="";
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		if(date!=null){
			result=sdf.format(date);
		}
		return result;
	}
	
	
	public static Date formatString(String str,String format) throws Exception{
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		return sdf.parse(str);
	}
	
	public static void main(String[] args) throws Exception{
		Date date=formatString("1993/10/12", "yyyy/MM/dd");
		String str=formatDate(date, "yyyy-MM-dd");
		System.out.println(str);
	}
}


    DbUtil.java:

package com.steadyjack.util;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * 資料庫連結工具
 * @author 鍾林森
 *
 */
public class DbUtil {

	private String dbUrl="jdbc:mysql://localhost:3306/db_poi";
	private String dbUserName="root";
	private String dbPassword="123456";
	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();
		}
	}
}


     excel匯入匯出工具類,這個很重要,ExcelUtil.java:

package com.steadyjack.util;

import java.io.InputStream;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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;

/**
 * Excel檔案處理工具類: 包括填充資料到普通excel、模板excel檔案,單元格格式處理
 * @author 鍾林森
 *
 */
public class ExcelUtil {

	/**
	 * 填充資料到普通的excel檔案中
	 * @param rs
	 * @param wb
	 * @param headers
	 * @throws Exception
	 */
	public static void fillExcelData(ResultSet rs,Workbook wb,String[] headers)throws Exception{
		Sheet sheet=wb.createSheet();
		Row row=sheet.createRow(0);
		
		//先填充行頭 : "編號","姓名","電話","Email","QQ","出生日期"
		for(int i=0;i<headers.length;i++){
			row.createCell(i).setCellValue(headers[i]);
		}
		
		//再填充資料
		int rowIndex=1;
		while(rs.next()){
			row=sheet.createRow(rowIndex++);
			for(int i=0;i<headers.length;i++){
				Object objVal=rs.getObject(i+1);
				if (objVal instanceof Date) {
					row.createCell(i).setCellValue(DateUtil.formatDate((Date)objVal,"yyyy-MM-dd"));
				}else{
					row.createCell(i).setCellValue(objVal.toString());
				}
			}
		}
	}
	
	/**
	 * 填充資料到模板excel檔案
	 * @param rs
	 * @param templateFileName
	 * @return
	 * @throws Exception
	 */
	public static Workbook fillExcelDataWithTemplate(ResultSet rs,String templateFileName)throws Exception{
		//首先:從本地磁碟讀取模板excel檔案,然後讀取第一個sheet
		InputStream inp=ExcelUtil.class.getResourceAsStream("/com/steadyjack/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++){
				Object objVal=rs.getObject(i+1);
				if (objVal instanceof Date) {
					row.createCell(i).setCellValue(DateUtil.formatDate((Date)objVal,"yyyy-MM-dd"));
				}else{
					row.createCell(i).setCellValue(objVal.toString());
				}
			}
		}
		return wb;
	}
	
	/**
	 * 處理單元格格式的簡單方式
	 * @param hssfCell
	 * @return
	 */
	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());
			}
		}
	}
	
	/**
	 * 處理單元格格式的第二種方式: 包括如何對單元格內容是日期的處理
	 * @param cell
	 * @return
	 */
	public static String formatCell2(HSSFCell cell) {
		if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
			
			//針對單元格式為日期格式
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
			}
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return cell.getStringCellValue();
		}
	}

	/**
	 * 處理單元格格式的第三種方法:比較全面
	 * @param cell
	 * @return
	 */
	public static String formatCell3(HSSFCell cell) {
		if (cell == null) {
			return "";
		}
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_NUMERIC:

			//日期格式的處理
			if (HSSFDateUtil.isCellDateFormatted(cell)) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				return sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue())).toString();
			}

			return String.valueOf(cell.getNumericCellValue());

			//字串
		case HSSFCell.CELL_TYPE_STRING:
			return cell.getStringCellValue();

			// 公式
		case HSSFCell.CELL_TYPE_FORMULA:
			return cell.getCellFormula();

			// 空白
		case HSSFCell.CELL_TYPE_BLANK:
			return "";

			// 布林取值
		case HSSFCell.CELL_TYPE_BOOLEAN:
			return cell.getBooleanCellValue() + "";
			
			//錯誤型別
		case HSSFCell.CELL_TYPE_ERROR:
			return cell.getErrorCellValue() + "";
		}

		return "";
	}
}


    將jdbc查詢得到的ResultSet轉為JsonArray工具類JsonUtil.java:

package com.steadyjack.util;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * jdbc 的結果集ResultSet轉化為JsonArray工具 
 * @author 鍾林森
 *
 */
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++){
				
				Object strVal=rs.getObject(i);
				if (strVal instanceof Date) {
					mapOfColValues.put(md.getColumnName(i),DateUtil.formatDate((Date)strVal,"yyyy-MM-dd"));
				}else{
					mapOfColValues.put(md.getColumnName(i),strVal);
				}
			}
			array.add(mapOfColValues);
		}
		return array;
	}
}


     ResponseUtil.java:

package com.steadyjack.util;

import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

/**
 * 將資料寫回頁面 jquery-ajax互動工具類
 * @author 鍾林森
 *
 */
public class ResponseUtil {

	/**
	 * 將資料寫回頁面 用於jquery-ajax的非同步互動
	 * @param response
	 * @param o
	 * @throws Exception
	 */
	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();
	}
	
	/**
	 * 將excel檔案寫回客戶端瀏覽器 用於下載
	 * @param response
	 * @param wb
	 * @param fileName
	 * @throws Exception
	 */
	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.steadyjack.util;

/**
 * 簡單字串處理工具
 * @author 鍾林森
 *
 */
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;
		}
	}
}


     接下來,是com.steadyjack.model中的User與PageBean:

package com.steadyjack.model;

import java.util.Date;

public class User {

	private int id;
	private String name;
	private String phone;
	private String email;
	private String qq;
	
	private Date birth;
	
	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 User(String name, String phone, String email, String qq, Date birth) {
		super();
		this.name = name;
		this.phone = phone;
		this.email = email;
		this.qq = qq;
		this.birth = birth;
	}

	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;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}
	
}
package com.steadyjack.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;
	}
}


     接下來是UserDao(其實,也開發了增刪改查的功能,但在這裡就不貼出來了,有意者可以加上面的qq聯絡)

package com.steadyjack.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.steadyjack.model.PageBean;
import com.steadyjack.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 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());
		
		//java.util.date轉為 java.sql.date
		pstmt.setDate(5, new java.sql.Date(user.getBirth() .getTime()));
		
		return pstmt.executeUpdate();
	}
}


     然後注意com.steadyjack.template下有個 “使用者模板檔案.xls”,這個可以自己製作:

    最後是重頭戲了UserAction.java:

package com.steadyjack.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.opensymphony.xwork2.ActionSupport;
import com.steadyjack.dao.UserDao;
import com.steadyjack.model.PageBean;
import com.steadyjack.model.User;
import com.steadyjack.util.DateUtil;
import com.steadyjack.util.DbUtil;
import com.steadyjack.util.ExcelUtil;
import com.steadyjack.util.JsonUtil;
import com.steadyjack.util.ResponseUtil;
import com.steadyjack.util.StringUtil;

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;
	}
	
	//匯出使用者  : 普通excel匯出
	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;
	}
	
	//使用者匯出 : 採用預先設定好的excel模板檔案進行匯出
	public String export2()throws Exception{
		Connection con=null;
		try {
			con=dbUtil.getCon();
			ResultSet rs=userDao.userList(con, null);
			Workbook wb=ExcelUtil.fillExcelDataWithTemplate(rs, "使用者模板檔案.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;
	}
	

	//excel檔案匯入,批量匯入資料
	public String upload()throws Exception{
		//此時的Workbook應該是從 客戶端瀏覽器上傳過來的 uploadFile了,其實跟讀取本地磁碟的一個樣
		POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(userUploadFile));
		HSSFWorkbook wb=new HSSFWorkbook(fs);
		HSSFSheet hssfSheet=wb.getSheetAt(0);
		
		if(hssfSheet!=null){
			//遍歷excel,從第二行開始 即 rowNum=1,逐個獲取單元格的內容,然後進行格式處理,最後插入資料庫
			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)));
				
				//對於單元格日期需要進行特殊處理
				user.setBirth(DateUtil.formatString(ExcelUtil.formatCell2(hssfRow.getCell(4)), "yyyy-MM-dd"));
				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;
	}
	
}


     最後有一個WebContent目錄下template資料夾有個userTemplateFile.xls,跟“使用者模板檔案.xls”是一模一樣的,只是換個名字而已。

     最後當然是頁面了crud1.html:

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>poi操作excel</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/userTemplateFile.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>
                <th field="birth" width="50">出生日期</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>
        		<tr>
        			<td>出生日期:</td>
        			<td><input id="birth" name="user.birth" 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>


    其中,新增、刪除、修改的功能已經實現了,但程式碼我就不貼出來了,因為我重點是介紹批量匯入匯出excel。

    當然啦,需要新建一個數據庫db_poi,新建一個數據庫表t_user:

DROP TABLE IF EXISTS `t_user`;
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,
  `birth` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8;


INSERT INTO `t_user` VALUES ('51', '鍾林森', '12121212', '[email protected]', '121212121212122', '2016-10-11 22:36:57');
INSERT INTO `t_user` VALUES ('54', 'steadyjack', '11111', '[email protected]', '1111122222121212', '2016-10-28 22:37:06');
INSERT INTO `t_user` VALUES ('55', '鍾林森', '22222', '[email protected]', '2222211111121212', '2016-10-20 22:37:09');
INSERT INTO `t_user` VALUES ('56', '鍾穩傑', '33333', '[email protected]', '3333322222121212', '2016-10-13 22:37:12');


    在tomcat跑起來,下面是執行效果:

    點選“匯出使用者”,即可下載得到“使用者excel表.xls”,開啟來瞧瞧,是否跟上圖的資料一致:

    發現一致是一致,但是就是醜陋了點。接下來,我們“用模板匯出使用者”,可以得到比較好看的資料:

     最後,點選“用模板批量匯入資料”:

    可以先下載模板檔案,填寫好資料之後,再回來這裡“選擇檔案”,上傳填寫好資料的那個excel檔案,下面是我弄好的幾條資料:

    最後,上傳這個檔案,匯入進去,再回來首頁看看:

    關於匯入,目前還沒有去深入搞:“判斷一些是否合法,如何將不合法的資料再匯入完成之後提示或者展示給使用者觀看。。。”這些,自己也在搞中,有興趣的,可以加qq交流!