我在用POI上传Excel办公表格软件excel教程至Mysql数据库,遇到一个小问题

使用poi导入导出数据库表数据网上已经有很多例子了,在这里,把自己做的记录下来,方便以后使用。
首先在poi官网http://poi.apache.org/download.html下载最新版本的poi组件,然后把jar包放到web工程的lib下
先说poi导入excel数据到数据库吧,这里只支持excel2003,excel2007导入。我是这样处理的,这其实包括2个部分,一个是excel文件上传,一个是对上传的excel文件解析,并吧数据保存到数据库中。
通用的poi解析excel2003或者2007代码
import java.io.F
import java.io.FileInputS
import java.io.FileNotFoundE
import java.io.IOE
import java.text.DecimalF
import java.text.SimpleDateF
import java.util.LinkedL
import java.util.L
import org.apache.poi.hssf.usermodel.HSSFC
import org.apache.poi.hssf.usermodel.HSSFDateU
import org.apache.poi.hssf.usermodel.HSSFR
import org.apache.poi.hssf.usermodel.HSSFS
import org.apache.poi.hssf.usermodel.HSSFW
import org.apache.poi.xssf.usermodel.XSSFC
import org.apache.poi.xssf.usermodel.XSSFR
import org.apache.poi.xssf.usermodel.XSSFS
import org.apache.poi.xssf.usermodel.XSSFW
public class ExcelReader {
* 对外提供读取excel 的方法
public static List&List&Object&& readExcel(File file) throws IOException{
String fileName = file.getName();
String extension = fileName.lastIndexOf(".")==-1?"":fileName.substring(fileName.lastIndexOf(".")+1);
if("xls".equals(extension)){
return read2003Excel(file);
}else if("xlsx".equals(extension)){
return read2007Excel(file);
throw new IOException("不支持的文件类型");
* 读取 office 2003 excel
* @throws IOException
* @throws FileNotFoundException */
private static List&List&Object&& read2003Excel(File file) throws IOException{
List&List&Object&& list = new LinkedList&List&Object&&();
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = hwb.getSheetAt(0);
Object value =
HSSFRow row =
HSSFCell cell =
for(int i = sheet.getFirstRowNum();i&= sheet.getPhysicalNumberOfRows();i++){
row = sheet.getRow(i);
if (row == null) {
List&Object& linked = new LinkedList&Object&();
for (int j = row.getFirstCellNum(); j &= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0");// 格式化数字
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
System.out.println(i+"行"+j+" 列 is String type");
value = cell.getStringCellValue();
case XSSFCell.CELL_TYPE_NUMERIC:
System.out.println(i+"行"+j+" 列 is N DateFormt:"+cell.getCellStyle().getDataFormatString());
if("@".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
} else if("General".equals(cell.getCellStyle().getDataFormatString())){
value = nf.format(cell.getNumericCellValue());
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
case XSSFCell.CELL_TYPE_BOOLEAN:
System.out.println(i+"行"+j+" 列 is Boolean type");
value = cell.getBooleanCellValue();
case XSSFCell.CELL_TYPE_BLANK:
System.out.println(i+"行"+j+" 列 is Blank type");
value = "";
System.out.println(i+"行"+j+" 列 is default type");
value = cell.toString();
if (value == null || "".equals(value)) {
linked.add(value);
list.add(linked);
* 读取Office 2007 excel
private static List&List&Object&& read2007Excel(File file) throws IOException {
List&List&Object&& list = new LinkedList&List&Object&&();
// 构造 XSSFWorkbook 对象,strPath 传入文件路径
XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
// 读取第一章表格内容
XSSFSheet sheet = xwb.getSheetAt(0);
Object value =
XSSFRow row =
XSSFCell cell =
for (int i = sheet.getFirstRowNum(); i &= sheet
.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
List&Object& linked = new LinkedList&Object&();
for (int j = row.getFirstCellNum(); j &= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
DecimalFormat df = new DecimalFormat("0");// 格式化 number String 字符
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0");// 格式化数字
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
System.out.println(i+"行"+j+" 列 is String type");
value = cell.getStringCellValue();
case XSSFCell.CELL_TYPE_NUMERIC:
System.out.println(i+"行"+j+" 列 is N DateFormt:"+cell.getCellStyle().getDataFormatString());
if("@".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
} else if("General".equals(cell.getCellStyle().getDataFormatString())){
value = nf.format(cell.getNumericCellValue());
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
case XSSFCell.CELL_TYPE_BOOLEAN:
System.out.println(i+"行"+j+" 列 is Boolean type");
value = cell.getBooleanCellValue();
case XSSFCell.CELL_TYPE_BLANK:
System.out.println(i+"行"+j+" 列 is Blank type");
value = "";
System.out.println(i+"行"+j+" 列 is default type");
value = cell.toString();
if (value == null || "".equals(value)) {
linked.add(value);
list.add(linked);
public static void main(String[] args) throws IOException
File file = new File("d:\\test1.xlsx");
List&List&Object&& list= readExcel(file);
// System.out.println(list);
怎么使用呢,
import java.io.F
import java.io.FileInputS
import java.io.FileOutputS
import java.io.IOE
import java.util.L
import org.apache.struts2.ServletActionC
import org.springframework.beans.factory.annotation.A
import com.lee.common.poi.ExcelR
import com.opensymphony.xwork2.ActionS
public class ImportExcelAction extends ActionSupport{
@Autowired
CustomerService customerS
// 上传文件域
// 上传文件类型
private String excelContentT
// 封装上传文件名
private String excelFileN
// 接受依赖注入的属性
private String saveP
public String execute() throws Exception
clearErrorsAndMessages();
FileOutputStream fos =
FileInputStream fis =
//防止文件重名,用系统时间,精确到毫秒为文件命名
java.text.SimpleDateFormat
simpleDateFormat
java.text.SimpleDateFormat( "yyyyMMddHHmmssSSS");//取系统时间,精确到毫秒。
java.util.Date
java.util.Date();
simpleDateFormat.format(date);
excelFileName = strTime+getExcelFileName();
fos = new FileOutputStream(getSavePath() + "/" + excelFileName);
fis = new FileInputStream(getExcel());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
System.out.println("文件上传成功");
} catch (Exception e) {
System.out.println("文件上传失败");
e.printStackTrace();
addActionError("文件上传失败");
return "input";
} finally {
close(fos, fis);
List&List&Object&& list= ExcelReader.readExcel(new File(getSavePath() + "/" +
excelFileName));
//在这里默认excel有表头数据,其实就是list第一行,所以i从1开始
if(!(list.size()&1) ){
for(int i=1 ;i&list.size();i++)
//通过 (String)list.get(i).get(0),(String)list.get(i).get(1)这种方式获取相应的值
//并新建对象,把数据持久化到数据库中
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
addActionError("解析excel失败");
return "input";
return SUCCESS;
private void close(FileOutputStream fos, FileInputStream fis) {
if (fis != null) {
fis.close();
} catch (IOException e) {
System.out.println("FileInputStream关闭失败");
e.printStackTrace();
* 文件存放目录
public String getSavePath() throws Exception{
return ServletActionContext.getServletContext().getRealPath(savePath);
public void setSavePath(String savePath) {
this.savePath = saveP
public File getExcel() {
public void setExcel(File excel) {
this.excel =
public String getExcelContentType() {
return excelContentT
public void setExcelContentType(String excelContentType) {
this.excelContentType = excelContentT
public String getExcelFileName() {
return excelFileN
public void setExcelFileName(String excelFileName) {
this.excelFileName = excelFileN
struts.xml配置&action name="importExcel"
class="importExcelAction"&
&param name="savePath"&/excelfolder&/param&
&result name="success"&/WEB-INF/view/importExcelSuccess.jsp&/result&
&result name="input"&/WEB-INF/view/importCustomerInfo.jsp&/result&
&/action&相应 的jsp页面
function check()
var excelfileName = document.upload_form.excel.
var exceltype = excelfileName.substring(excelfileName.lastIndexOf('.')
1).toLowerCase();
if(excelfileName.length==0)
alert("请选择excel");
else if(!(exceltype=="xls"|| exceltype=="xlsx"))
alert("格式必须为excel 2003或者2007的一种");
&form name="upload_form" action="importExcel.action" method="post" enctype="multipart/form-data" onsubmit="return check()"&
&input type="file"
id="excel" name="excel" size="29" class="file"&
&input type="submit" class="importButton" value=""&
至于poi导出excel报表,也比较容易,参见我以前写的例子 http://download.csdn.net/detail/xiaoliouc/5117319
在SSM下使用POI实现Excel表的导入/导出
导出就是将List转化为Excel(listToExcel)
导入就是将Excel转化为List(excelToList)
Apache POI是Apache软件基金会的开放源码函式库,PO...
poi导入excel
使用poi进行导入导出excel是我们开发中常见的应用场景!
导入必要的jar包
创建读取excel的工具类–ExcelUtils
public class ExcelUtils {
POI实现动态导出功能
今天工作很闲,无意中发现同事做的一个动态导出功能,之前自己也利用POI做过excle的导出功能,但都是通过提前 定义导出文件,写死要导出的字段,在访问数据库获取导出信息,在写入ex...
实际工作:----Poi报表导入导出
Poi常用的组件
常用组件:
HSSFWorkbook
excel的文档对象
POI技术处理Excel表 .xls ..xlsx两种格式的导入操作
一、说明1、文章转载自:http://blog.csdn.net/onepersontz/article/details/原文标题====SpringMvc+POI 处理Excel的导...
POI报表--导入和导出!
POI报表:导入和导出!
* @Project : 宅急送
* @Title : POITest.java
* @Package cn.itcast.bos.service.test...
使用POI来做报表
apache POI
没有更多推荐了,&&&&&&&&&&&&&&&&&&
posts - 14,comments - 2,trackbacks - 0
SpringMVC文件上传 Excle文件 Poi解析并批量导入 MYSQL数据库&
业务需求说明: *
1 批量导入成员 并且 自主创建账号 *
2 校验数据格式
且 重复导入提示 已被占用 *
3 导入手机相同 则更新源有信息 *
4 返回错误信息 */
jsp文件 部分 浏览 以及功能键 代码:
&div class="modal-body" style="position:"&
&form class="" role="form" id="upload_form"&
&select class="form-control m-b" id="upload_dept" name="uploadDept"&
&div class="input-group"&
&input type="text" class="form-control input-sm" name="upload_filename"&
&div class="input-group-btn"&
&button type="button" class="btn btn-sm btn-primary"&
选择上传文件按钮
type类型指定为 file
accept 可以在浏览过程中 进行过滤显示
支持多个用逗号隔开
&!-- 选择文件后显示文件名称
对更改事件绑定了事件监听器 selectUploadFile(this)
此框按钮id为: upload_file
&input type="file" id="upload_file" onchange="selectUploadFile(this)" name="uploadFile" accept=".xls,.xlsx" class="input-fzliulan"&
&div class="modal-footer"&
&button type="button" id="btn_upCancel" class="btn btn-white" data-dismiss="modal"&关闭&/button&
&button type="button" id="btn_upSubmit" class="btn btn-success pdlr16"&&span id="uploadTxt"&导入&/span&&img id="loadingImg" style="display: none" src="&%=contextPath%&/resource/images/loading.gif" /&&/button&
comm.jsp文件定义的变量:
var userId = '&c:out value="${sessionScope.USER.userId}" /&';
var orgId = '&c:out value="${sessionScope.ORG.orgId}" /&';
var authLevel = '&c:out value="${sessionScope.USER.authLevel}" /&';
var userType = '&c:out value="${sessionScope.USER.type}" /&';
var orgAmount= '&c:out value="${sessionScope.AGENT.orgAmount}" /&';
var loginUser = {userId: userId, orgId: orgId, authLevel: authLevel, type: userType ,orgAmount:orgAmount};
1 $(function(){
bindEvent();
4 /** 为页面按钮绑定事件
6 function bindEvent(){
* 显示上传文件名称
* @param fileObj
function selectUploadFile(fileObj){
var fullPath = $(fileObj).val();
var index = fullPath.lastIndexOf('\\') + 1;
var fileName = fullPath.substring(index);
$('input[name="upload_filename"]').val(fileName);
$('#downLoadTemplate').click(function(){
//下载模板按钮的监听器
var url = webContext + '/file\\template\\组织用户信息模板.xlsx';
downloadFile(url)
* 上传文件
$('#btn_upSubmit').click(function(){
var valid = uploadValidator.checkForm(); //检测传单内容输入是否有问题
if(!valid){
uploadValidator.showErrors();
} else{ //检测成功
$('#uploadTxt').text('');
$('#loadingImg').show();
//按钮换成动画效果图片
36 /** 准备参数: */
var orgId = loginUser.orgId;
//但钱用户的组织id
var deptId = $('#upload_dept').val();
选框中选择的部门id
var password = hex_md5('123456');//
默认密码 进行加密
var param = {orgId: orgId, deptId: deptId, password: password};
//ajax传输 携带json详细信息
var url = webContext + '/org/uploadOrgUser';
/** 使用ajaxFileUpload */
$.ajaxFileUpload({
url: url, //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'upload_file', //文件上传域的ID
就是选定文件的 type=file的input框的id
ajaxFileUpload 会帮我们把他分装到ajax请求的 携带对象域中去
dataType: 'json', //返回值类型 一般设置为json
type: 'post',
data: param,
success:function(){
//成功的success 回调方法等业务流程结束后再写
//先留已空白
项目使用SpringMVC :&
其controller为:
1 //-----------------------------------MVC 的控制器----------------------
2 //Controller为:
3 @Controller
4 @RequestMapping("/org")
5 public class OrgController extends BaseController {
@Autowired
private IOrgService orgS
@RequestMapping("/uploadOrgUser")
@ResponseBody
public Map&String, Object& uploadOrgUser(HttpServletRequest request){
Map&String, Object& map = new HashMap&String, Object&();
String flag = "failure";
String msg = "上传成功";
MultipartHttpServletRequest mtRequest = (MultipartHttpServletRequest)//多部分httpRquest对象
是HttpServletRequest类的一个子类接口
支持文件分段上传对象
Integer orgId = RequestUtil.getIntParam(mtRequest, "orgId");
Integer deptId = RequestUtil.getIntParam(mtRequest, "deptId"); //选取部门id
String password = RequestUtil.getStringParam(request, "password"); // 初始密码 已被md5加密
MultipartFile upFile = mtRequest.getFile("uploadFile"); // 直接获取文件对象
if(null == upFile || upFile.getSize()==0){
//文件不存在的情况
msg = "上传文件不存在或为空文件";
map.put("flag", flag);
map.put("msg", msg);
//返回错误信息
String targetPath = request.getServletContext().getRealPath("/file/upload"); //获取服务器 中file/update 的 url地址
map = orgService.uploadOrgUser(targetPath, orgId, deptId, password, upFile);
//调用实现类 返回 界面消息 对象
--业务层接口--说明:
1 public interface IOrgService {
* @param targetPath
* @param orgId
* @param deptId
* @param password
* @param upFile
public Map&String, Object& uploadOrgUser(String targetPath, Integer orgId, Integer deptId, String password, MultipartFile upFile);
--业务层实现类:
1 //业务层实现类:
2 @Service("orgService")
3 public class OrgServiceImpl extends BaseService implements IOrgService {
@Autowired
private IOrgDao orgD
@Autowired
private IUserDao userD
@Autowired
private IDeptDao deptD
@Autowired
private IOrgUserDao orgUserD
@Autowired
private IServiceAuthDao authD
批量导入 业务方法
public Map&String, Object& uploadOrgUser(String targetPath, Integer orgId, Integer deptId, String password, MultipartFile upFile) {
Map&String,Object& rm = new HashMap&String,Object&();
String flag ="failure";
String msg = "上传失败";
File f = new File(targetPath) //实例硬盘中文件夹(路径)对象
if(!f.exists()){//判断此路径/文件夹是否存在
f.mkdirs(); //如果不存在
则创建文件夹/目录
String originalName = upFile.getOriginalFilename();//获取文件对象原始文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String tag = sdf.format(new Date());
String upFileName = targetPath + File.separator+tag+"_"+originalN// 拼接出文件的要存储的位置(全路径)
File file = new File(upFileName);//创建 内存中的File对象
if(file.exists()){ //判断是否存在
file.delete();//如果有重名文件存在
就删除文件
// 这个对象对应的硬盘必须删
如果已经存在 则会抛出
// IOException异常
List&OrgUser& orgUsers = null;
List&User& users = null;
List&RowData& offedData = null;
//List 集合对象准备
upFile.transferTo(file);//转存文件
本质还是一样的打开流传文件
需要注意 file对应的硬盘中的文件不能存在 需要删除
否则会抛出 文件已经存在且不能删除 异常
// 校验上传数据
辅助方法一 **/
Map&String,Object& validData = validUpload(file,orgId,deptId);// 校验数据
分类 返回 map形式
users = (List&User&) validData.get("PASSED_USERS");
//通过的user
是向 m_user 表的
orgUsers = (List&OrgUser&) validData.get("PASSED_ORGUSERS"); //
是向 m_org_user 表的
offedData = (List&RowData&) validData.get("OFFED_ROW");
int rowNum = (Integer) validData.get("DATA_SIZE");
excle 数据总长度
rm.put("ROW_COUNT", rowNum);//业务类的总长度
List&OrgUser& ous = orgUserDao.getOrgUsers(orgId);//获取组织的所有用户
ServiceAuth sa = new ServiceAuth(); //权限对象
sa.setOrgId(orgId);
设置组织id
sa.setServiceCode(Sys.GROUP_ORG); //设置服务编码
多用户版基础服务
sa.setType(Sys.TYPE_BUY); //设置 类型 为购买类型
ServiceAuth nSa = authDao.getOrgServiceAuthInfo(sa); //获取组织服务等级 详细信息
int actSize = ous.size(); // 当前组织已有用户的总长度
int license = nSa.getLicense(); // 组织上限人数
int totalNum = 0;
//设置总数为 0
Org o = orgDao.getOrgById(orgId);
//获取组织对象
Date duration = DateFormater.stringToDate(o.getDuration(), "yyyy-MM-dd"); //获取服务到期时间
//上数据库插入数据
if(null!=users && !users.isEmpty()){
totalNum = actSize + users.size();
//总数现在等于 添加人数和已有人数
if(totalNum & license){//上传人数和原有人数之和小于组织服务人数上限
for(int i=0; i&users.size(); i++){
User u = users.get(i);
u.setPassword(password);
OrgUser ou = orgUsers.get(i);
userDao.addUser(u);
//添加到微信企业号
addCpUser(u);
//添加个人空间
Org selfOrg = new Org();
selfOrg.setAdminName(u.getUserName());
selfOrg.setType(Sys.ORG_TYPE_PER);
selfOrg.setState(Sys.ORG_VERIFY_1);
selfOrg.setAdminId(u.getUserId());
selfOrg.setAdminName(u.getUserName());
selfOrg.setDuration(duration);
selfOrg.setDel(Sys.UN_STOPED);
selfOrg.setCreateTime(new Date());
selfOrg.setUpdateTime(new Date());
selfOrg.setIdparent(0);
orgDao.addOrg(selfOrg);
Dept d = new Dept();
d.setDeptId(0);
addOrgUserRelation(selfOrg, d, u);
if(null!=u.getUserId() && u.getUserName().equals(ou.getOrgUserName())){
ou.setUserId(u.getUserId());
orgUserDao.addOrgUser(ou);
rm.put("PASSED_COUNT", users.size());//成功数据
rm.put("ORG_LICENSE", license);
rm.put("ORG_ACTSIZE", actSize);
rm.put("OVER_LICENSE", totalNum - license);
int offedCount = 0;
if(null!= offedData && !offedData.isEmpty()){
offedCount = offedData.size();
rm.put("OFFED_DATA", offedData);
rm.put("OFFED_COUNT", offedCount);
flag = "success";
msg = "上传成功";
catch (Exception e2) {
logger.error("Exception while uploadOrgUser", e2);
rm.put("flag", flag);
rm.put("msg", msg);
----------------------------------------------------------------------------------------------------------------------------------------------
//辅助方法清单:&
//*************************** 辅助方法一 *****************************************************************
* 校验上传文件
* 参数:文件对象
private Map&String, Object& validUpload(File uploadFile, Integer orgId, Integer deptId) throws Exception{
Map&String, Object& map = new HashMap&String, Object&();
List&User& passed = null;
List&User& offed = null;
List&String& mobileList = userDao.getAllActiveMobile();//为了防止已注册用户再次注册
List&String& emailList = userDao.getAllActiveEmail();//
现在还是查询出所有的
------需要优化标记
//获取上传的excel中的数据
//******辅助方法二*********
ExcelData uploaddata = getUploadUserData(uploadFile);//获取内存中解析好的excle数据对象
//校验上传数据
//******辅助方法三*********
Map&String, Object& dataMap = validUploadData(orgId, deptId, uploaddata, mobileList, emailList); //返回的是数据对象
return dataM
//*************************** 辅助方法二 *****************************************************************
* 获取上传文件的数据
* @param uploadFile
* @throws Exception
private ExcelData getUploadUserData(File uploadFile) throws Exception{
List&User& list = new ArrayList&User&();
String[] columnKey = {"userName", "mobile", "phone", "email", "QQ", "weixin", "job", "dept", "note"};
int startRow = 1;
ExcelData uploadData = FileUtil.parseExcelFile(uploadFile, startRow, columnKey);//将要抛出异常
return uploadD
//*************************** 辅助方法三 *****************************************************************
方法说明:
校验上传数据
* @param orgId
其应该所属的组织
* @param deptId
所选的部门id
* @param excelData excel表格数据对象
* @param mobiles
所有的手机号码 集合
用来判断手机是否注册
* @param emails
所有的邮箱号码 集合
private Map&String, Object& validUploadData(Integer orgId, Integer deptId,ExcelData excelData, List&String& mobiles, List&String& emails) {
Map&String, Object& map = new HashMap&String, Object&();
List&RowData& passed = new ArrayList&RowData&();
List&User& passedUsers = new ArrayList&User&();
// 通过验证的
List&OrgUser& passedOrgUsers = new ArrayList&OrgUser&(); //通过验证的
到m_org_user
List&RowData& offed = new ArrayList&RowData&();
List&RowData& rows = null;//
Date createTime = new Date();//创建时间
Date updateTime = new Date();
//更新时间
List&Dept& deptList = null;
//当前组织的所有部门的
Map&String, Dept& deptMap = new HashMap&String, Dept&();
if(null != excelData && null != excelData.getRows() && !excelData.getRows().isEmpty()){
//如果传入对象不为空
rows = excelData.getRows();
//获取对象中的所有数据
类型应该是List集合 每个元素应该是一行数据 即:RowData
map.put("DATA_SIZE", rows.size());// 设置总数据有多少条
List&String& excelMobiles = new ArrayList&String&();
//用于存放excle表格中的电话号码
List&String& excelEmails = new ArrayList&String&(); //用于存放excle表格中的邮箱号码
deptList = deptDao.getDeptsByOrgId(orgId);//获取所有部门?
for(Dept dept:deptList){
String deptName = dept.getDeptName();
deptMap.put(deptName, dept);//转成map了
35 rowloop:
//行循环跳出坐标准备
for (int i = 0; i & rows.size(); i++) {//循环便利数据
OrgUser orgUser = new OrgUser();
//组织用户 实例化对象准备
User user = new User();
//用户 POJO准备
//获取行数据
RowData r = rows.get(i);
获取行数据
int rowIndex = r.getRowIndex();
获取当前行是第几行
List&CellData& cells = r.getCells();
//获取当前行的所有数据
boolean flag = true;
String userName="",mobile="",phone="",email="",qq="",weixin="",job="";
int mIndex = 0;
int eIndex = 0;
47 columnloop: //列循环跳出坐标准备
for (int j = 0; j & cells.size(); j++) {
// 每一行单元格数据 遍历
CellData c = cells.get(j);
//获取出当前的 数据独立单元格
String key = c.getKey();
//属于哪一列?
String cellValue = c.getCellValue(); //值
if("userName".equals(key)){
userName = cellV
if(StringUtil.isBlank(cellValue)){
flag = false;
c.setPassed(0);
c.setExtraInfo("用户姓名不能为空");
user.setUserName(cellValue);
orgUser.setOrgUserName(cellValue);
} else if("mobile".equals(key)){
//手机相关验证
mobile = cellV
if(!StringUtil.isBlank(cellValue)){
if(!Validator.isMobile(cellValue)){ //校验手机格式
flag = false;
c.setPassed(0);
c.setExtraInfo("不正确的手机号");
if(mobiles.contains(cellValue.trim())){// 比对数据库中的
是否已被注册
flag = false;
c.setPassed(0);
c.setExtraInfo("该手机号已经被使用");
if(excelMobiles.contains(cellValue.trim())){ // 当前表格 数据有重复
flag = false;
c.setPassed(0);
c.setExtraInfo("重复的手机号码");
user.setLoginName(cellValue);
user.setMobile(cellValue);
} else if("phone".equals(key)){ //暂无
phone = cellV
if(!StringUtil.isBlank(cellValue)){
if(!Validator.isPhone(cellValue)){
c.setPassed(0);
c.setExtraInfo("不正确的电话号");
user.setPhone(cellValue);
} else if("email".equals(key)){
// 邮箱相关验证
email = cellV
if(!StringUtil.isBlank(cellValue)){
if(!Validator.isEmail(cellValue)){
flag = false;
c.setPassed(0);
c.setExtraInfo("邮箱格式不正确");
if(emails.contains(cellValue.trim())){
flag = false;
c.setPassed(0);
c.setExtraInfo("该邮箱已经被使用");
if(excelMobiles.contains(cellValue.trim())){
flag = false;
c.setPassed(0);
c.setExtraInfo("重复的邮箱");
user.setLoginName(cellValue);
user.setEmail(cellValue);
} else if("QQ".equals(key)){
qq = cellV
user.setQq(cellValue);
} else if("weixin".equals(key)){
weixin = cellV
user.setWeixin(cellValue);
} else if("job".equals(key)){
job = cellV
orgUser.setPosition(cellValue);
} else if("note".equals(key)){
user.setNote(cellValue);
} else if("dept".equals(key)) {
if(!StringUtil.isBlank(cellValue) && null!=deptMap.get(cellValue.trim())){
Dept d = deptMap.get(cellValue.trim());
orgUser.setDeptId(d.getDeptId());
orgUser.setDeptId(deptId);
//校验手机与邮箱是否同时为空
if(StringUtil.isBlank(mobile) && StringUtil.isBlank(email)){
flag = false;
CellData mobileCell = cells.get(mIndex);//所属的 行和列
CellData emailCell = cells.get(eIndex);
mobileCell.setPassed(0);
//设置是否通过了校验的标识
注:此标识是对单元格数据进行设置的
mobileCell.setExtraInfo("手机与邮箱不能同时为空"); //没有通过校验
emailCell.setPassed(0);
emailCell.setExtraInfo("手机与邮箱不能同时为空");
//验证通过的话
//初始化user 和 orgUser对象
user.setDefaultOrgId(orgId);
user.setMultiLogin(0);
user.setIsDistributor(0);
user.setSrcOrg(orgId);
user.setMobileBinded(0);
user.setEmailBinded(0);
user.setUtype(0);
user.setUpdateTime(updateTime);
user.setCreateTime(createTime);
user.setDel(Sys.UN_STOPED);
user.setType(2);
user.setSource(1);
user.setIspremiumuser(true);
user.setNote("上传生成用户");
user.setPassword("123456");
orgUser.setOrgId(orgId);
orgUser.setDeptId(deptId);
orgUser.setCreateTime(createTime);
orgUser.setUpdateTime(updateTime);
orgUser.setDel(Sys.UN_STOPED);
orgUser.setState(1);
orgUser.setIsDataCommissioner(0);
orgUser.setIsMarketCommissioner(0);
//向通过list里添加数据
passedUsers.add(user);
//添加到通过的
数据列表中去
passedOrgUsers.add(orgUser);
if(!StringUtil.isBlank(mobile)){
excelMobiles.add(mobile);
//添加到 准备的 list中去
以防下面重复数据
在上面验证
if(!StringUtil.isBlank(email)){
excelEmails.add(email);
offed.add(r);
map.put("PASSED_USERS", passedUsers); //
map.put("PASSED_ORGUSERS", passedOrgUsers);
map.put("OFFED_ROW", offed);
==============================================================================================
// &辅助工具类:
1 package com.SS.
3 import com.SS.util.excel.CellD
4 import com.SS.util.excel.ExcelD
5 import com.SS.util.excel.RowD
6 import com.sun.image.codec.jpeg.JPEGC
7 import com.sun.image.codec.jpeg.JPEGEncodeP
8 import com.sun.image.codec.jpeg.JPEGImageE
9 import org.apache.log4j.L
10 import org.apache.poi.hssf.usermodel.HSSFC
11 import org.apache.poi.hssf.usermodel.HSSFR
12 import org.apache.poi.hssf.usermodel.HSSFS
13 import org.apache.poi.hssf.usermodel.HSSFW
14 import org.apache.poi.ss.usermodel.C
15 import org.apache.poi.xssf.usermodel.XSSFC
16 import org.apache.poi.xssf.usermodel.XSSFR
17 import org.apache.poi.xssf.usermodel.XSSFS
18 import org.apache.poi.xssf.usermodel.XSSFW
20 import javax.imageio.ImageIO;
21 import java.awt.*;
22 import java.awt.image.BufferedI
23 import java.io.*;
24 import java.util.ArrayL
25 import java.util.L
* 文件操作工具类
30 public class FileUtil {
private Logger logger = Logger.getLogger(FileUtil.class);
* 获取文件的后缀名称
* @param file
public static String getFileSuffix(File file){
String suffix = "";
if(null != file && StringUtil.isBlank(file.getName())){
String fileName = file.getName();
suffix = fileName.substring(fileName.lastIndexOf("."));
* 解析excel文件
* @param file excel文件
* @param startRow 起始行 0为第一行
* @param columnKey
每列对应的key值
public static ExcelData parseExcelFile(File file, int startRow, String[] columnKey){
List&RowData& rows = null;
ExcelData excelData = new ExcelData();
if(null==file || !file.exists() || columnKey.length&1){
return excelD
String fileName = file.getName();
excelData.setFileName(fileName);
if(fileName.endsWith("xls")){
rows = parse2003Excel(file, startRow, columnKey);
} else if(fileName.endsWith("xlsx")){
rows = parse2007Excel(file, startRow, columnKey);
throw new RuntimeException("Unknown file type : "+fileName);
excelData.setRows(rows);
} catch (Exception e) {
e.printStackTrace();
return excelD
* 解析2003 excel文件
* @param file excel文件
* @param startRow 起始行 0为第一行
第一行已经有 头了
* @param columnKey
每列对应的key值
private static List&RowData& parse2003Excel(File file, int startRow, String[] columnKey){
List&RowData& rows = new ArrayList&RowData&();
String fileName = file.getName();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));//获取输入流
HSSFWorkbook wk = new HSSFWorkbook(bis); // poi提供的类
HSSFSheet sheet = wk.getSheetAt(0);//获取一片?
HSSFCell cell = null;
for(int rowIndex=startR rowIndex&=sheet.getLastRowNum(); rowIndex++){
//getLastRowNum 获取最后一行的行号
HSSFRow row = sheet.getRow(rowIndex);
//获取行数据
if(null==row){
//如果这行数据为空
RowData rowData = new RowData(rowIndex+1);//起始是2
行数据存储对象初始化
List&CellData& cells = new ArrayList&CellData&();//
单元格s 对象存储对象初始化
for(int columnIndex=0; columnIndex&columnKey. columnIndex++){
String key = columnKey[columnIndex];
String cellValue = "";
cell = row.getCell(columnIndex); //获取独立单元格对象
if(null!=cell){
cell.setCellType(Cell.CELL_TYPE_STRING);//设置对象数据类型为String
cellValue = cell.getStringCellValue(); // 获取数据
是String 因为上面转换了
if(!StringUtil.isBlank(cellValue)){
cellValue = cellValue.trim(); //非空进行剪切
CellData cellData = new CellData(columnIndex+1, cellValue, key);//单元格数据对象实例化
参数有: 的列的位置
对应的列明
cells.add(cellData);
//添加到单元格s对象中去
rowData.setCells(cells);
// 行数据添加
rows.add(rowData); // 行数据列表 添加 行数据
//关闭输入流
bis.close();
} catch (Exception e) {
e.printStackTrace();
//rows 可以说是 内存中的转化好的表格格式正确文件内容对象
* 解析2007 excel文件
* @param file excel文件
* @param startRow 起始行 0为第一行
* @param columnKey
每列对应的key值
private static List&RowData& parse2007Excel(File file, int startRow, String[] columnKey){
List&RowData& rows = new ArrayList&RowData&();
String fileName = file.getName();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
XSSFWorkbook wb = new XSSFWorkbook(in);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFCell cell = null;
for(int rowIndex=startR rowIndex&=sheet.getLastRowNum(); rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if(null==row){
RowData rowData = new RowData(rowIndex+1);
List&CellData& cells = new ArrayList&CellData&();
for(int columnIndex=0; columnIndex&columnKey. columnIndex++){
String key = columnKey[columnIndex];
String cellValue = "";
cell = row.getCell(columnIndex);
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getStringCellValue();
if(!StringUtil.isBlank(cellValue)){
cellValue = cellValue.trim();
CellData cellData = new CellData(columnIndex+1, cellValue, key);
cells.add(cellData);
rowData.setCells(cells);
rows.add(rowData);
//关闭输入流
in.close();
} catch (Exception e) {
e.printStackTrace();
1 public class Validator {
/*public static void main(String[] args) {
String mobile = "";
String phone = "010-";
String username = "fdsdfsdj";
System.out.println(Validator.isUsername(username));
System.out.println(Validator.isChinese(username));
String email = "";
System.out.println("isMobile="+Validator.isMobile(mobile));
System.out.println("isPhone="+Validator.isPhone(phone));
String regex = "^zo+$";
String str = "zozo";
boolean flag = Validator.testString(regex, str);
System.out.println(flag);
public static boolean testString(String regex, String str){
return Pattern.matches(regex, str);
* 正则表达式:验证用户名
public static final String REGEX_USERNAME = "^[a-zA-Z]\\w{5,17}$";
* 正则表达式:验证密码
public static final String REGEX_PASSWORD = "^[a-zA-Z0-9]{6,16}$";
* 正则表达式:验证手机号
public static final String REGEX_MOBILE = "^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9])|(17[0-9]))\\d{8}$";
* 正则表达式:验证固话
public static final String REGEX_PHONE = "^(0\\d{2}-\\d{8})|(0\\d{3}-\\d{7})|(0\\d{3}-\\d{8})$";
* 正则表达式:验证qq
public static final String REGEX_QQ = "^[1-9][0-9]{4,} $";
* 正则表达式:验证邮箱
public static final String REGEX_EMAIL = "^[A-Za-z0-9][\\w\\-\\.]{1,12}@([\\w\\\\-]+\\.)+[\\w]{2,3}$";
* 正则表达式:验证汉字
public static final String REGEX_CHINESE = "^[\u4e00-\u9fa5],{0,}$";
* 正则表达式:验证身份证
public static final String REGEX_ID_CARD = "(^\\d{18}$)|(^\\d{15}$)";
* 正则表达式:验证URL
public static final String REGEX_URL = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
* 正则表达式:验证IP地址
public static final String REGEX_IP_ADDR = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
* 校验用户名
* @param username
* @return 校验通过返回true,否则返回false
public static boolean isUsername(String username) {
return Pattern.matches(REGEX_USERNAME, username);
* 校验密码
* @param password
* @return 校验通过返回true,否则返回false
public static boolean isPassword(String password) {
return Pattern.matches(REGEX_PASSWORD, password);
* 校验手机号
* @param mobile
* @return 校验通过返回true,否则返回false
public static boolean isMobile(String mobile) {
return Pattern.matches(REGEX_MOBILE, mobile);
* 校验邮箱
* @param email
* @return 校验通过返回true,否则返回false
public static boolean isEmail(String email) {
return Pattern.matches(REGEX_EMAIL, email);
* 校验固话
* @param phone
public static boolean isPhone(String phone){
return Pattern.matches(REGEX_PHONE, phone);
* @param qq
public static boolean isQQ(String qq){
return Pattern.matches(REGEX_QQ, qq);
* 校验汉字
* @param chinese
* @return 校验通过返回true,否则返回false
public static boolean isChinese(String chinese) {
return Pattern.matches(REGEX_CHINESE, chinese);
* 校验身份证
* @param idCard
* @return 校验通过返回true,否则返回false
public static boolean isIDCard(String idCard) {
return Pattern.matches(REGEX_ID_CARD, idCard);
* @param url
* @return 校验通过返回true,否则返回false
public static boolean isUrl(String url) {
return Pattern.matches(REGEX_URL, url);
* 校验IP地址
* @param ipAddr
public static boolean isIPAddr(String ipAddr) {
return Pattern.matches(REGEX_IP_ADDR, ipAddr);
======================
下面是解析excle文档的 &文档与内存对象的对应转换关系:
----ajax请求返回 后进行处理:
success: function (data, status) {//服务器成功响应处理函数
$('#uploadTxt').text('导入');
$('#loadingImg').hide();
if('success'==data.flag){
$('#btn_upSubmit').show();
$('#uploading').hide();
$('#btn_upCancel').trigger('click');
$("#orgUserTable").trigger("reloadGrid", [{page: 1}]);
var offedCount = data.OFFED_COUNT;
var rowCount = data.ROW_COUNT;
var offedData = data.OFFED_DATA;
var orgLicense = data.ORG_LICENSE;
var overLicense = data.OVER_LICENSE;
var actSize = data.ORG_ACTSIZE;
if(0&overLicense && 0!=orgLicense){//存在超出数据
$('#licenseNum').text(orgLicense);
$('#actNum').text(actSize);
$('#uploadMsg1').hide();
$('#uploadMsg2').show();
//显示错误信息
$('#showErrData').trigger('click');
if(0 != offedCount){
$('#totalCount').text(rowCount);
$('#errCount').text(offedCount);
$('#uploadMsg2').hide();
$('#uploadMsg1').show();
$('#err_body').find('tr').remove();
var errBody = $('#err_body');
for(var i=0; i&offedData. i++){
var tr = createTrObj();
var rowData = offedData[i];
var rowIndex = rowData.rowI
var cells = rowData.
$(tr).find('td[role="rowIndex"]').text(rowIndex);
for(var j=0; j&cells. j++){
var cell = cells[j];
var cellValue = cell.cellV
var extraInfo = cell.extraI
switch(cell.key){
case 'userName':
td = $(tr).find('td[role="name"]').text(cellValue);
case 'mobile':
td = $(tr).find('td[role="mobile"]').text(cellValue);
case 'phone':
td = $(tr).find('td[role="phone"]').text(cellValue);
case 'email':
td = $(tr).find('td[role="email"]').text(cellValue);
case 'QQ':
td = $(tr).find('td[role="QQ"]').text(cellValue);
case 'weixin':
td = $(tr).find('td[role="weixin"]').text(cellValue);
case 'job':
td = $(tr).find('td[role="position"]').text(cellValue);
case 'note':
td = $(tr).find('td[role="note"]').text(cellValue);
if(null!=extraInfo && ''!=extraInfo && 'undefined'!=extraInfo){
td.attr('class','font-rb');
if('userName'==cell.key){
td.attr('class','bggray');
if(('mobile'==cell.key||'email'==cell.key) && ''==cellValue){
td.attr('class','bggray');
td.attr('title',extraInfo);
$(tr).appendTo(errBody);
//显示错误信息
$('#showErrData').trigger('click');
title: "上传成功!",
//text: "点击下方按钮关闭提示框!",
type: "success"
}},展示相关错误信息文件内容为:
上传过程:
上传后返回:
// &注明: &应博友提醒发现少了三个文件 源码 &现补充 &
1 package com.SS.util.
3 import java.util.L
6 public class RowData {
private int rowI
private List&CellData&
public RowData(){}
public RowData(int index){
this.rowIndex =
public int getRowIndex() {
return rowI
public void setRowIndex(int rowIndex) {
this.rowIndex = rowI
public List&CellData& getCells() {
public void setCells(List&CellData& cells) {
this.cells =
1 package com.SS.util.
3 import java.util.L
8 public class RowData {
private int rowI
private List&CellData&
public RowData(){}
public RowData(int index){
this.rowIndex =
public int getRowIndex() {
return rowI
public void setRowIndex(int rowIndex) {
this.rowIndex = rowI
public List&CellData& getCells() {
public void setCells(List&CellData& cells) {
this.cells =
1 package com.SS.util.
* version 1.0
7 public class CellData {
* 单元格列数
private int columnI
* 单元格数据
private String cellV
* 附加信息
private String extraI
* 对应数据的key
* 是否通过校验
* 0 未通过
private int passed=1;
private boolean mobile = true;
public CellData(){}
public CellData(int index, String content, String dataKey){
this.columnIndex =
this.cellValue =
this.key = dataK
public int getColumnIndex() {
return columnI
public void setColumnIndex(int columnIndex) {
this.columnIndex = columnI
public String getCellValue() {
return cellV
public void setCellValue(String cellValue) {
this.cellValue = cellV
public String getExtraInfo() {
return extraI
public void setExtraInfo(String extraInfo) {
this.extraInfo = extraI
public String getKey() {
public void setKey(String key) {
this.key =
public int getPassed() {
public void setPassed(int passed) {
this.passed =
阅读(...) 评论()}

我要回帖

更多关于 制作excel表格全步骤 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信