SpringMvc+POI 处理Excel的导入操作

本文介绍如何使用Apache POI库处理Excel文件的导入导出操作,包括不同版本Excel文件的支持、数据格式化及表格样式的设置等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

说明

  POI可以对2003-和2007+版本的Excel文件做导入导出操作,本章只简单介绍对Excel文件的导入操作。

       Excel文件的上传处理处理请求,依然使用SpringMvc中的MultipartRequest方式处理。

       前端JSP中使用传统form表单提交方式和Juery.form.js插件提供的异步表单请求方式,分别对这两种方式进行介绍。


环境

JDK7+ Tomcat7.x + Spring4.1.8


说明

ImportExcelUtil.java:Excel解析工具类

UploadExcelControl.java :处理来自页面的请求控制器

InfoVo.java :将Excel转换为对象存储

main.jsp:前端访问页

........


ImportExcelUtil.java(Excel解析工具类)

[java]  view plain  copy
  1. package com.poiexcel.util;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.text.DecimalFormat;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  11. import org.apache.poi.ss.usermodel.Cell;  
  12. import org.apache.poi.ss.usermodel.Row;  
  13. import org.apache.poi.ss.usermodel.Sheet;  
  14. import org.apache.poi.ss.usermodel.Workbook;  
  15. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  16.   
  17.   
  18. public class ImportExcelUtil {  
  19.       
  20.     private final static String excel2003L =".xls";    //2003- 版本的excel  
  21.     private final static String excel2007U =".xlsx";   //2007+ 版本的excel  
  22.       
  23.     /** 
  24.      * 描述:获取IO流中的数据,组装成List<List<Object>>对象 
  25.      * @param in,fileName 
  26.      * @return 
  27.      * @throws IOException  
  28.      */  
  29.     public  List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{  
  30.         List<List<Object>> list = null;  
  31.           
  32.         //创建Excel工作薄  
  33.         Workbook work = this.getWorkbook(in,fileName);  
  34.         if(null == work){  
  35.             throw new Exception("创建Excel工作薄为空!");  
  36.         }  
  37.         Sheet sheet = null;  
  38.         Row row = null;  
  39.         Cell cell = null;  
  40.           
  41.         list = new ArrayList<List<Object>>();  
  42.         //遍历Excel中所有的sheet  
  43.         for (int i = 0; i < work.getNumberOfSheets(); i++) {  
  44.             sheet = work.getSheetAt(i);  
  45.             if(sheet==null){continue;}  
  46.               
  47.             //遍历当前sheet中的所有行  
  48.             for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {  
  49.                 row = sheet.getRow(j);  
  50.                 if(row==null||row.getFirstCellNum()==j){continue;}  
  51.                   
  52.                 //遍历所有的列  
  53.                 List<Object> li = new ArrayList<Object>();  
  54.                 for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {  
  55.                     cell = row.getCell(y);  
  56.                     li.add(this.getCellValue(cell));  
  57.                 }  
  58.                 list.add(li);  
  59.             }  
  60.         }  
  61.         work.close();  
  62.         return list;  
  63.     }  
  64.       
  65.     /** 
  66.      * 描述:根据文件后缀,自适应上传文件的版本  
  67.      * @param inStr,fileName 
  68.      * @return 
  69.      * @throws Exception 
  70.      */  
  71.     public  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{  
  72.         Workbook wb = null;  
  73.         String fileType = fileName.substring(fileName.lastIndexOf("."));  
  74.         if(excel2003L.equals(fileType)){  
  75.             wb = new HSSFWorkbook(inStr);  //2003-  
  76.         }else if(excel2007U.equals(fileType)){  
  77.             wb = new XSSFWorkbook(inStr);  //2007+  
  78.         }else{  
  79.             throw new Exception("解析的文件格式有误!");  
  80.         }  
  81.         return wb;  
  82.     }  
  83.   
  84.     /** 
  85.      * 描述:对表格中数值进行格式化 
  86.      * @param cell 
  87.      * @return 
  88.      */  
  89.     public  Object getCellValue(Cell cell){  
  90.         Object value = null;  
  91.         DecimalFormat df = new DecimalFormat("0");  //格式化number String字符  
  92.         SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化  
  93.         DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字  
  94.           
  95.         switch (cell.getCellType()) {  
  96.         case Cell.CELL_TYPE_STRING:  
  97.             value = cell.getRichStringCellValue().getString();  
  98.             break;  
  99.         case Cell.CELL_TYPE_NUMERIC:  
  100.             if("General".equals(cell.getCellStyle().getDataFormatString())){  
  101.                 value = df.format(cell.getNumericCellValue());  
  102.             }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){  
  103.                 value = sdf.format(cell.getDateCellValue());  
  104.             }else{  
  105.                 value = df2.format(cell.getNumericCellValue());  
  106.             }  
  107.             break;  
  108.         case Cell.CELL_TYPE_BOOLEAN:  
  109.             value = cell.getBooleanCellValue();  
  110.             break;  
  111.         case Cell.CELL_TYPE_BLANK:  
  112.             value = "";  
  113.             break;  
  114.         default:  
  115.             break;  
  116.         }  
  117.         return value;  
  118.     }  
  119.       
  120.   
  121. }  



UploadExcelControl.java (Spring控制器)

[java]  view plain  copy
  1. package com.poiexcel.control;  
  2.   
  3. import java.io.InputStream;  
  4. import java.io.PrintWriter;  
  5. import java.util.List;  
  6.   
  7. import javax.servlet.http.HttpServletRequest;  
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.springframework.stereotype.Controller;  
  11. import org.springframework.web.bind.annotation.RequestMapping;  
  12. import org.springframework.web.bind.annotation.RequestMethod;  
  13. import org.springframework.web.bind.annotation.ResponseBody;  
  14. import org.springframework.web.multipart.MultipartFile;  
  15. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  16.   
  17. import com.poiexcel.util.ImportExcelUtil;  
  18. import com.poiexcel.vo.InfoVo;  
  19.   
  20. @Controller  
  21. @RequestMapping("/uploadExcel/*")    
  22. public class UploadExcelControl {  
  23.       
  24.     /**  
  25.      * 描述:通过传统方式form表单提交方式导入excel文件  
  26.      * @param request  
  27.      * @throws Exception  
  28.      */  
  29.     @RequestMapping(value="upload.do",method={RequestMethod.GET,RequestMethod.POST})  
  30.     public  String  uploadExcel(HttpServletRequest request) throws Exception {  
  31.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
  32.         System.out.println("通过传统方式form表单提交方式导入excel文件!");  
  33.           
  34.         InputStream in =null;  
  35.         List<List<Object>> listob = null;  
  36.         MultipartFile file = multipartRequest.getFile("upfile");  
  37.         if(file.isEmpty()){  
  38.             throw new Exception("文件不存在!");  
  39.         }  
  40.         in = file.getInputStream();  
  41.         listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
  42.         in.close();  
  43.           
  44.         //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出  
  45.         for (int i = 0; i < listob.size(); i++) {  
  46.             List<Object> lo = listob.get(i);  
  47.             InfoVo vo = new InfoVo();  
  48.             vo.setCode(String.valueOf(lo.get(0)));  
  49.             vo.setName(String.valueOf(lo.get(1)));  
  50.             vo.setDate(String.valueOf(lo.get(2)));  
  51.             vo.setMoney(String.valueOf(lo.get(3)));  
  52.               
  53.             System.out.println("打印信息-->机构:"+vo.getCode()+"  名称:"+vo.getName()+"   时间:"+vo.getDate()+"   资产:"+vo.getMoney());  
  54.         }  
  55.         return "result";  
  56.     }  
  57.       
  58.     /** 
  59.      * 描述:通过 jquery.form.js 插件提供的ajax方式上传文件 
  60.      * @param request 
  61.      * @param response 
  62.      * @throws Exception 
  63.      */  
  64.     @ResponseBody  
  65.     @RequestMapping(value="ajaxUpload.do",method={RequestMethod.GET,RequestMethod.POST})  
  66.     public  void  ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {  
  67.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;    
  68.           
  69.         System.out.println("通过 jquery.form.js 提供的ajax方式上传文件!");  
  70.           
  71.         InputStream in =null;  
  72.         List<List<Object>> listob = null;  
  73.         MultipartFile file = multipartRequest.getFile("upfile");  
  74.         if(file.isEmpty()){  
  75.             throw new Exception("文件不存在!");  
  76.         }  
  77.           
  78.         in = file.getInputStream();  
  79.         listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());  
  80.           
  81.         //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出  
  82.         for (int i = 0; i < listob.size(); i++) {  
  83.             List<Object> lo = listob.get(i);  
  84.             InfoVo vo = new InfoVo();  
  85.             vo.setCode(String.valueOf(lo.get(0)));  
  86.             vo.setName(String.valueOf(lo.get(1)));  
  87.             vo.setDate(String.valueOf(lo.get(2)));   
  88.             vo.setMoney(String.valueOf(lo.get(3)));  
  89.               
  90.             System.out.println("打印信息-->机构:"+vo.getCode()+"  名称:"+vo.getName()+"   时间:"+vo.getDate()+"   资产:"+vo.getMoney());  
  91.         }  
  92.           
  93.         PrintWriter out = null;  
  94.         response.setCharacterEncoding("utf-8");  //防止ajax接受到的中文信息乱码  
  95.         out = response.getWriter();  
  96.         out.print("文件导入成功!");  
  97.         out.flush();  
  98.         out.close();  
  99.     }  
  100.   
  101.   
  102. }  




InfoVo.java(保存Excel数据对应的对象)

[java]  view plain  copy
  1. package com.poiexcel.vo;  
  2.   
  3.   
  4. //将Excel每一行数值转换为对象  
  5. public class InfoVo {  
  6.       
  7.     private String code;  
  8.     private String name;  
  9.     private String date;  
  10.     private String money;  
  11.       
  12.     public String getCode() {  
  13.         return code;  
  14.     }  
  15.     public void setCode(String code) {  
  16.         this.code = code;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.     public String getDate() {  
  25.         return date;  
  26.     }  
  27.     public void setDate(String date) {  
  28.         this.date = date;  
  29.     }  
  30.     public String getMoney() {  
  31.         return money;  
  32.     }  
  33.     public void setMoney(String money) {  
  34.         this.money = money;  
  35.     }  
  36. }  



main.jsp(前端代码)

[html]  view plain  copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6. <html>  
  7.   <head>  
  8.     <base href="<%=basePath%>">  
  9.     <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>  
  10.     <script type="text/javascript" src="js/jquery.form.js"></script>   
  11.     <title>My JSP 'index.jsp' starting page</title>  
  12.     <script type="text/javascript">  
  13.             //ajax 方式上传文件操作  
  14.              $(document).ready(function(){  
  15.                 $('#btn').click(function(){  
  16.                     if(checkData()){  
  17.                         $('#form1').ajaxSubmit({    
  18.                             url:'uploadExcel/ajaxUpload.do',  
  19.                             dataType: 'text',  
  20.                             success: resutlMsg,  
  21.                             error: errorMsg  
  22.                         });   
  23.                         function resutlMsg(msg){  
  24.                             alert(msg);     
  25.                             $("#upfile").val("");  
  26.                         }  
  27.                         function errorMsg(){   
  28.                             alert("导入excel出错!");      
  29.                         }  
  30.                     }  
  31.                 });  
  32.              });  
  33.                
  34.              //JS校验form表单信息  
  35.              function checkData(){  
  36.                 var fileDir = $("#upfile").val();  
  37.                 var suffix = fileDir.substr(fileDir.lastIndexOf("."));  
  38.                 if("" == fileDir){  
  39.                     alert("选择需要导入的Excel文件!");  
  40.                     return false;  
  41.                 }  
  42.                 if(".xls" != suffix && ".xlsx" != suffix ){  
  43.                     alert("选择Excel格式的文件导入!");  
  44.                     return false;  
  45.                 }  
  46.                 return true;  
  47.              }  
  48.     </script>   
  49.   </head>  
  50.     
  51.   <body>  
  52.   <div>1.通过简单的form表单提交方式,进行文件的上</br> 2.通过jquery.form.js插件提供的form表单一步提交功能 </div></br>  
  53.     <form method="POST"  enctype="multipart/form-data" id="form1" action="uploadExcel/upload.do">  
  54.         <table>  
  55.          <tr>  
  56.             <td>上传文件: </td>  
  57.             <td> <input id="upfile" type="file" name="upfile"></td>  
  58.          </tr>  
  59.         <tr>  
  60.             <td><input type="submit" value="提交" onclick="return checkData()"></td>  
  61.             <td><input type="button" value="ajax方式提交" id="btn" name="btn" ></td>  
  62.          </tr>  
  63.         </table>    
  64.     </form>  
  65.       
  66.   </body>  
  67. </html>  


web.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">  
  7.   
  8.       <!-- 加载Spring容器监听 -->  
  9.       <listener>      
  10.             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  11.       </listener>  
  12.         
  13.       <!-- 设置Spring容器加载配置文件路径 -->  
  14.       <context-param>      
  15.           <param-name>contextConfigLocation</param-name>      
  16.           <param-value>WEB-INF/application/applicationContext-*.xml</param-value>  
  17.       </context-param>  
  18.         
  19.       <!--配置Springmvc核心控制器-->  
  20.       <servlet>            
  21.             <servlet-name>springmvc</servlet-name>           
  22.             <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  23.             <load-on-startup>1</load-on-startup>  
  24.       </servlet>      
  25.       <!--为DispatcherServlet建立映射 -->        
  26.       <servlet-mapping>    
  27.             <servlet-name>springmvc</servlet-name>        
  28.             <url-pattern>*.do</url-pattern>      
  29.       </servlet-mapping>   
  30.     <welcome-file-list>  
  31.         <welcome-file>main.jsp</welcome-file>  
  32.     </welcome-file-list>    
  33. </web-app>  


springmvc-servlet.xml(只做简单配置)

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.      xmlns:context="http://www.springframework.org/schema/context"  
  4.      xmlns:mvc="http://www.springframework.org/schema/mvc"    
  5.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  6.      xmlns:tx="http://www.springframework.org/schema/tx"   
  7.      xsi:schemaLocation="  
  8.           http://www.springframework.org/schema/beans       
  9.           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
  10.           http://www.springframework.org/schema/context  
  11.           http://www.springframework.org/schema/context/spring-context-4.1.xsd  
  12.           http://www.springframework.org/schema/mvc  
  13.           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
  14.           http://www.springframework.org/schema/tx       
  15.           http://www.springframework.org/schema/tx/spring-tx-4.1.xsd     
  16.           http://www.springframework.org/schema/context       
  17.           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd ">  
  18.        
  19.      <!-- 启动注解驱动-->    
  20.      <mvc:annotation-driven/>    
  21.      <!-- 启动包扫描功能-->    
  22.      <context:component-scan base-package="com.poiexcel.*" />    
  23.        
  24. </beans>    


applicationContext-base.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.      xmlns:context="http://www.springframework.org/schema/context"  
  4.      xmlns:mvc="http://www.springframework.org/schema/mvc"    
  5.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  6.      xmlns:tx="http://www.springframework.org/schema/tx"   
  7.      xsi:schemaLocation="  
  8.           http://www.springframework.org/schema/beans       
  9.           http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
  10.           http://www.springframework.org/schema/context  
  11.           http://www.springframework.org/schema/context/spring-context-4.1.xsd   
  12.           http://www.springframework.org/schema/mvc  
  13.           http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd  
  14.           http://www.springframework.org/schema/tx       
  15.           http://www.springframework.org/schema/tx/spring-tx-4.1.xsd      
  16.           http://www.springframework.org/schema/context       
  17.           http://www.springframework.org/schema/context/spring-context-4.1.xsd ">  
  18.             
  19.      <!-- 视图解释类 -->    
  20.      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  21.       <property name="prefix" value="/WEB-INF/jsp/" />  
  22.       <property name="suffix" value=".jsp" />  
  23.      </bean>  
  24.             
  25.     <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
  26.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  27.         <property name="defaultEncoding" value="utf-8" />  
  28.         <!-- 指定所上传文件的总大小不能超过10485760000B。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
  29.         <property name="maxUploadSize" value="10485760000" />  
  30.         <property name="maxInMemorySize" value="40960" />  
  31.     </bean>  
  32.             
  33. </beans>            


效果


后台打印信息


原文链接:https://blog.youkuaiyun.com/onepersontz/article/details/49891405

补充1,有些excel的操作技巧需要用得到,1,合并单元格;2,略去首行:

        Workbook webBook;
        if (EXCEL_TYPE.equals(ExcelType.EXCEL_2003L)){
            webBook = new HSSFWorkbook();
        } {
            webBook = new XSSFWorkbook();
        }
        //createCellStyle(webBook,excelType);
        //Sheet sheet = webBook.getSheetAt(0);
        Sheet sheet = webBook.createSheet();
        sheet.setDefaultColumnWidth(18);//表格宽度
        sheet.setColumnWidth(6,30 * 256);//表格宽度
        sheet.setColumnWidth(2,30 * 256);//表格宽度
        sheet.setDefaultRowHeightInPoints(18);

        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(0,20,6,6));

        //开始操作模板,找到某行某列(某个cell),需要注意的是这里有个坑,行和列的计数都是从0开始的
        Row row0 = sheet.createRow(0);
        row0.setHeight((short) (25*18));

        //6月25日产品张欣妍要求车船号改为车号
        //ExcelUtils.createHeaderCell(webBook,row0,0,"*车船号",EXCEL_TYPE);
        ExcelUtils.createHeaderCell(webBook,row0,0,"*车号",EXCEL_TYPE);
        //ExcelUtils.createHeaderCell(webBook,row0,1,"车船联系人",EXCEL_TYPE);
        ExcelUtils.createHeaderCell(webBook,row0,1,"联系人",EXCEL_TYPE);
        ExcelUtils.createHeaderCell(webBook,row0,2,"身份证号",EXCEL_TYPE);
        ExcelUtils.createHeaderCell(webBook,row0,3,"计划提货量(吨)",EXCEL_TYPE);
        ExcelUtils.createHeaderCell(webBook,row0,4,"允许提货次数",EXCEL_TYPE);
        ExcelUtils.createHeaderCell(webBook,row0,5,"备注",EXCEL_TYPE);
        String tips = "模板使用帮助\n" +
                "\n" +
                "1、车辆号必填,且不能重复,最多输入1000辆车号,即最多允许导入1000行车辆信息;\n" +
                "\n" +
                "2、允许提货次数为0时表示此车辆不限提货次数,本列仅允许输入数字;\n" +
                "\n" +
                "3、计划提货量精确到小数点后三位;\n" +
                "\n" +
                "4、不要改变A至F列排列顺序,且不要增加或删除A至F列中的任一列。";
        Cell cell = row0.createCell(6);
        cell.setCellValue(tips);

        CellStyle titleStyle = ExcelUtils.createCellStyle(webBook,EXCEL_TYPE);
        cell.setCellStyle(titleStyle);
        DataFormat dataFormat = webBook.createDataFormat();
        CellStyle cellStyle3 = webBook.createCellStyle();
        //cellStyle3.setDataFormat(dataFormat.getFormat("0.000"));
        cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.000"));//没有效果
        CellStyle cellStyle4 = webBook.createCellStyle();
        cellStyle4.setDataFormat(HSSFDataFormat.getBuiltinFormat("0"));
        // 设置为文本格式,防止身份证号变成科学计数法
        //cellStyle.setDataFormat(dataFormat.getFormat("@"));
        // 设置为数字格式
        //cellStyle4.setDataFormat(dataFormat.getFormat("1"));
        //System.out.println("cellStyle3-----------"+cellStyle3.getDataFormatString()+"---cellStyle3----"+cellStyle4.getDataFormatString());
        //System.out.println("cellStyle3-----------"+cellStyle3.getDataFormatString()+"---cellStyle3----"+cellStyle4.getDataFormatString());
        //第0行是首行得从第1行开始
        for (int i = 0; i < MAX_LINE; i++) {
            if(0 == i){continue;}
            Row row = sheet.createRow(i);
            Cell cell3 = row.createCell((short) 3);
            cell3.setCellStyle(cellStyle3);
            cell3.setCellType(Cell.CELL_TYPE_NUMERIC);
            Cell cell4 = row.createCell((short) 4);
            cell4.setCellStyle(cellStyle4);
            cell4.setCellType(Cell.CELL_TYPE_NUMERIC);
        }

3,设置表格内容样式,注意如果存在前景色则设置背景色可能看不出来效果

public static CellStyle createHeaderStyle(Workbook wb, String excelType) {
        CellStyle cellstyle = null;
        if (excelType.equals(ExcelType.EXCEL_2003L)){
            /**
             * 设置表格样式
             */
            cellstyle = wb.createCellStyle();
            cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellstyle.setBottomBorderColor(HSSFColor.BLACK.index);
            cellstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellstyle.setLeftBorderColor(HSSFColor.BLACK.index);
            cellstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellstyle.setRightBorderColor(HSSFColor.BLACK.index);
            cellstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellstyle.setTopBorderColor(HSSFColor.BLACK.index);
            cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
            //cellstyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
            cellstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            //cellstyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);//背景色是灰色

            /**
             * 设置字体样式
             */
            Font font = wb.createFont();
            font.setFontHeightInPoints((short) 9);
            font.setColor(HSSFColor.BLACK.index);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            //font.setFontName("宋体");
            font.setFontName("微软雅黑");
            cellstyle.setFont(font);
        } else {
            cellstyle = wb.createCellStyle();
            cellstyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            cellstyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
            cellstyle.setBottomBorderColor(HSSFColor.BLACK.index);
            cellstyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
            cellstyle.setLeftBorderColor(HSSFColor.BLACK.index);
            cellstyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
            cellstyle.setRightBorderColor(HSSFColor.BLACK.index);
            cellstyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
            cellstyle.setTopBorderColor(HSSFColor.BLACK.index);
            cellstyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            //cellstyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
            cellstyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
            //cellstyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
            /**
             * 设置字体样式
             */
            Font font = wb.createFont();
            font.setFontHeightInPoints((short) 9);
            font.setColor(HSSFColor.BLACK.index);
            font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
            //font.setFontName("宋体");
            font.setFontName("微软雅黑");
            cellstyle.setFont(font);
        }
        //cellstyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
        cellstyle.setFillForegroundColor(HSSFColor.YELLOW.index);
        //cellstyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);//背景色是灰色
        cellstyle.setFillBackgroundColor(HSSFColor.YELLOW.index);//背景色是灰色


        return cellstyle;
    }

补充2,

1、单元格宽度问题

这个问题有两个解决办法,一个是

sheet.autoSizeColumn(1);
sheet.autoSizeColumn(1, true);

这种是自适应,第一参数是列号,从0开始,第二参数是是否考虑合并单元格。

还有一种是固定的多宽,这个宽度值就交给自己去测试了:

sheet.setColumnWidth(1, 5000)

这个第二个参数是宽度,具体上面说了自己测试。5000就很宽了,看放什么了。

2、数据不是数字格式问题

这个看api的感觉应该是设置这么个参数,cell.setCellType(Cell.CELL_TYPE_NUMERIC);

但是实际上这个参数设置了不起作用,后来发现自己放的值是String类型,所以不行,后来改为了Double.valueOf(str)方法,发现还是不行,换成Double.parseDouble(str)就行了,原来前面的方法返回的是Double,后面的是double,封装类型也不行。。。

后来就统一把所有的参数设置为Object类型了,这样好转。

3、格式化后显示###

这里是因为宽度不够啦,所以我这里主要说一下怎么格式化好了。

其实Excel本身带了一部分的格式化,见下图

Excel格式设置

如上图所示,Excel自带了一部分格式,而poi的DataFormat中也自带了这些格式并对应了short值,如下所示:

内置数据类型
编号

"General"
0

"0"
1

"0.00"
2

"#,##0"
3

"#,##0.00"
4

"($#,##0_);($#,##0)"
5

"($#,##0_);[Red]($#,##0)"
6

"($#,##0.00);($#,##0.00)"
7

"($#,##0.00_);[Red]($#,##0.00)"
8

"0%"
9

"0.00%"
0xa

"0.00E+00"
0xb

"# ?/?"
0xc

"# ??/??"
0xd

"m/d/yy"
0xe

"d-mmm-yy"
0xf

"d-mmm"
0x10

"mmm-yy"
0x11

"h:mm AM/PM"
0x12

"h:mm:ss AM/PM"
0x13

"h:mm"
0x14

"h:mm:ss"
0x15

"m/d/yy h:mm"
0x16

保留为过国际化用
0x17 - 0x24

"(#,##0_);(#,##0)"
0x25

"(#,##0_);[Red](#,##0)"
0x26

"(#,##0.00_);(#,##0.00)"
0x27

"(#,##0.00_);[Red](#,##0.00)"
0x28

"_($*#,##0_);_($*(#,##0);_($* \"-\"_);_(@_)"
0x29

"_(*#,##0.00_);_(*(#,##0.00);_(*\"-\"??_);_(@_)"
0x2a

"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
0x2b

"_($*#,##0.00_);_($*(#,##0.00);_($*\"-\"??_);_(@_)"
0x2c

"mm:ss"
0x2d

"[h]:mm:ss"
0x2e

"mm:ss.0"
0x2f

"##0.0E+0"
0x30

"@" - This is text format
0x31

使用下面的代码来设置

接下来我会举例日期、小数、货币、百分比、中文大写、科学计数几种方式的格式化:

 1、日期格式

2、小数格式

3、货币格式

4、百分比格式

5、中文大写格式

6、科学计数格式

这里面一部分使用的是DataFormat.getBuiltinFormat(),是由于这部分格式化是Excel中自带的格式,具体自带的格式大家可以自己打开Excel看看,上图也有截出一部分。

到此POI的Excel的单元格格式化方式的一些问题就解决了。

原文地址:http://irfen.me/poi-excel-cell-format-set-params/

以上。


poi解析excel功能参数说明 此项目是基于springMVC实现的,基本流程为从前台jsp页面使用Ajax文件上传导入excel文件(.xls(97-03)/.xlsx(07以后)),传到后台controller调用相应工具类解析后返回指定参数做后续处理. 1. POIUtil.java工具类 解析通过MutilpartFile导入Excel并解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,通过workbook.getNumberOfSheets()获取工作簿数量,遍历工作簿,sheet.getLastRowNum()获取最大行数,将每行数据放入List list = new Array List(),并根据excel数据类型将器转换为字符串、数字、Boolean、公式、空值类型防止出现错误,最后返回一个list. 2. ExcelUtil.java工具类 解析通过MutilpartFile导入Excel并解析里面数据,先判断文件的类型(excel处理有两种此处为两种通用)是.xls/.xlsx,采用Apache的POI的API来操作Excel,读取内容后保存到List中,再将List转Json(使用Linked,增删快,与Excel表顺序保持一致),Sheet表1————>List1<Map> 步骤1:根据Excel版本类型创建对于的Workbook以及CellSytle 步骤2:遍历每一个表中的每一行的每一列,这里做了些小改动,因为后续可能解析过后可能会保存入数据库,这里为第一行数据添加一个自定义表头 String[] p = new String[]{"name","age","sex","tel","address","e-mail","phone"}; 遍历的列数量以p的length为准 步骤3:一个sheet表就是一个Json,多表就多Json,对应一个 List 一个sheet表的一行数据就是一个 Map 一行中的一列,就把当前列头为key,列值为value存到该列的Map中 Map 一个线性Hash Map,以Excel的sheet表顺序,并以sheet表明作为key,sheet表转换Json后的字符串作为value 最后返回一个LinkedHashMap 3. ExcelToJsonPoi.java工具类 这个与上面工具类类似,不过这个是解析本地excel文件不是使用的流,使用迭代遍历sheet工作簿与每行每列的值,将所有类型作为String类型处理返回一个json对象输出至控制台
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值