Apache poi 与 EasyExcel使用详解
转载:https://blog.csdn.net/vbirdbest/article/details/72870714
1. 什么是Apache POI
Apache POI 简介是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式档案读和写的功能。
官方主页:http://poi.apache.org/index.html
API文档:http://poi.apache.org/apidocs/index.html【英文】
在线API文档:https://tool.oschina.net/apidocs/apidoc?api=apache-POI
快速指南:https://max.book118.com/html/2017/0918/134317481.shtm
中文Excel文档:https://www.yiibai.com/javaexamples/java_apache_poi_excel.html
中文word文档:https://www.yiibai.com/javaexamples/java_apache_poi_word.html
中文PPT文档:https://www.yiibai.com/javaexamples/java_apache_poi_ppt.html
中文PDF文档:https://www.yiibai.com/javaexamples/java_apache_pdf_box.html
POI结构:
HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML 【XLSX】格式档案的功能。
HWPF - 提供读写Microsoft Word DOC97格式档案的功能。
XWPF - 提供读写Microsoft Word DOC2003格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读Microsoft Visio格式档案的功能。
HPBF - 提供读Microsoft Publisher格式档案的功能。
HSMF - 提供读Microsoft Outlook格式档案的功能。
2. 为什么要学习它
在web开发中,有一个经典的功能,就是数据的导入导出。特别是数据的导出,在生产管理或者财务系统中用的非常普遍,因为这些系统经常要做一些报表打印的工作。而数据的导入往往用于那些大数据量的批量导入和简化操作。
现在流行的操作Excel开源工具有Apache的POI(耗内存)及阿里的EasyExcel。
本文主要讲解导入数据!
3. Let's Go
3.1 介绍常用类与方法简介
HSSFWorkbook 工作簿,代表一个excel的整个文档。
HSSFWorkbook: 是操作Excel2003以前(包括2003)的版本,扩展名是.xls
XSSFWorkbook: 是操作Excel2007的版本,扩展名是.xlsx。
HSSFWorkbook(); // 创建一个新的工作簿
HSSFWorkbook(InputStream inputStream); // 创建一个关联输入流的工作簿,可以将一个excel文件封装成工作簿
HSSFSheet createSheet(String sheetname); 创建一个新的Sheet
HSSFSheet getSheet(String sheetName); 通过名称获取Sheet
HSSFSheet getSheetAt(int index); // 通过索引获取Sheet,索引从0开始
HSSFCellStyle createCellStyle(); 创建单元格样式
int getNumberOfSheets(); 获取sheet的个数
setActiveSheet(int index); 设置默认选中的工作表
write();
write(File newFile);
write(OutputStream stream);
HSSFSheet 工作表
HSSFRow createRow(int rownum); 创建新行,需要指定行号,行号从0开始
HSSFRow getRow(int index); 根据索引获取指定的行
int addMergedRegion(CellRangeAddress region); 合并单元格
CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol); 单元格范围, 用于合并单元格,需要指定要合并的首行、最后一行、首列、最后一列。
autoSizeColumn(int column); 自动调整列的宽度来适应内容
getLastRowNum(); 获取最后的行的索引,没有行或者只有一行的时候返回0
setColumnWidth(int columnIndex, int width); 设置某一列的宽度,width=字符个数 * 256,例如20个字符的宽度就是20 * 256
HSSFRow 行
HSSFCell createCell(int column); 创建新的单元格
short getFirstCellNum(); 获取此行中第一个单元格的编号
int getPhysicalNumberOfCells(); 获取此行已定义的单元格数量,若只有第0,4,5列有值,则返回的是3
HSSFCell setCell(shot index);
HSSFCell getCell(shot index); 获取此行指定列的单元格,若你想获取的那个单元格未定义,则返回null
setRowStyle(HSSFCellStyle style); 设置行样式
short getLastCellNum(); 获取最后的单元格号,如果单元格有第一个开始算,lastCellNum就是列的个数
setHeightInPoints(float height); 设置行的高度
HSSFCell 单元格
setCellValue(String value); 设置单元格的值
setCellType(); 设置单元格类型,如 字符串、数字、布尔等
setCellStyle(); 设置单元格样式
String getStringCellValue(); 获取单元格中的字符串值
setCellStyle(HSSFCellStyle style); 设置单元格样式,例如字体、加粗、格式化
setCellFormula(String formula); 设置计算公式,计算的结果作为单元格的值,也提供了异常常用的函数,如求和”sum(A1,C1)”、日期函数、字符串相关函数、CountIf和SumIf函数、随机数函数等
HSSFCellStyle 单元格样式
setFont(Font font); 为单元格设置字体样式
setAlignment(HorizontalAlignment align); // 设置水平对齐方式
setVerticalAlignment(VerticalAlignment align); // 设置垂直对齐方式
setFillPattern(FillPatternType fp);
setFillForegroundColor(short bg); 设置前景色
setFillBackgroundColor(short bg); 设置背景颜色
HSSFFont 字体
setColor(short color); // 设置字体颜色
setBold(boolean bold); // 设置是否粗体
setItalic(boolean italic); 设置倾斜
setUnderline(byte underline); 设置下划线
HSSFName 名称
HSSFDataFormat 日期格式化
HSSFHeader Sheet的头部
HSSFFooter Sheet的尾部
HSSFDateUtil 日期工具
HSSFPrintSetup 打印设置
HSSFErrorConstants 错误信息表
Excel中的工作簿、工作表、行、单元格中的关系:
一个Excel文件对应于一个workbook(HSSFWorkbook),
一个workbook可以有多个sheet(HSSFSheet)组成,
一个sheet是由多个row(HSSFRow)组成,
一个row是由多个cell(HSSFCell)组成
3.2 使用示例
3.2.1 导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
poi有两个不同的jar包,分别是处理excel2003和excel2007以后的版本,对应的是poi和poi-ooxml。
poi-ooxml是poi的升级版本,处理的单页数据量也是百万级别的,所以我们选择的也是poi-ooxml。
3.2.2 桌面生成一个Excel文件
public static void createExcel() throws IOException{
// 获取桌面路径
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
File file = new File(filePath);
OutputStream outputStream = new FileOutputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sheet1");
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("id");
row.createCell(1).setCellValue("订单号");
row.createCell(2).setCellValue("下单时间");
row.createCell(3).setCellValue("个数");
row.createCell(4).setCellValue("单价");
row.createCell(5).setCellValue("订单金额");
row.setHeightInPoints(30); // 设置行的高度
HSSFRow row1 = sheet.createRow(1);
row1.createCell(0).setCellValue("1");
row1.createCell(1).setCellValue("NO00001");
// 日期格式化
HSSFCellStyle cellStyle2 = workbook.createCellStyle();
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
sheet.setColumnWidth(2, 20 * 256); // 设置列的宽度
HSSFCell cell2 = row1.createCell(2);
cell2.setCellStyle(cellStyle2);
cell2.setCellValue(new Date());
row1.createCell(3).setCellValue(2);
// 保留两位小数
HSSFCellStyle cellStyle3 = workbook.createCellStyle();
cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
HSSFCell cell4 = row1.createCell(4);
cell4.setCellStyle(cellStyle3);
cell4.setCellValue(29.5);
// 货币格式化
HSSFCellStyle cellStyle4 = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setFontName("华文行楷");
font.setFontHeightInPoints((short)15);
cellStyle4.setFont(font);
HSSFCell cell5 = row1.createCell(5);
cell5.setCellFormula("D2*E2"); // 设置计算公式
// 获取计算公式的值
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
cell5 = e.evaluateInCell(cell5);
System.out.println(cell5.getNumericCellValue());
workbook.setActiveSheet(0);
workbook.write(outputStream);
outputStream.close();
}
3.2.3 读取Excel解析数据
public static void readExcel() throws IOException{
FileSystemView fsv = FileSystemView.getFileSystemView();
String desktop = fsv.getHomeDirectory().getPath();
String filePath = desktop + "/template.xls";
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workbook.getSheet("Sheet1");
int lastRowIndex = sheet.getLastRowNum();
System.out.println(lastRowIndex);
for (int i = 0; i <= lastRowIndex; i++) {
HSSFRow row = sheet.getRow(i);
if (row == null) { break; }
short lastCellNum = row.getLastCellNum();
for (int j = 0; j < lastCellNum; j++) {
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(cellValue);
}
}
bufferedInputStream.close();
}
4. 什么是EasyExcel
EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。在尽可能节约内存的情况下支持读写百M的Excel。
官网:https://www.yuque.com/easyexcel/doc/easyexcel
写Excel数据示例代码:https://alibaba-easyexcel.github.io/quickstart/write.html#示例代码
读Excel数据示例代码:https://alibaba-easyexcel.github.io/quickstart/read.html#示例代码
https://mp.weixin.qq.com/s/zJtP0rf2mVxtjeUlDXiLfg