说明
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解析工具类)
- package com.poiexcel.util;
- import java.io.IOException;
- import java.io.InputStream;
- import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.Row;
- import org.apache.poi.ss.usermodel.Sheet;
- import org.apache.poi.ss.usermodel.Workbook;
- import org.apache.poi.xssf.usermodel.XSSFWorkbook;
- public class ImportExcelUtil {
- private final static String excel2003L =".xls"; //2003- 版本的excel
- private final static String excel2007U =".xlsx"; //2007+ 版本的excel
- /**
- * 描述:获取IO流中的数据,组装成List<List<Object>>对象
- * @param in,fileName
- * @return
- * @throws IOException
- */
- public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception{
- List<List<Object>> list = null;
- //创建Excel工作薄
- Workbook work = this.getWorkbook(in,fileName);
- if(null == work){
- throw new Exception("创建Excel工作薄为空!");
- }
- Sheet sheet = null;
- Row row = null;
- Cell cell = null;
- list = new ArrayList<List<Object>>();
- //遍历Excel中所有的sheet
- for (int i = 0; i < work.getNumberOfSheets(); i++) {
- sheet = work.getSheetAt(i);
- if(sheet==null){continue;}
- //遍历当前sheet中的所有行
- for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
- row = sheet.getRow(j);
- if(row==null||row.getFirstCellNum()==j){continue;}
- //遍历所有的列
- List<Object> li = new ArrayList<Object>();
- for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
- cell = row.getCell(y);
- li.add(this.getCellValue(cell));
- }
- list.add(li);
- }
- }
- work.close();
- return list;
- }
- /**
- * 描述:根据文件后缀,自适应上传文件的版本
- * @param inStr,fileName
- * @return
- * @throws Exception
- */
- public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
- Workbook wb = null;
- String fileType = fileName.substring(fileName.lastIndexOf("."));
- if(excel2003L.equals(fileType)){
- wb = new HSSFWorkbook(inStr); //2003-
- }else if(excel2007U.equals(fileType)){
- wb = new XSSFWorkbook(inStr); //2007+
- }else{
- throw new Exception("解析的文件格式有误!");
- }
- return wb;
- }
- /**
- * 描述:对表格中数值进行格式化
- * @param cell
- * @return
- */
- public Object getCellValue(Cell cell){
- Object value = null;
- DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
- SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
- DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
- switch (cell.getCellType()) {
- case Cell.CELL_TYPE_STRING:
- value = cell.getRichStringCellValue().getString();
- break;
- case Cell.CELL_TYPE_NUMERIC:
- if("General".equals(cell.getCellStyle().getDataFormatString())){
- value = df.format(cell.getNumericCellValue());
- }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
- value = sdf.format(cell.getDateCellValue());
- }else{
- value = df2.format(cell.getNumericCellValue());
- }
- break;
- case Cell.CELL_TYPE_BOOLEAN:
- value = cell.getBooleanCellValue();
- break;
- case Cell.CELL_TYPE_BLANK:
- value = "";
- break;
- default:
- break;
- }
- return value;
- }
- }
UploadExcelControl.java (Spring控制器)
- package com.poiexcel.control;
- import java.io.InputStream;
- import java.io.PrintWriter;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.multipart.MultipartHttpServletRequest;
- import com.poiexcel.util.ImportExcelUtil;
- import com.poiexcel.vo.InfoVo;
- @Controller
- @RequestMapping("/uploadExcel/*")
- public class UploadExcelControl {
- /**
- * 描述:通过传统方式form表单提交方式导入excel文件
- * @param request
- * @throws Exception
- */
- @RequestMapping(value="upload.do",method={RequestMethod.GET,RequestMethod.POST})
- public String uploadExcel(HttpServletRequest request) throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- System.out.println("通过传统方式form表单提交方式导入excel文件!");
- InputStream in =null;
- List<List<Object>> listob = null;
- MultipartFile file = multipartRequest.getFile("upfile");
- if(file.isEmpty()){
- throw new Exception("文件不存在!");
- }
- in = file.getInputStream();
- listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
- in.close();
- //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
- for (int i = 0; i < listob.size(); i++) {
- List<Object> lo = listob.get(i);
- InfoVo vo = new InfoVo();
- vo.setCode(String.valueOf(lo.get(0)));
- vo.setName(String.valueOf(lo.get(1)));
- vo.setDate(String.valueOf(lo.get(2)));
- vo.setMoney(String.valueOf(lo.get(3)));
- System.out.println("打印信息-->机构:"+vo.getCode()+" 名称:"+vo.getName()+" 时间:"+vo.getDate()+" 资产:"+vo.getMoney());
- }
- return "result";
- }
- /**
- * 描述:通过 jquery.form.js 插件提供的ajax方式上传文件
- * @param request
- * @param response
- * @throws Exception
- */
- @ResponseBody
- @RequestMapping(value="ajaxUpload.do",method={RequestMethod.GET,RequestMethod.POST})
- public void ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
- MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
- System.out.println("通过 jquery.form.js 提供的ajax方式上传文件!");
- InputStream in =null;
- List<List<Object>> listob = null;
- MultipartFile file = multipartRequest.getFile("upfile");
- if(file.isEmpty()){
- throw new Exception("文件不存在!");
- }
- in = file.getInputStream();
- listob = new ImportExcelUtil().getBankListByExcel(in,file.getOriginalFilename());
- //该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
- for (int i = 0; i < listob.size(); i++) {
- List<Object> lo = listob.get(i);
- InfoVo vo = new InfoVo();
- vo.setCode(String.valueOf(lo.get(0)));
- vo.setName(String.valueOf(lo.get(1)));
- vo.setDate(String.valueOf(lo.get(2)));
- vo.setMoney(String.valueOf(lo.get(3)));
- System.out.println("打印信息-->机构:"+vo.getCode()+" 名称:"+vo.getName()+" 时间:"+vo.getDate()+" 资产:"+vo.getMoney());
- }
- PrintWriter out = null;
- response.setCharacterEncoding("utf-8"); //防止ajax接受到的中文信息乱码
- out = response.getWriter();
- out.print("文件导入成功!");
- out.flush();
- out.close();
- }
- }
- package com.poiexcel.vo;
- //将Excel每一行数值转换为对象
- public class InfoVo {
- private String code;
- private String name;
- private String date;
- private String money;
- public String getCode() {
- return code;
- }
- public void setCode(String code) {
- this.code = code;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getDate() {
- return date;
- }
- public void setDate(String date) {
- this.date = date;
- }
- public String getMoney() {
- return money;
- }
- public void setMoney(String money) {
- this.money = money;
- }
- }
main.jsp(前端代码)
- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <html>
- <head>
- <base href="<%=basePath%>">
- <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
- <script type="text/javascript" src="js/jquery.form.js"></script>
- <title>My JSP 'index.jsp' starting page</title>
- <script type="text/javascript">
- //ajax 方式上传文件操作
- $(document).ready(function(){
- $('#btn').click(function(){
- if(checkData()){
- $('#form1').ajaxSubmit({
- url:'uploadExcel/ajaxUpload.do',
- dataType: 'text',
- success: resutlMsg,
- error: errorMsg
- });
- function resutlMsg(msg){
- alert(msg);
- $("#upfile").val("");
- }
- function errorMsg(){
- alert("导入excel出错!");
- }
- }
- });
- });
- //JS校验form表单信息
- function checkData(){
- var fileDir = $("#upfile").val();
- var suffix = fileDir.substr(fileDir.lastIndexOf("."));
- if("" == fileDir){
- alert("选择需要导入的Excel文件!");
- return false;
- }
- if(".xls" != suffix && ".xlsx" != suffix ){
- alert("选择Excel格式的文件导入!");
- return false;
- }
- return true;
- }
- </script>
- </head>
- <body>
- <div>1.通过简单的form表单提交方式,进行文件的上</br> 2.通过jquery.form.js插件提供的form表单一步提交功能 </div></br>
- <form method="POST" enctype="multipart/form-data" id="form1" action="uploadExcel/upload.do">
- <table>
- <tr>
- <td>上传文件: </td>
- <td> <input id="upfile" type="file" name="upfile"></td>
- </tr>
- <tr>
- <td><input type="submit" value="提交" onclick="return checkData()"></td>
- <td><input type="button" value="ajax方式提交" id="btn" name="btn" ></td>
- </tr>
- </table>
- </form>
- </body>
- </html>
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
- http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd ">
- <!-- 加载Spring容器监听 -->
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 设置Spring容器加载配置文件路径 -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>WEB-INF/application/applicationContext-*.xml</param-value>
- </context-param>
- <!--配置Springmvc核心控制器-->
- <servlet>
- <servlet-name>springmvc</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <!--为DispatcherServlet建立映射 -->
- <servlet-mapping>
- <servlet-name>springmvc</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>main.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
springmvc-servlet.xml(只做简单配置)
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd ">
- <!-- 启动注解驱动-->
- <mvc:annotation-driven/>
- <!-- 启动包扫描功能-->
- <context:component-scan base-package="com.poiexcel.*" />
- </beans>
applicationContext-base.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-4.1.xsd ">
- <!-- 视图解释类 -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="prefix" value="/WEB-INF/jsp/" />
- <property name="suffix" value=".jsp" />
- </bean>
- <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="utf-8" />
- <!-- 指定所上传文件的总大小不能超过10485760000B。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
- <property name="maxUploadSize" value="10485760000" />
- <property name="maxInMemorySize" value="40960" />
- </bean>
- </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自带了一部分格式,而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
|
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
DataFormat
format
=
workBook
.
createDataFormat
(
)
;
cellStyle
.
setDataFormat
(
format
.
getFormat
(
"@"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
接下来我会举例日期、小数、货币、百分比、中文大写、科学计数几种方式的格式化:
1、日期格式
1
2
3
4
5
6
|
cell
.
setCellValue
(
new
Date
(
2008
,
5
,
5
)
)
;
//set date format
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
DataFormat
format
=
workBook
.
createDataFormat
(
)
;
cellStyle
.
setDataFormat
(
format
.
getFormat
(
"yyyy-MM-dd"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
2、小数格式
1
2
3
4
|
cell
.
setCellValue
(
1.2
)
;
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
cellStyle
.
setDataFormat
(
DataFormat
.
getBuiltinFormat
(
"0.00"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
3、货币格式
1
2
3
4
5
|
cell
.
setCellValue
(
20000
)
;
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
DataFormat
format
=
workBook
.
createDataFormat
(
)
;
cellStyle
.
setDataFormat
(
format
.
getFormat
(
"¥#,##0"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
4、百分比格式
1
2
3
4
|
cell
.
setCellValue
(
20
)
;
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
cellStyle
.
setDataFormat
(
DataFormat
.
getBuiltinFormat
(
"0.00%"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
5、中文大写格式
1
2
3
4
5
|
cell
.
setCellValue
(
20000
)
;
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
DataFormat
format
=
workBook
.
createDataFormat
(
)
;
cellStyle
.
setDataFormat
(
format
.
getFormat
(
"[DbNum2][$-804]0"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
6、科学计数格式
1
2
3
4
|
cell
.
setCellValue
(
20000
)
;
CellStyle
cellStyle
=
workBook
.
createCellStyle
(
)
;
cellStyle
.
setDataFormat
(
DataFormat
.
getBuiltinFormat
(
"0.00E+00"
)
)
;
cell
.
setCellStyle
(
cellStyle
)
;
|
这里面一部分使用的是DataFormat.getBuiltinFormat(),是由于这部分格式化是Excel中自带的格式,具体自带的格式大家可以自己打开Excel看看,上图也有截出一部分。
到此POI的Excel的单元格格式化方式的一些问题就解决了。
原文地址:http://irfen.me/poi-excel-cell-format-set-params/以上。