在SSM下使用POI实现Excel表的导入/导出

对于批量数据的操作,在项目中引进Excel的导入和导出功能是个不错的选择。对于Excel表的结构,简单理解我觉得大体可以把它分成三部分(SheetCellRow),可以把这三部分理解为。因此,我们想要获取到某一个单元的内容,可以通过获取该单元所在的页数和对应所在的行和列从而定位到该单位,继而便可执行操作从而获取其中的内容。Java使用POI实现对excel的导入和导出也是相似的思路。

环境,导入POI对应的包

spring+springMVC+Mybatis

[html]  view plain  copy
  1. <dependency>  
  2. <groupId>org.apache.poi</groupId>  
  3. <artifactId>poi-ooxml-schemas</artifactId>  
  4. <version>3.14-beta1</version>  
  5. </dependency>  

创建一个ExcelBean实现数据的封装

[java]  view plain  copy
  1. public class ExcelBean implements  java.io.Serializable{  
  2.     private String headTextName; //列头(标题)名  
  3.     private String propertyName; //对应字段名  
  4.     private Integer cols; //合并单元格数  
  5.     private XSSFCellStyle cellStyle;  
  6.     public ExcelBean(){  
  7.     }  
  8.     public ExcelBean(String headTextName, String propertyName){  
  9.         this.headTextName = headTextName;  
  10.         this.propertyName = propertyName;  
  11.     }  
  12.     public ExcelBean(String headTextName, String propertyName, Integer cols) {  
  13.         super();  
  14.         this.headTextName = headTextName;  
  15.         this.propertyName = propertyName;  
  16.         this.cols = cols;  
  17.     }  
  18.     /* 省略了get和set方法 */  
  19. }  

创建一个Excel表数据导入和导出的工具类ExcelUtil

[java]  view plain  copy
  1. public class ExcelUtil {  
  2.     private final static String excel2003L =".xls";    //2003- 版本的excel  
  3.     private final static String excel2007U =".xlsx";   //2007+ 版本的excel  
  4.     /** 
  5.      * Excel导入 
  6.      */  
  7.     public static  List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{  
  8.         List<List<Object>> list = null;  
  9.         //创建Excel工作薄  
  10.         Workbook work = getWorkbook(in,fileName);  
  11.         if(null == work){  
  12.             throw new Exception("创建Excel工作薄为空!");  
  13.         }  
  14.         Sheet sheet = null;  
  15.         Row row = null;  
  16.         Cell cell = null;  
  17.         list = new ArrayList<List<Object>>();  
  18.         //遍历Excel中所有的sheet  
  19.         for (int i = 0; i < work.getNumberOfSheets(); i++) {  
  20.             sheet = work.getSheetAt(i);  
  21.             if(sheet==null){continue;}  
  22.             //遍历当前sheet中的所有行  
  23.             //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部  
  24.             for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {  
  25.                 //读取一行  
  26.                 row = sheet.getRow(j);  
  27.                 //去掉空行和表头  
  28.                 if(row==null||row.getFirstCellNum()==j){continue;}  
  29.                 //遍历所有的列  
  30.                 List<Object> li = new ArrayList<Object>();  
  31.                 for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
  32.                     cell = row.getCell(y);  
  33.                     li.add(getCellValue(cell));  
  34.                 }  
  35.                 list.add(li);  
  36.             }  
  37.         }  
  38.         return list;  
  39.     }  
  40.     /** 
  41.      * 描述:根据文件后缀,自适应上传文件的版本 
  42.      */  
  43.     public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
  44.         Workbook wb = null;  
  45.         String fileType = fileName.substring(fileName.lastIndexOf("."));  
  46.         if(excel2003L.equals(fileType)){  
  47.             wb = new HSSFWorkbook(inStr);  //2003-  
  48.         }else if(excel2007U.equals(fileType)){  
  49.             wb = new XSSFWorkbook(inStr);  //2007+  
  50.         }else{  
  51.             throw new Exception("解析的文件格式有误!");  
  52.         }  
  53.         return wb;  
  54.     }  
  55.     /** 
  56.      * 描述:对表格中数值进行格式化 
  57.      */  
  58.     public static  Object getCellValue(Cell cell){  
  59.         Object value = null;  
  60.         DecimalFormat df = new DecimalFormat("0");  //格式化字符类型的数字  
  61.         SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化  
  62.         DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字  
  63.         switch (cell.getCellType()) {  
  64.             case Cell.CELL_TYPE_STRING:  
  65.                 value = cell.getRichStringCellValue().getString();  
  66.                 break;  
  67.             case Cell.CELL_TYPE_NUMERIC:  
  68.                 if("General".equals(cell.getCellStyle().getDataFormatString())){  
  69.                     value = df.format(cell.getNumericCellValue());  
  70.                 }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){  
  71.                     value = sdf.format(cell.getDateCellValue());  
  72.                 }else{  
  73.                     value = df2.format(cell.getNumericCellValue());  
  74.                 }  
  75.                 break;  
  76.             case Cell.CELL_TYPE_BOOLEAN:  
  77.                 value = cell.getBooleanCellValue();  
  78.                 break;  
  79.             case Cell.CELL_TYPE_BLANK:  
  80.                 value = "";  
  81.                 break;  
  82.             default:  
  83.                 break;  
  84.         }  
  85.         return value;  
  86.     }  
  87.     /** 
  88.      * 导入Excel表结束 
  89.      * 导出Excel表开始 
  90.      * @param sheetName 工作簿名称 
  91.      * @param clazz  数据源model类型 
  92.      * @param objs   excel标题列以及对应model字段名 
  93.      * @param map  标题列行数以及cell字体样式 
  94.      */  
  95.     public static XSSFWorkbook createExcelFile(Class clazz, List objs, Map<Integer, List<ExcelBean>> map, String sheetName) throws   
  96. IllegalArgumentException,IllegalAccessException,InvocationTargetException,  
  97. ClassNotFoundException, IntrospectionException, ParseException {  
  98.         // 创建新的Excel工作簿  
  99.         XSSFWorkbook workbook = new XSSFWorkbook();  
  100.         // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称  
  101.         XSSFSheet sheet = workbook.createSheet(sheetName);  
  102.         // 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;  
  103.         createFont(workbook); //字体样式  
  104.         createTableHeader(sheet, map); //创建标题(头)  
  105.         createTableRows(sheet, map, objs, clazz); //创建内容  
  106.         return workbook;  
  107.     }  
  108.     private static XSSFCellStyle fontStyle;  
  109.     private static XSSFCellStyle fontStyle2;  
  110.     public static void createFont(XSSFWorkbook workbook) {  
  111.         // 表头  
  112.         fontStyle = workbook.createCellStyle();  
  113.         XSSFFont font1 = workbook.createFont();  
  114.         font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);  
  115.         font1.setFontName("黑体");  
  116.         font1.setFontHeightInPoints((short14);// 设置字体大小  
  117.         fontStyle.setFont(font1);  
  118.         fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框  
  119.         fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框  
  120.         fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框  
  121.         fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框  
  122.         fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中  
  123.         // 内容  
  124.         fontStyle2=workbook.createCellStyle();  
  125.         XSSFFont font2 = workbook.createFont();  
  126.         font2.setFontName("宋体");  
  127.         font2.setFontHeightInPoints((short10);// 设置字体大小  
  128.         fontStyle2.setFont(font2);  
  129.         fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框  
  130.         fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框  
  131.         fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框  
  132.         fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框  
  133.         fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中  
  134.     }  
  135.     /** 
  136.      * 根据ExcelMapping 生成列头(多行列头) 
  137.      * 
  138.      * @param sheet 工作簿 
  139.      * @param map 每行每个单元格对应的列头信息 
  140.      */  
  141.     public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {  
  142.         int startIndex=0;//cell起始位置  
  143.         int endIndex=0;//cell终止位置  
  144.         for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {  
  145.             XSSFRow row = sheet.createRow(entry.getKey());  
  146.             List<ExcelBean> excels = entry.getValue();  
  147.             for (int x = 0; x < excels.size(); x++) {  
  148.                 //合并单元格  
  149.                 if(excels.get(x).getCols()>1){  
  150.                     if(x==0){  
  151.                         endIndex+=excels.get(x).getCols()-1;  
  152.                         CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);  
  153.                         sheet.addMergedRegion(range);  
  154.                         startIndex+=excels.get(x).getCols();  
  155.                     }else{  
  156.                         endIndex+=excels.get(x).getCols();  
  157.                         CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);  
  158.                         sheet.addMergedRegion(range);  
  159.                         startIndex+=excels.get(x).getCols();  
  160.                     }  
  161.                     XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());  
  162.                     cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容  
  163.                     if (excels.get(x).getCellStyle() != null) {  
  164.                         cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式  
  165.                     }  
  166.                     cell.setCellStyle(fontStyle);  
  167.                 }else{  
  168.                     XSSFCell cell = row.createCell(x);  
  169.                     cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容  
  170.                     if (excels.get(x).getCellStyle() != null) {  
  171.                         cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式  
  172.                     }  
  173.                     cell.setCellStyle(fontStyle);  
  174.                 }  
  175.             }  
  176.         }  
  177.     }  
  178.     public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz)  
  179.             throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,  
  180.             ClassNotFoundException, ParseException {  
  181.         int rowindex = map.size();  
  182.         int maxKey = 0;  
  183.         List<ExcelBean> ems = new ArrayList<>();  
  184.         for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {  
  185.             if (entry.getKey() > maxKey) {  
  186.                 maxKey = entry.getKey();  
  187.             }  
  188.         }  
  189.         ems = map.get(maxKey);  
  190.         List<Integer> widths = new ArrayList<Integer>(ems.size());  
  191.         for (Object obj : objs) {  
  192.             XSSFRow row = sheet.createRow(rowindex);  
  193.             for (int i = 0; i < ems.size(); i++) {  
  194.                 ExcelBean em = (ExcelBean) ems.get(i);  
  195.                 // 获得get方法  
  196.                 PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);  
  197.                 Method getMethod = pd.getReadMethod();  
  198.                 Object rtn = getMethod.invoke(obj);  
  199.                 String value = "";  
  200.                 // 如果是日期类型进行转换  
  201.                 if (rtn != null) {  
  202.                     if (rtn instanceof Date) {  
  203.                         value = dateUtil.dateToString((Date)rtn);  
  204.                     } else if(rtn instanceof BigDecimal){  
  205.                         NumberFormat nf = new DecimalFormat("#,##0.00");  
  206.                         value=nf.format((BigDecimal)rtn).toString();  
  207.                     } else if((rtn instanceof Integer) && (Integer.valueOf(rtn.toString())<0 )){  
  208.                         value="--";  
  209.                     }else {  
  210.                         value = rtn.toString();  
  211.                     }  
  212.                 }  
  213.                 XSSFCell cell = row.createCell(i);  
  214.                 cell.setCellValue(value);  
  215.                 cell.setCellType(XSSFCell.CELL_TYPE_STRING);  
  216.                 cell.setCellStyle(fontStyle2);  
  217.                 // 获得最大列宽  
  218.                 int width = value.getBytes().length * 300;  
  219.                 // 还未设置,设置当前  
  220.                 if (widths.size() <= i) {  
  221.                     widths.add(width);  
  222.                     continue;  
  223.                 }  
  224.                 // 比原来大,更新数据  
  225.                 if (width > widths.get(i)) {  
  226.                     widths.set(i, width);  
  227.                 }  
  228.             }  
  229.             rowindex++;  
  230.         }  
  231.         // 设置列宽  
  232.         for (int index = 0; index < widths.size(); index++) {  
  233.             Integer width = widths.get(index);  
  234.             width = width < 2500 ? 2500 : width + 300;  
  235.             width = width > 10000 ? 10000 + 300 : width + 300;  
  236.             sheet.setColumnWidth(index, width);  
  237.         }  
  238.     }  
  239. }  

Excel表导入Controller端实现

[java]  view plain  copy
  1. @RequestMapping("/import")  
  2. public String impotr(HttpServletRequest request, Model model) throws Exception {  
  3.      int adminId = 1;  
  4.      //获取上传的文件  
  5.      MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;  
  6.      MultipartFile file = multipart.getFile("upfile");  
  7.      String month = request.getParameter("month");  
  8.      InputStream in = file.getInputStream();  
  9.      //数据导入  
  10.      salaryService.importExcelInfo(in,file,month,adminId);  
  11.      in.close();  
  12.      return "redirect:/salary/index.html";  
  13. }  

Service层,这里是Service接口importExcellnfo的实现方法,调用了ExcelUtil里的方法

[java]  view plain  copy
  1. public void importExcelInfo(InputStream in, MultipartFile file, String salaryDate,Integer adminId) throws Exception{  
  2.     List<List<Object>> listob = ExcelUtil.getBankListByExcel(in,file.getOriginalFilename());  
  3.     List<Salarymanage> salaryList = new ArrayList<Salarymanage>();  
  4.     //遍历listob数据,把数据放到List中  
  5.     for (int i = 0; i < listob.size(); i++) {  
  6.         List<Object> ob = listob.get(i);  
  7.         Salarymanage salarymanage = new Salarymanage();  
  8.         //设置编号  
  9.         salarymanage.setSerial(SerialUtil.salarySerial());  
  10.         //通过遍历实现把每一列封装成一个model中,再把所有的model用List集合装载  
  11.         salarymanage.setAdminId(adminId);  
  12.         salarymanage.setCompany(String.valueOf(ob.get(1)));  
  13.         salarymanage.setNumber(String.valueOf(ob.get(2)));  
  14.         salarymanage.setName(String.valueOf(ob.get(3)));  
  15.         salarymanage.setSex(String.valueOf(ob.get(4)));  
  16.         salarymanage.setCardName(String.valueOf(ob.get(5)));  
  17.         salarymanage.setBankCard(String.valueOf(ob.get(6)));  
  18.         salarymanage.setBank(String.valueOf(ob.get(7)));  
  19.         //object类型转Double类型  
  20.         salarymanage.setMoney(Double.parseDouble(ob.get(8).toString()));  
  21.         salarymanage.setRemark(String.valueOf(ob.get(9)));  
  22.         salarymanage.setSalaryDate(salaryDate);  
  23.         salaryList.add(salarymanage);  
  24.     }  
  25.     //批量插入  
  26.     salarymanageDao.insertInfoBatch(salaryList);  
  27. }  

接着是mapper.xml,用<foreach></foreach>实现数据的批量插入

[java]  view plain  copy
  1. <insert id="insertInfoBatch" parameterType="java.util.List">  
  2.     insert into salarymanage (admin_id, serial,company, number, name,sex, card_name, bank_card,  
  3.       bank, money, remark,salary_date)  
  4.     values  
  5.     <foreach collection="list" item="item" index="index" separator=",">  
  6.       (#{item.adminId}, #{item.serial}, #{item.company},#{item.number}, #{item.name},  
  7.       #{item.sex}, #{item.cardName},#{item.bankCard}, #{item.bank},  
  8.       #{item.money}, #{item.remark}, #{item.salaryDate})  
  9.     </foreach>  
  10. </insert>  

到这里,excel表的导入功能便完成了。这里补充一下mybatis里<foreach>里面的部分参数,collection是传入参数的类型,如果传入参数是List,这里便是list,如果是一个数组,便是array,separator指的是数据之间用“,”隔开,这也是借鉴了mysql插入多条数据的写法,具体的执行效率还没做多的探讨,我试过导入30条数据,效率还是可以接受的,如果有人有更好的写法,欢迎留言交流。

Excel导出Controller端实现

[java]  view plain  copy
  1. @RequestMapping("/export")  
  2. public @ResponseBody void export(HttpServletRequest request, HttpServletResponse response) throwsClassNotFoundException, IntrospectionException, IllegalAccessException, ParseException, InvocationTargetException {  
  3.     String salaryDate = request.getParameter("salaryDate");  
  4.     if(salaryDate!=""){  
  5.         response.reset(); //清除buffer缓存  
  6.         Map<String,Object> map=new HashMap<String,Object>();  
  7.         // 指定下载的文件名  
  8.         response.setHeader("Content-Disposition""attachment;filename="+salaryDate+".xlsx");  
  9.         response.setContentType("application/vnd.ms-excel;charset=UTF-8");  
  10.         response.setHeader("Pragma""no-cache");  
  11.         response.setHeader("Cache-Control""no-cache");  
  12.         response.setDateHeader("Expires"0);  
  13.         XSSFWorkbook workbook=null;  
  14.         //导出Excel对象  
  15.         workbook = salaryService.exportExcelInfo(salaryDate);  
  16.         OutputStream output;  
  17.         try {  
  18.             output = response.getOutputStream();  
  19.             BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);  
  20.             bufferedOutPut.flush();  
  21.             workbook.write(bufferedOutPut);  
  22.             bufferedOutPut.close();  
  23.         } catch (IOException e) {  
  24.             e.printStackTrace();  
  25.         }  
  26.     }  
  27. }  

Service层,这里也是只写接口exportExcelInfo的实现方法

[java]  view plain  copy
  1. public XSSFWorkbook exportExcelInfo(String salaryDate) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException {  
  2.     //根据条件查询数据,把数据装载到一个list中  
  3.     List<Salarymanage> list = salarymanageDao.selectApartInfo(salaryDate);  
  4.     for(int i=0;i<list.size();i++){  
  5.         //查询财务名字  
  6.         int adminId = list.get(i).getAdminId();  
  7.         String adminName = salarymanageDao.selectAdminNameById(adminId);  
  8.         list.get(i).setAdminName(adminName);  
  9.         list.get(i).setId(i+1);  
  10.     }  
  11.     List<ExcelBean> excel=new ArrayList<>();  
  12.     Map<Integer,List<ExcelBean>> map=new LinkedHashMap<>();  
  13.     XSSFWorkbook xssfWorkbook=null;  
  14.     //设置标题栏  
  15.     excel.add(new ExcelBean("序号","id",0));  
  16.     excel.add(new ExcelBean("厂名","company",0));  
  17.     excel.add(new ExcelBean("工号","number",0));  
  18.     excel.add(new ExcelBean("姓名","name",0));  
  19.     excel.add(new ExcelBean("性别","sex",0));  
  20.     excel.add(new ExcelBean("开户名","cardName",0));  
  21.     excel.add(new ExcelBean("银行卡号","bankCard",0));  
  22.     excel.add(new ExcelBean("开户行","bank",0));  
  23.     excel.add(new ExcelBean("金额","money",0));  
  24.     excel.add(new ExcelBean("备注","remark",0));  
  25.     map.put(0, excel);  
  26.     String sheetName = salaryDate + "月份收入";  
  27.     //调用ExcelUtil的方法  
  28.     xssfWorkbook = ExcelUtil.createExcelFile(Salarymanage.class, list, map, sheetName);  
  29.     return xssfWorkbook;  
  30. }  

这里不写出导出功能的mapper.xml实现语句了,具体实现也就是数据查询,把查询出来的数据转载到一个List中。

以上便是在SSM下使用POI实现excel表的导入和导出的整体思路,主要的导入和导出的核心方法都封装在Excel的工具类中,但面对具体的表格需要具体分析循环的开始,以便能够去除表头或者标题栏。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值