您的位置:首页 > 编程语言 > Java开发

Java读取Execl表格数据

2014-04-26 15:58 447 查看
在前面提到用java代码新建一个Execl 表格并添加数据到表格中,

这次写了一个读取Execl表格数据并添加导数据库中的案列

给定对方一个Execl模板表格,如果导入的Execl表格和预订的表格不相符,给予对应的提示

如果全部都符合要求则把读取到的每一行数据对象添加到数据库中去(需考虑导入数量大小问题)

所需 jxl.jar 下载地址 http://pan.baidu.com/s/1pJsXKEJ
HTML代码

<div id="saveCustom">

<form action="<%=path%>/custom/testAction!addCustomByExcel.action" method="post" name="excelForm" id="excelForm" enctype="multipart/form-data">
<s:token name="token" id="token"/>
<table width="100%" border="0" align="center" style="border-left: 1px #ccc solid; border-bottom: 1px #ccc solid; border-right: 1px #ccc solid; background-color: white;" >
<tr>
<td height="60" class="title" colspan="2">Excel文档导入</td>
</tr>
<tr align="center">
<td style="height: 60px;" >
<span style="color: red; font-size: 14px;"><strong>请选择Excel文档1:</strong></span>     
<input type="file" name="customExcel" id="customExcel"/>

      <a href="<%=path + "/jsp/template.xls"%>" target="_blank"><span style="color: red"><strong>[模板下载]</strong></span</a>
</br>
</td>
</tr>
<tr align="center">
<td style="border-top: 1px #eee dashed; height: 40px;">
<input type="submit" name="sub" value=" 提 交 " sytle="cursor: pointer;" class="sub"/>
<input type="button" name="return" value="取 消" sytle="cursor: pointer;" onclick="$.unblockUI()" class="sub"/>
</td>
</tr>
</table>
</form>

</div>

//Action 控制层

private CustomService customService;//spring IOC注入service对象

private File customExcel;
public File getCustomExcel() {
return customExcel;
}
public void setCustomExcel(File customExcel) {
this.customExcel = customExcel;
}

public void setCustomService(CustomService customService)
{
this.customService = customService;
}

public String addCustomByExcel() {
String token = getP("token"); //拿到页面上传来的token值 防止重复提价导入
String sessionToken=(String)getSession().getAttribute("struts.tokens.token");
if(null!=sessionToken&&sessionToken.equals(token)){
if (customExcel != null) {
Long size = customExcel.length();//拿到上传文件的长度
if (size > 1024 * 1024 * 5) {
getRequest().setAttribute("error", "请选择小于5M的文件!");
return "errorInfo";
} else {
String result = customService.customByExcel(customExcel);
String[] results = result.split(":");//返回哪行哪列格式有误
if("5000Y1".equals(result)){
getRequest().setAttribute("error", "请下载新模板!");
return "errorInfo";
}
if (results.length == 1) {//导入文件操作提示
getRequest().setAttribute("info", "success");
getRequest().setAttribute("num",results[0]);
} else {
getRequest().setAttribute("error","第" + results[0] + "行,列名为\""+results[1]+"\"数据格式有问题,检查是否存在空格!");
}
}
} else {
getRequest().setAttribute("error", "请选择一个要导入的excel文件!");
return "errorInfo";
}
}else{
getRequest().setAttribute("error", "请勿重复提交!");
return "errorInfo";
}
return "errorInfo";
}

//Service层

private HibernateTransactionManager transactionManager;//事物对象spring IOC注入
public HibernateTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(HibernateTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}

public String customByExcel(File customExcel) {
Workbook wb = null;
List<Custom> customs=new ArrayList<Custom>();
int rowNum = 0;//总行数
String sgin="succeed";//表示导入表格当中的每一行都符合模板要求
String errorRow="",errorCol="",result="";//标记错误数据在第几行 和那个字段 最终返回结果

//事物回滚处理
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = transactionManager.getTransaction(def);
try {
wb=Workbook.getWorkbook(customExcel);
if(wb!=null){
Sheet[] sheet=wb.getSheets();
if(sheet != null && sheet.length > 0){
rowNum = sheet[0].getRows()-1;//拿到总行数
Cell[] cells2 = sheet[0].getRow(0);

        //查看必填列 列名字是否和模板一致
if(cells2.length != 9 || !"中文名".equals(cells2[0].getContents().replace(" ", "")) ||
!"性别".equals(cells2[2].getContents().replace(" ", "")) ||
!"证件类型".equals(cells2[3].getContents().replace(" ", "")) ||
!"证件号码".equals(cells2[4].getContents().replace(" ", "")) ||
!"所在国家".equals(cells2[5].getContents().replace(" ", ""))
){
return "5000Y1";//模板格式不正确
}

for(int i=1;i<rowNum;i++){
Cell[] cells = sheet[0].getRow(i);//拿到第一个表空间的第i列的数据
if(cells!=null && cells.length>0){
if ("pass".equals(colIsNotEmpty(cells))) {//必填字段都不等于空
Custom custom=new Custom();
      //把读取到的数据填充到对象中、、、、、、、、、            

System.out.println(cells[0].getContents().replace(" ", "").toString()+"::"
+cells[1].getContents().replace(" ", "").toString()+"::"
+cells[2].getContents().replace(" ", "").toString()+"::"
+cells[3].getContents().replace(" ", "").toString()+"::"
+cells[4].getContents().replace(" ", "").toString()+"::"
+cells[5].getContents().replace(" ", "").toString()+"::"
+cells[6].getContents().replace(" ", "").toString()+"::"
+cells[7].getContents().replace(" ", "").toString()+"::"
+cells[8].getContents().replace(" ", "").toString()
);
customs.add(custom);
}else{
errorCol=colIsNotEmpty(cells);
errorRow=(i+1)+"";
sgin="failure";
break;
}
}
}

if(sgin.equals("succeed")){//如果模板正确并且数据格式也符合要求就添加本次导入的数据
for(Custom c:customs){
customDao.saveCustom(c);
}
result=customs.size()+"";//返回成功添加条数
transactionManager.commit(status);
}else {
result=errorRow+":"+errorCol;//返回错误行和列信息
}
}
}
} catch (Exception e) {
transactionManager.rollback(status);//添加数据或者是其他发生异常回滚
e.printStackTrace();
}
return result;
}

//验证必填字段是否都符合要求,如果不符合要求则返回字段名称

public String colIsNotEmpty(Cell[] cells){
if(!StringUtils.isNotEmpty(cells[0].getContents().replace(" ", ""))){
return "中文名";
}
if(!StringUtils.isNotEmpty(cells[2].getContents().replace(" ", ""))){
return "性别";
}
if(!StringUtils.isNotEmpty(cells[3].getContents().replace(" ", ""))){
return "证件类型";
}
if(!StringUtils.isNotEmpty(cells[4].getContents().replace(" ", ""))){
return "证件号码";
}
if(!StringUtils.isNotEmpty(cells[5].getContents().replace(" ", ""))){
return "所在国家";
}
return "pass";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: