jeecg3.5中的导⼊excel⽂件的使⽤及完善
jeecg中导⼊导出excel⽂件使⽤了jeecg团队⾃⼰开发的⼀个easypoi库,所以使⽤起来⾮常简单,以我项⽬中导⼊⿊名单列表功能为例:
iview therapeutics1. 在实体中增加注解
先增加类的注解:
@ExcelTarget("blackListEntity")
public class BlackListEntity implements java.io.Serializable {
再增加字段注解:
/**⼿机号码*/
@Excel(name="⼿机号码")
private Long msisdn;
/**状态*/
@Excel(name="状态",replace = {"启⽤_1","禁⽤_0"})
private Integer state;
jquery下载的文件怎么使用在jsp界⾯中使⽤upload标签,如下:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/context/mytags.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>Excel导⼊</title>
<t:base type="jquery,easyui,tools"></t:base>
</head>
<body scroll="no">
<t:formvalid formid="formobj" layout="div" dialog="true" beforeSubmit="upload">
<fieldset class="step">
<div class="form"><t:upload name="fiels" buttonText="选择要导⼊的⽂件" uploader="blackListController.do?importExcel" extend="*.xls;*.xlsx" id="file_upload" for <div class="form" id="filediv" ></div>
</fieldset>
</t:formvalid>
</body>
</html>
在controller中接收上传的⽂件并调⽤easypoi的api进⾏⽂件的解析就可以了,如下:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = FileMap();
List<BlackListEntity> allRecords = new ArrayList<BlackListEntity>();
for (Map.Entry<String, MultipartFile> entity : Set()) {
MultipartFile file = Value();// 获取上传⽂件对象
ImportParams params = new ImportParams();
params.setTitleRows(0);
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<BlackListEntity> listBlackList = ExcelImportUtil.InputStream(),BlackListEntity.class,params);
allRecords.addAll(listBlackList);
} catch (Exception e) {
<(ExceptionMessage(e));
}finally{
try {
} catch (IOException e) {
e.printStackTrace();
}
}
}
这样⼀个导⼊excel⽂件的功能就做好了,easypoi会把excel⽂件中的数据解析成为⼀个List对象,接下去要怎么处理就跟具体的业务逻揖
有关了。
但我们实际开发中往往会遇到这样的需求:客户希望导⼊失败的信息也能够查看,如这个导⼊⿊名单功能中就要求⼿机号码不能重复,如果
⼿机号码在数据库中存的话要在导⼊完成后让⽤户可以下载错误⽂件查看哪些号码是导重复了。
我的解决思路⼤概如下:
1. 在service中保存数据时检查号码在数据库中是否已经存在,如果存在则产⽣⼀个ErrorMsg类的实例放放到List中
2. 对这个List进⾏循环⽣成excel⽂件写⼊到磁盘中
3. 产⽣⼀个TSAttachment的实例,也就是往jeecg的附件表中增加⼀条附件记录,把错误⽇志当作⼀个附件保存起来
4. 把下载这个附件的链接返回到jsp界⾯
完整代码如下:
jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/context/mytags.jsp"%>
<!DOCTYPE html>
<html>
<head>
<title>Excel导⼊</title>
<t:base type="jquery,easyui,tools"></t:base>
</head>
<body scroll="no">
<t:formvalid formid="formobj" layout="div" dialog="true" beforeSubmit="upload">
<fieldset class="step">
<div class="form"><t:upload name="fiels" buttonText="选择要导⼊的⽂件" uploader="blackListController.do?importExcel" extend="*.xls;*.xlsx" id="file_upload" for <div class="form" id="filediv" ></div>
</fieldset>
</t:formvalid>
</body>
</html>
controller
@RequestMapping(params = "importExcel", method = RequestMethod.POST)
@ResponseBody
public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = FileMap();
List<BlackListEntity> allRecords = new ArrayList<BlackListEntity>();
for (Map.Entry<String, MultipartFile> entity : Set()) {
MultipartFile file = Value();// 获取上传⽂件对象
ImportParams params = new ImportParams();
params.setTitleRows(0);
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<BlackListEntity> listBlackList = ExcelImportUtil.InputStream(),BlackListEntity.class,params);
allRecords.addAll(listBlackList);
} catch (Exception e) {
<(ExceptionMessage(e));
}finally{
savefiledialog是什么对话框try {
} catch (IOException e) {
e.printStackTrace();
}
}
}
AjaxJson j = this.blackListService.saveBlackLists(allRecords, request);
return j;
}
对应的两个service类(接⼝我就没贴了,只贴实现类的代码),其中⽤到了jeecg中的AjaxJson类⽤来返回json结果BlackListServiceImpl
public AjaxJson saveBlackLists(List<BlackListEntity> listBlackList, HttpServletRequest request) {
List<BlackListEntity> actualList = new ArrayList<BlackListEntity>();
List<ErrorMsg> errorMsgList = new ArrayList<ErrorMsg>();
long tempCount = 0;
int idx = 0;
for (BlackListEntity blackList : listBlackList) {
idx++;
//判断⿊名单号码在数据库中是否存在
tempCount = CountForJdbcParam(GET_COUNT, new String[]{Msisdn().toString()});
if (tempCount == 0) {
actualList.add(blackList);
} else {
//创建错误信息,包括⾏号,错误信息两个字段
指针调用成员函数ErrorMsg errorMsg = new ErrorMsg();
errorMsg.setNum(idx + 1);
errorMsg.setMsg("⼿机号码" + Msisdn() + "在系统中已经存在");
errorMsgList.add(errorMsg);
}
}
if (!actualList.isEmpty()) {
super.batchSave(actualList);
//产⽣重新加载⿊名单事件
EventEntity event = new EventEntity();
event.setEventId("ReloadBlackListEvent");
super.save(event);
}
AjaxJson j = new AjaxJson();
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("successNum", actualList.size());
attributes.put("failNum", errorMsgList.size());
if (!errorMsgList.isEmpty()) {
String downloadHref = MsgService.saveErrorMsg(errorMsgList, request, attributes);
StringBuilder builder = new StringBuilder("导⼊完成,但有⼀些数据导⼊失败,您可以");
builder.append("<a href=\"").append(downloadHref).append("\">下载错误信息</a>进⾏查看");
j.String());
} else {
j.setMsg("导⼊成功");
}
return j;
}
ErrorMsgServiceImpl(⽤来封装⽣成错误⽇志及⽣成附件记录并返回链接的逻揖):
/**
*
*/
package com.jason.ddoWeb.service.implmon;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.poi.ss.usermodel.Workbook;break跳出while循环用法
import n.service.impl.CommonServiceImpl;
import n.service.impl.CommonServiceImpl;
import util.ResourceUtil;
import org.l.ExcelExportUtil;
import org.l.entity.TemplateExportParams;
import org.jeecgframework.web.system.pojo.base.TSAttachment;
import org.springframework.stereotype.Service;
import ansaction.annotation.Transactional;
import com.del.ErrorMsg;
import com.jason.ddoWeb.servicemon.ErrorMsgServiceI;
/**
* ⽣成错误信息公共service
* @author jasonzhang
*
*/
@Service("errorMsgService")
@Transactional
public class ErrorMsgServiceImpl extends CommonServiceImpl implements
ErrorMsgServiceI {
/
* (non-Javadoc)
* @see com.jason.ddoWeb.servicemon.ErrorMsgServiceI#saveErrorMsg(java.util.List, javax.servlet.http.HttpServletRequest, java.util.Map)
*/
@Override
public String saveErrorMsg(List<ErrorMsg> errorMsgs,
HttpServletRequest request, Map<String, Object> attributes) {
//把错误信息写⼊⽂件
TemplateExportParams params = new TemplateExportParams();
params.setHeadingRows(1);
params.setHeadingStartRow(0);
params.setTemplateUrl("export/template/errormsgtemp.xls");
Map<String,Object> map = new HashMap<String, Object>();
特斯拉事件介绍Workbook book = portExcel(params, ErrorMsg.class, errorMsgs, map);
String uploadbasepath = ConfigByName("uploadpath");
String path = uploadbasepath + "/";// ⽂件保存在硬盘的相对路径
String realPath = Session().getServletContext().getRealPath("/") + "/" + path;// ⽂件的硬盘真实路径
File file = new File(realPath);
if (!ists()) {
file.mkdirs();// 创建根⽬录
}
String errormsgPath = realPath + "/" + ConfigByName("errormsgpath");
file = new File(errormsgPath);
if (!ists()) {
file.mkdirs();
}
String fileName = System.currentTimeMillis() + ".xls";
//String filePath = errormsgPath + "/" + fileName;
try {
FileOutputStream fos = new FileOutputStream(errormsgPath + "/" + fileName);
book.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TSAttachment attachment = new TSAttachment();
attachment.setRealpath("/" + ConfigByName("uploadpath") + "/" + ConfigByName("errormsgpath") + "/" + fileName); attachment.setAttachmenttitle(fileName);
attachment.setExtend("xls");
super.save(attachment);
StringBuilder builder = new StringBuilder();
builder.append("commonController.do?viewFile&fileid=").Id());
String();
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论