jeecg中導入導出excel文件使用了jeecg團隊本身開發的一個easypoi庫,因此使用起來很是簡單,以我項目中導入黑名單列表功能爲例:html
在實體中增長註解java
先增長類的註解:jquery
@ExcelTarget("blackListEntity") public class BlackListEntity implements java.io.Serializable {
再增長字段註解:web
/**手機號碼*/ @Excel(name="手機號碼") private Long msisdn; /**狀態*/ @Excel(name="狀態",replace = {"啓用_1","禁用_0"}) private Integer state;
在jsp界面中使用upload標籤,以下:spring
<%@ 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 style="overflow-y: hidden" 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" formData="documentTitle"></t:upload></div> <div class="form" id="filediv" style="height: 50px"></div> </fieldset> </t:formvalid> </body> </html>
在controller中接收上傳的文件並調用easypoi的api進行文件的解析就能夠了,以下:數據庫
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Map<String, MultipartFile> fileMap = multipartRequest.getFileMap(); List<BlackListEntity> allRecords = new ArrayList<BlackListEntity>(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 獲取上傳文件對象 ImportParams params = new ImportParams(); params.setTitleRows(0); params.setHeadRows(1); params.setNeedSave(true); try { List<BlackListEntity> listBlackList = ExcelImportUtil.importExcelByIs(file.getInputStream(),BlackListEntity.class,params); allRecords.addAll(listBlackList); } catch (Exception e) { logger.error(ExceptionUtil.getExceptionMessage(e)); }finally{ try { file.getInputStream().close(); } catch (IOException e) { e.printStackTrace(); } } }
這樣一個導入excel文件的功能就作好了,easypoi會把excel文件中的數據解析成爲一個List對象,接下去要怎麼處理就跟具體的業務邏揖有關了。apache
但咱們實際開發中每每會遇到這樣的需求:客戶但願導入失敗的信息也可以查看,如這個導入黑名單功能中就要求手機號碼不能重複,若是手機號碼在數據庫中存的話要在導入完成後讓用戶能夠下載錯誤文件查看哪些號碼是導重複了。json
個人解決思路大概以下:api
在service中保存數據時檢查號碼在數據庫中是否已經存在,若是存在則產生一個ErrorMsg類的實例放放到List中
app
對這個List進行循環生成excel文件寫入到磁盤中
產生一個TSAttachment的實例,也就是往jeecg的附件表中增長一條附件記錄,把錯誤日誌看成一個附件保存起來
把下載這個附件的連接返回到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 style="overflow-y: hidden" 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" formData="documentTitle"></t:upload></div> <div class="form" id="filediv" style="height: 50px"></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 = multipartRequest.getFileMap(); List<BlackListEntity> allRecords = new ArrayList<BlackListEntity>(); for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) { MultipartFile file = entity.getValue();// 獲取上傳文件對象 ImportParams params = new ImportParams(); params.setTitleRows(0); params.setHeadRows(1); params.setNeedSave(true); try { List<BlackListEntity> listBlackList = ExcelImportUtil.importExcelByIs(file.getInputStream(),BlackListEntity.class,params); allRecords.addAll(listBlackList); } catch (Exception e) { logger.error(ExceptionUtil.getExceptionMessage(e)); }finally{ try { file.getInputStream().close(); } 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 = super.getCountForJdbcParam(GET_COUNT, new String[]{blackList.getMsisdn().toString()}); if (tempCount == 0) { actualList.add(blackList); } else { //建立錯誤信息,包括行號,錯誤信息兩個字段 ErrorMsg errorMsg = new ErrorMsg(); errorMsg.setNum(idx + 1); errorMsg.setMsg("手機號碼" + blackList.getMsisdn() + "在系統中已經存在"); 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 = this.errorMsgService.saveErrorMsg(errorMsgList, request, attributes); StringBuilder builder = new StringBuilder("導入完成,但有一些數據導入失敗,您能夠"); builder.append("<a href=\"").append(downloadHref).append("\">下載錯誤信息</a>進行查看"); j.setMsg(builder.toString()); } else { j.setMsg("導入成功"); } return j; }
ErrorMsgServiceImpl(用來封裝生成錯誤日誌及生成附件記錄並返回連接的邏揖):
/** * */ package com.jason.ddoWeb.service.impl.common; 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; import org.jeecgframework.core.common.service.impl.CommonServiceImpl; import org.jeecgframework.core.util.ResourceUtil; import org.jeecgframework.poi.excel.ExcelExportUtil; import org.jeecgframework.poi.excel.entity.TemplateExportParams; import org.jeecgframework.web.system.pojo.base.TSAttachment; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jason.ddoWeb.common.model.ErrorMsg; import com.jason.ddoWeb.service.common.ErrorMsgServiceI; /** * 生成錯誤信息公共service * @author jasonzhang * */ @Service("errorMsgService") @Transactional public class ErrorMsgServiceImpl extends CommonServiceImpl implements ErrorMsgServiceI { /* (non-Javadoc) * @see com.jason.ddoWeb.service.common.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 = ExcelExportUtil.exportExcel(params, ErrorMsg.class, errorMsgs, map); String uploadbasepath = ResourceUtil.getConfigByName("uploadpath"); String path = uploadbasepath + "/";// 文件保存在硬盤的相對路徑 String realPath = request.getSession().getServletContext().getRealPath("/") + "/" + path;// 文件的硬盤真實路徑 File file = new File(realPath); if (!file.exists()) { file.mkdirs();// 建立根目錄 } String errormsgPath = realPath + "/" + ResourceUtil.getConfigByName("errormsgpath"); file = new File(errormsgPath); if (!file.exists()) { 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("/" + ResourceUtil.getConfigByName("uploadpath") + "/" + ResourceUtil.getConfigByName("errormsgpath") + "/" + fileName); attachment.setAttachmenttitle(fileName); attachment.setExtend("xls"); super.save(attachment); StringBuilder builder = new StringBuilder(); builder.append("commonController.do?viewFile&fileid=").append(attachment.getId()); return builder.toString(); } }