POI导入导出Excel 利用自定义注解

1、自定义注解

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by wangjianjun on 2017/5/5.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target( { java.lang.annotation.ElementType.FIELD })
public @interface ExcelVOAttribute {

    /**
     * 字段名
     * @return
     */
    String name() default "";

    /**
     *  配置列的名称,对应A,B,C,D....
     * @return
     */
    String column();

    /**
     * 提示信息
     * @return
     */
    String prompt() default "";

    boolean isExport() default true;
}

  2、定义对应的excel列头对象,与实体对象进行转化

 1 public class EXCheckPlan {
 2 
 3     /**计划名称*/
 4     @ExcelVOAttribute(name = "plan_name",column = "A")
 5     public String planName;
 6     /**是否可用*/
 7     @ExcelVOAttribute(name = "enabled",column = "B")
 8     public boolean enabled;
 9     /**计划类型*/
10     @ExcelVOAttribute(name = "plan_type",column = "C")
11     public String planType;
12     /**cron表达式*/
13     @ExcelVOAttribute(name = "cron",column = "D")
14     public String cron;
15     /**任务执行参数:json格式*/
16     @ExcelVOAttribute(name = "params_json",column = "E")
17     public String paramsJson;
18     /**计划状态*/
19     @ExcelVOAttribute(name = "plan_status",column = "F")
20     public String planStatus;
21     /**关联的对账定义*/
22     @ExcelVOAttribute(name = "ref_check_name",column = "G")
23     public String refCheckName;
24     /**计划备注*/
25     @ExcelVOAttribute(name = "remark",column = "H")
26     public String remark;
27 
28     public void setPlanName(String planName) {
29         this.planName = planName;
30     }
31 
32     public void setEnabled(boolean enabled) {
33         this.enabled = enabled;
34     }
35 
36     public void setPlanType(String planType) {
37         this.planType = planType;
38     }
39 
40     public void setCron(String cron) {
41         this.cron = cron;
42     }
43 
44     public void setParamsJson(String paramsJson) {
45         this.paramsJson = paramsJson;
46     }
47 
48     public void setPlanStatus(String planStatus) {
49         this.planStatus = planStatus;
50     }
51 
52     public void setRefCheckName(String refCheckName) {
53         this.refCheckName = refCheckName;
54     }
55 
56     public void setRemark(String remark) {
57         this.remark = remark;
58     }
59 
60     public String getPlanName() {
61         return planName;
62     }
63 
64     public boolean isEnabled() {
65         return enabled;
66     }
67 
68     public String getPlanType() {
69         return planType;
70     }
71 
72     public String getCron() {
73         return cron;
74     }
75 
76     public String getParamsJson() {
77         return paramsJson;
78     }
79 
80     public String getPlanStatus() {
81         return planStatus;
82     }
83 
84     public String getRefCheckName() {
85         return refCheckName;
86     }
87 
88     public String getRemark() {
89         return remark;
90     }
91 }

3、核心操作工具

  1 import org.apache.poi.hssf.usermodel.HSSFCell;
  2 import org.apache.poi.hssf.usermodel.HSSFRow;
  3 import org.apache.poi.hssf.usermodel.HSSFSheet;
  4 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  5 import org.apache.poi.ss.usermodel.CellType;
  6 import org.omg.CORBA.Object;
  7 
  8 import javax.servlet.http.HttpServletRequest;
  9 import javax.servlet.http.HttpServletResponse;
 10 import java.io.*;
 11 import java.lang.reflect.Field;
 12 import java.net.URL;
 13 import java.text.SimpleDateFormat;
 14 import java.util.*;
 15 
 16 import static org.apache.poi.ss.usermodel.CellType.STRING;
 17 
 18 /**
 19  * Created by wangjianjun on 2017/5/8.
 20  */
 21 public class ExcelUtil<T> {
 22 
 23     Class<T> clazz;
 24 
 25     public ExcelUtil(){
 26 
 27     }
 28 
 29     public ExcelUtil(Class<T> clazz) {
 30         this.clazz = clazz;
 31     }
 32 
 33     public List<T> importExcel(String sheetName, HSSFWorkbook workbook) throws InspectionServiceException{
 34 
 35         int maxCol = 0;
 36         List<T> list = new ArrayList<>();
 37         try {
 38 
 39             HSSFSheet sheet = workbook.getSheet(sheetName);
 40 
 41             if (sheet == null){
 42 //                sheet = workbook.getSheetAt(0);
 43 //                if (!sheet.getSheetName().equals(sheetName))
 44 //                    return null;
 45                 throw new InspectionServiceException("未找到对应的sheetName:"+sheetName);
 46             }
 47 
 48             int rows = sheet.getPhysicalNumberOfRows();
 49 
 50             if (rows > 0){
 51                 List<Field> allFields = getMappedField(clazz,null);
 52                 Map<Integer,Field> fieldMap = new HashMap<>();
 53                 for (Field field:allFields){
 54                     if (field.isAnnotationPresent(ExcelVOAttribute.class)){
 55                         ExcelVOAttribute attr = field.getAnnotation(ExcelVOAttribute.class);
 56                         int col = getExcelCol(attr.column());
 57                         maxCol = Math.max(col,maxCol);
 58                         fieldMap.put(col,field);
 59                     }
 60                 }
 61 
 62                 for (int i=1;i<rows;i++){
 63                     HSSFRow row = sheet.getRow(i);
 64                     int cellNum = maxCol;
 65                     T entity = null;
 66                     for (int j=0;j<=cellNum;j++){
 67                         HSSFCell cell = row.getCell(j);
 68                         if (cell == null){
 69                             continue;
 70                         }
 71 
 72                         CellType cellType = cell.getCellTypeEnum();
 73                         String value;
 74                         switch (cellType){
 75                             case NUMERIC:
 76                                 cell.setCellType(STRING);
 77                                 value = String.valueOf(cell.getStringCellValue());
 78                                 break;
 79                             case BOOLEAN:
 80                                 value = String.valueOf(cell.getBooleanCellValue());
 81                                 break;
 82                             default:
 83                                 value = cell.getStringCellValue();
 84                                 break;
 85                         }
 86 
 87                         if (value == null || "".equals(value))
 88                             continue;
 89 
 90                         entity = (entity == null ? clazz.newInstance():entity);
 91                         Field field = fieldMap.get(j);
 92                         if (field == null)
 93                             continue;
 94 
 95                         Class fieldType = field.getType();
 96                         if (String.class == fieldType)
 97                             field.set(entity,String.valueOf(value));
 98                         else if ((Integer.TYPE == fieldType)
 99                                 || (Integer.class == fieldType)) {
100                             field.set(entity, Integer.parseInt(value));
101                         } else if ((Long.TYPE == fieldType)
102                                 || (Long.class == fieldType)) {
103                             field.set(entity, Long.valueOf(value));
104                         } else if ((Float.TYPE == fieldType)
105                                 || (Float.class == fieldType)) {
106                             field.set(entity, Float.valueOf(value));
107                         } else if ((Short.TYPE == fieldType)
108                                 || (Short.class == fieldType)) {
109                             field.set(entity, Short.valueOf(value));
110                         } else if ((Double.TYPE == fieldType)
111                                 || (Double.class == fieldType)) {
112                             field.set(entity, Double.valueOf(value));
113                         } else if (Character.TYPE == fieldType) {
114                             if ((value != null) && (value.length() > 0)) {
115                                 field.set(entity, Character
116                                         .valueOf(value.charAt(0)));
117                             }
118                         }else if (Boolean.TYPE == fieldType){
119                             field.set(entity,Boolean.valueOf(value));
120                         }
121                     }
122                     if (entity != null)
123                         list.add(entity);
124                 }
125             }
126 
127         } catch (InstantiationException e) {
128             throw new  InspectionServiceException(e.getMessage());
129         } catch (IllegalAccessException e) {
130             throw new  InspectionServiceException(e.getMessage());
131         }
132 
133         return list;
134     }
135 
136     public void exportExcel(List<T> list,HSSFWorkbook workbook,String sheetName,int sheetIx) throws InspectionServiceException{
137 
138         genOneSheet(list,workbook);
139         workbook.setSheetName(sheetIx,sheetName);
140     }
141 
142     private void genOneSheet(List<T> list,HSSFWorkbook workbook) throws InspectionServiceException{
143 
144         List<Field> fields = getMappedField(clazz,null);
145         HSSFSheet sheet = workbook.createSheet();
146 
147         HSSFRow row;
148         HSSFCell cell;
149         row = sheet.createRow(0);
150         for (int j=0;j<fields.size();j++){
151             Field field = fields.get(j);
152             ExcelVOAttribute attr = field.getAnnotation(ExcelVOAttribute.class);
153             int col = getExcelCol(attr.column());
154             cell = row.createCell(col);
155             cell.setCellType(CellType.STRING);
156             cell.setCellValue(attr.name());
157         }
158 
159         int startNo = 0;
160         int endNo = list.size();
161         for (int j=startNo;j<endNo;j++){
162             row = sheet.createRow(j+1-startNo);
163             T vo = list.get(j);
164             for (int k=0;k<fields.size();k++){
165                 Field field = fields.get(k);
166                 ExcelVOAttribute attr = field.getAnnotation(ExcelVOAttribute.class);
167                 try {
168                     if (attr.isExport()){
169                         cell = row.createCell(getExcelCol(attr.column()));
170                         cell.setCellType(CellType.STRING);
171                         cell.setCellValue(field.get(vo)==null?"":String.valueOf(field.get(vo)));
172                     }
173                 } catch (IllegalAccessException e) {
174                     throw new  InspectionServiceException(e.getMessage());
175                 }
176             }
177         }
178     }
179 
180     /**
181      * 得到实体类所有通过注解映射了数据表的字段
182      * @param clazz
183      * @param fields
184      * @return
185      */
186     private List<Field> getMappedField(Class clazz,List<Field> fields){
187 
188         if (fields == null){
189             fields =  new ArrayList<>();
190         }
191 
192         Field[] allFields = clazz.getDeclaredFields();
193         for (Field field:allFields){
194             if (field.isAnnotationPresent(ExcelVOAttribute.class)){
195                 fields.add(field);
196             }
197         }
198 
199         if (clazz.getSuperclass()!=null && !clazz.getSuperclass().equals(Object.class)){
200             getMappedField(clazz.getSuperclass(),fields);
201         }
202 
203         return fields;
204     }
205 
206     /**
207      * 将EXCEL中A,B,C,D,E列映射成0,1,2,3
208      *
209      * @param col
210      */
211     public static int getExcelCol(String col) {
212         col = col.toUpperCase();
213         // 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
214         int count = -1;
215         char[] cs = col.toCharArray();
216         for (int i = 0; i < cs.length; i++) {
217             count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
218         }
219         return count;
220     }
221 
222     public void downLoad(String filePath, HttpServletResponse response,
223                          boolean isOnLine) throws Exception {
224         File f = new File(filePath);
225         /*
226          * if (!f.exists()) { response.sendError(404, "File not found!");
227          * return; }
228          */
229         BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
230         byte[] buf = new byte[1024];
231         int len = 0;
232         response.reset(); // 非常重要
233         // 在线打开方式
234         if (isOnLine) {
235             URL u = new URL(filePath);
236             response.setContentType(u.openConnection().getContentType());
237             response.setHeader("Content-Disposition", "inline; filename="
238                     + toUTF8(f.getName()));
239             // 文件名应该编码成UTF-8
240         }
241         // 纯下载方式
242         else {
243             response.setContentType("application/x-msdownload");
244             response.setHeader("Content-Disposition", "attachment; filename="
245                     + toUTF8(f.getName()));
246         }
247         OutputStream out = response.getOutputStream();
248         while ((len = br.read(buf)) > 0)
249             out.write(buf, 0, len);
250         out.flush();
251         br.close();
252         out.close();
253     }
254 
255     // UTF-8编码
256     public String toUTF8(String s) {
257         StringBuffer sb = new StringBuffer();
258         for (int i = 0; i < s.length(); i++) {
259             char c = s.charAt(i);
260             if (c >= 0 && c <= 255) {
261                 sb.append(c);
262             } else {
263                 byte[] b;
264                 try {
265                     b = Character.toString(c).getBytes("utf-8");
266                 } catch (Exception ex) {
267                     System.out.println(ex);
268                     b = new byte[0];
269                 }
270                 for (int j = 0; j < b.length; j++) {
271                     int k = b[j];
272                     if (k < 0)
273                         k += 256;
274                     sb.append("%" + Integer.toHexString(k).toUpperCase());
275                 }
276             }
277         }
278         return sb.toString();
279     }
280 
281     public static String genUploadPathName(HttpServletRequest request,String title){
282         String unloadPath = request.getSession().getServletContext().getRealPath("/") + "\\download\\"
283                 + "excel" + "\\";
284 
285         // 自动生成日期
286         SimpleDateFormat autoDate = new SimpleDateFormat(
287                 "yyyyMMddHHmmssSSS");
288         // excel名为:当前名+日期时间
289         //title += autoDate.format(new Date());
290         if (title==null || title.equals(""))
291             title = "inspectionExport";
292         File dirFile = new File(unloadPath);
293         // 如果dir对应的文件不存在,或者不是一个目录,则退出
294         if (!dirFile.exists() || !dirFile.isDirectory()) {
295             dirFile.mkdirs();
296         }
297 
298         return unloadPath+title + ".xls";
299     }
300 }

4、使用

  1 @RequestMapping("/upload.action")
  2     public ModelAndView uploadAndParse(HttpServletRequest request, HttpServletResponse response){
  3 
  4         ModelAndView mv;
  5         String importMsg = "importSuc";
  6 
  7         try {
  8             FileItemFactory factory = new DiskFileItemFactory();
  9             ServletFileUpload upload = new ServletFileUpload(factory);
 10             upload.setHeaderEncoding(request.getCharacterEncoding());
 11 
 12             List<FileItem> list = upload.parseRequest(request);
 13             for (int i = 0; i < list.size(); i++) {
 14                 FileItem item = list.get(i);
 15                 if (item.getName().endsWith(".xls")||item.getName().endsWith(".xlsx")) {
 16                     // 说明是文件,不过这里最好限制一下
 17                     List<CheckPlan> planList = importXlsx(item.getInputStream());
 18 
 19                     //对于已经插入数据库的任务进行提交
 20                     if (planList !=null && planList.size()>0) {
 21                         allInsertPlanCommit(planList);
 22                     }
 23                 } else {
 24                     // 说明文件格式不符合要求
 25                     importMsg = "importStyleError_c";
 26                 }
 27             }
 28         }catch (Exception e){
 29             logger.error("uploadAndParse:" + e.getMessage(), e);
 30             importMsg = "importError";
 31         }finally {
 32             mv = queryAllCheckPlan(null,new QueryCheckPlanCond());
 33             mv.addObject("retMsg",importMsg);
 34         }
 35 
 36         return mv;
 37     }
 38 
 39     @RequestMapping("/export.action")
 40     public void exportAndParse(HttpServletRequest request, HttpServletResponse response){
 41 
 42         PagingResult<CheckPlan> planPagingResult;
 43         PagingResult<CheckDef> checkDefPagingResult;
 44         PagingResult<DiffHandlerDef> diffHandlerDefPagingResult;
 45         List<EXDiffHandlerDef> exDiffHandlerDefs = null;
 46         List<EXCheckPlan> exCheckPlanList = null;
 47         List<EXCheckDef> exCheckDefList;
 48         List<EXCheckDefRule> exCheckDefRuleList;
 49         List<CheckRule> ruleList;
 50         QueryCheckCond defCond = new QueryCheckCond();
 51         QueryCheckPlanCond planCond = new QueryCheckPlanCond();
 52         QueryDiffHandlerCond diffCond = new QueryDiffHandlerCond();
 53         defCond.setPageSize(0);
 54         defCond.setFetchCheckRules(true);
 55         planCond.setPageSize(0);
 56         diffCond.setPageSize(0);
 57         try {
 58             planPagingResult = planService.queryCheckPlans(planCond);
 59             checkDefPagingResult = checkService.queryCheckDef(defCond);
 60             diffHandlerDefPagingResult = handlerService.queryDiffHandlerDef(diffCond);
 61 
 62             if (planPagingResult !=null && planPagingResult.getRecords() != null){
 63                 List<CheckPlan> checkPlanList = planPagingResult.getRecords();
 64                 exCheckPlanList = write2EXCheckPlans(checkPlanList);
 65             }
 66 
 67             if (diffHandlerDefPagingResult != null && diffHandlerDefPagingResult.getRecords() != null){
 68                 List<DiffHandlerDef> diffHandlerDefList = diffHandlerDefPagingResult.getRecords();
 69                 exDiffHandlerDefs = write2ExDiffHandlerDef(diffHandlerDefList);
 70             }
 71 
 72             if (checkDefPagingResult != null && checkDefPagingResult.getRecords() != null) {
 73                 List<CheckDef> checkDefList = checkDefPagingResult.getRecords();
 74                 List<EXCheckDefRule> exCheckDefRules = new ArrayList<>();
 75                 List<EXCheckDefRule> exCheckDefRulesTemp;
 76                 for (CheckDef checkDef : checkDefList) {
 77                     ruleList = checkDef.getRules();
 78                     if (ruleList!=null && ruleList.size()>0) {
 79                         exCheckDefRulesTemp = write2EXDefRules(ruleList,checkDef.getCheckName());
 80                         exCheckDefRules.addAll(exCheckDefRulesTemp);
 81                     }
 82                 }
 83 
 84                 exCheckDefRuleList = exCheckDefRules;
 85                 exCheckDefList = write2EXCheckDefs(checkDefList);
 86                 String filePathName = ExcelUtil.genUploadPathName(request,"计划定义规则");
 87 
 88                 // 创建excel文件
 89                 FileOutputStream fos = null;
 90                 try {
 91                     fos = new FileOutputStream(new File(filePathName));
 92                 } catch (FileNotFoundException e) {
 93                     e.printStackTrace();
 94                 }
 95                 HSSFWorkbook workbook = new HSSFWorkbook();
 96                 ExcelUtil<EXDiffHandlerDef> diffExcelUtil = new ExcelUtil<>(EXDiffHandlerDef.class);
 97                 diffExcelUtil.exportExcel(exDiffHandlerDefs, workbook, "diff_handler", 0);
 98 
 99                 ExcelUtil<EXCheckDefRule> ruleExcelUtil = new ExcelUtil<>(EXCheckDefRule.class);
100                 ruleExcelUtil.exportExcel(exCheckDefRuleList, workbook, "check_rule", 1);
101 
102                 ExcelUtil<EXCheckDef> checkDefExcelUtil = new ExcelUtil<>(EXCheckDef.class);
103                 checkDefExcelUtil.exportExcel(exCheckDefList, workbook, "check_def", 2);
104 
105                 ExcelUtil<EXCheckPlan> planExcelUtil = new ExcelUtil<>(EXCheckPlan.class);
106                 planExcelUtil.exportExcel(exCheckPlanList, workbook, "check_plan", 3);
107 
108                 workbook.write(fos);
109                 workbook.close();
110                 ruleExcelUtil.downLoad(filePathName,response,false);
111             }
112         } catch (InspectionServiceException e) {
113             logger.error("exportAndParse:" + e.getMessage(), e);
114         } catch (Exception e) {
115             logger.error("exportAndParse:" + e.getMessage(), e);
116         }
117     }
118 public List<CheckPlan> importXlsx(InputStream is) throws InspectionServiceException,IOException {
119 
120         try {
121             HSSFWorkbook workbook = new HSSFWorkbook(is);
122             if (workbook == null)
123                 return null;
124 
125             ExcelUtil diffExcelUtil1 = new ExcelUtil<>(EXDiffHandlerDef.class);
126             List<EXDiffHandlerDef> diffs = diffExcelUtil1.importExcel("diff_handler",workbook);
127 
128             ExcelUtil ruleExcelUtil1 = new ExcelUtil<>(EXCheckDefRule.class);
129             List<EXCheckDefRule> rules = ruleExcelUtil1.importExcel("check_rule",workbook);
130 
131             ExcelUtil  defExcelUtil = new ExcelUtil(EXCheckDef.class);
132             List<EXCheckDef> defs = defExcelUtil.importExcel("check_def",workbook);
133 
134             ExcelUtil planExcelUtil = new ExcelUtil(EXCheckPlan.class);
135             List<EXCheckPlan> plans = planExcelUtil.importExcel("check_plan",workbook);
136 
137             return createDbDataAndInsert(diffs,rules,defs,plans);
138         }catch (InspectionServiceException e) {
139             throw new  InspectionServiceException(e.getMessage());
140         }
141     }

 

posted @ 2017-05-12 15:23  风吹弦断  阅读(1083)  评论(0编辑  收藏  举报