当前位置:网站首页>Reading and writing Apache poi
Reading and writing Apache poi
2022-06-27 09:07:00 【Midsummer 28】
POI-Excel
Frequently used information
- Export user information as excel form ( For example, export data : database information )
- take excel The information in the table is entered into the website database ( For example, import data : Question bank )
Development often uses excel To deal with , For example, import 、 export excel
operation Excel What's more popular at present is Apache POI And Alibaba's easyExcel
Apache POI( It will be more troublesome )
Official website :Apache POI - the Java API for Microsoft Documents

Baidu profile :
Apache POI [1] Yes, it is Java Write free open source cross platform Java API,Apache POI Provide API to Java Program pair [Microsoft Office](https://baike.baidu.com/item/Microsoft Office) Format file reading and writing functions .POI by “Poor Obfuscation Implementation” An acronym for , Meaning for “ Simple version of fuzzy implementation ”.
structure :

easyExcel(alibaba)
Official website :https://github.com/alibaba/easyexce or EasyExcel · Language sparrow (yuque.com)

EasyExcel Alibaba is an open source excel Processing framework , With Easy to use , Save memory
EasyExcel It's based on Java Simple 、 Save memory for reading and writing Excel Open source projects for . In the case of saving memory as much as possible, it supports reading and writing M Of Excel.
EasyExcel The main reason that can greatly reduce the memory occupation is parsing Excel The file data is not loaded into memory at one time , Instead, read data from a row on the disk , One by one .
File decompression, file reading through file form

POI-Excel Write
Create project
Create a new project
introduce pom rely on
<!-- Import dependence --> <dependencies> <!--03--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.0</version> </dependency> <!--07--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.0</version> </dependency> <!-- Date formatting tool --> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.10.1</version> </dependency> <!--test--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>The popular science :
03 Version of execl and 07 Version of execl What's the difference ?03 And 07 Differences in versions :
03 edition
@Test public void test03() throws IOException { // Create a workbook Workbook workbook = new HSSFWorkbook(); // Create a worksheet Sheet sheet = workbook.createSheet(" Li Kai's worksheet "); // Create lines Row row = sheet.createRow(0); // Create cell grids ((0,0) Cell cell = row.createCell(0); /* Add content */ cell.setCellValue(" Spend today "); //(0,1) Cell cell1 = row.createCell(1); cell.setCellValue("20"); /*1,0*/ final Row row1 = sheet.createRow(1); final Cell cell2 = row1.createCell(0); cell2.setCellValue(" Count the time "); final String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss:sss"); final Cell cell3 = row1.createCell(1); /* Put in time */ cell3.setCellValue(time); /* Generate a table 03 Version USES xls ending */ FileOutputStream fileOutputStream = new FileOutputStream(PATH + " Li Kai's sunrise consumption table .xls"); workbook.write(fileOutputStream); // Closed flow fileOutputStream.close(); workbook.close(); System.out.println(" Generation completed "); }07 edition
public void test07() throws IOException { // Create a workbook Workbook workbook = new XSSFWorkbook(); // Create a worksheet Sheet sheet = workbook.createSheet(" Li Kai's worksheet "); // Create lines Row row = sheet.createRow(0); // Create cell grids ((0,0) Cell cell = row.createCell(0); /* Add content */ cell.setCellValue(" Spend today "); //(0,1) Cell cell1 = row.createCell(1); cell1.setCellValue("20"); /*1,0*/ Row row1 = sheet.createRow(1); Cell cell2 = row1.createCell(0); cell2.setCellValue(" Count the time "); final String time = new DateTime().toString("yyyy-MM-dd HH:mm:ss:sss"); final Cell cell3 = row1.createCell(1); /* Put in time */ cell3.setCellValue(time); /* Generate a table 03 Version USES xls ending */ FileOutputStream fileOutputStream = new FileOutputStream(PATH + " Li Kai's sunrise consumption table .xlsx"); workbook.write(fileOutputStream); // Closed flow fileOutputStream.close(); workbook.close(); System.out.println(" Generation completed "); }difference :
The difference between objects
03 edition :
Workbook workbook = new HSSFWorkbook();07 edition :
Workbook workbook = new XSSFWorkbook();The difference between suffixes
03 07 xls xlsx
03 Version of large file write
shortcoming : Only... Can be written at most 65536 That's ok , Otherwise, an exception will be thrown
java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
advantage : Write cache in process , Do not operate disk , The last one-time write to disk , Fast
Time :
Correct code :
public void test03BigData() throws IOException {
// Time difference :
final long begin = System.currentTimeMillis();
// Create a workbook
Workbook workbook = new HSSFWorkbook();
// Create table
final Sheet sheet = workbook.createSheet();
// Write data
for (int rowNum = 0;rowNum<65536;rowNum++){
final Row row = sheet.createRow(rowNum);
for (int cellNum = 0;cellNum<10;cellNum++){
final Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("over");
final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
final long end = System.currentTimeMillis();
System.out.println((double)(end-begin)/1000);
}
Error code :
public void test03BigData() throws IOException {
// Time difference :
final long begin = System.currentTimeMillis();
// Create a workbook
Workbook workbook = new HSSFWorkbook();
// Create table
final Sheet sheet = workbook.createSheet();
// Write data
for (int rowNum = 0;rowNum<65537;rowNum++){
final Row row = sheet.createRow(rowNum);
for (int cellNum = 0;cellNum<10;cellNum++){
final Cell cell = row.createCell(cellNum);
cell.setCellValue(cellNum);
}
}
System.out.println("over");
final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xls");
workbook.write(fileOutputStream);
fileOutputStream.close();
final long end = System.currentTimeMillis();
System.out.println((double)(end-begin)/1000);
}
07 Version of large file write
shortcoming : When writing data, the data speed is very slow , Very memory intensive , There will also be spills , Such as 100w Data
advantage : You can write a large amount of data , Such as 20w Data
Time :

You can find even one more piece of data , There will be more time 4 times
Code :
public void test07BigData() throws IOException { // Time difference : final long begin = System.currentTimeMillis(); // Create a workbook Workbook workbook = new XSSFWorkbook(); // Create table final Sheet sheet = workbook.createSheet(); // Write data for (int rowNum = 0;rowNum<65537;rowNum++){ final Row row = sheet.createRow(rowNum); for (int cellNum = 0;cellNum<10;cellNum++){ final Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } System.out.println("over"); final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); final long end = System.currentTimeMillis(); System.out.println((double)(end-begin)/1000); }07 Version of big data write SXSSF
advantage: Can write a very large amount of data , for example 100w Pieces of data or even more , be relative to 07 Version of XSSF, He reads and writes data faster , Less memoryBe careful: Temporary files are generated in the process , Need to clean up temporary filesBy default 100 Records are stored in memory , If you exceed that amount , The first data will be written to the temporary file .
If you want to customize the amount of data in memory , You can use the
new SXXSFWorkbook( Number )Time :

Code :
public void test07BigDataS() throws IOException { // Time difference : final long begin = System.currentTimeMillis(); // Create a workbook Workbook workbook = new SXSSFWorkbook(); // Create table final Sheet sheet = workbook.createSheet(); // Write data for (int rowNum = 0;rowNum<65537;rowNum++){ final Row row = sheet.createRow(rowNum); for (int cellNum = 0;cellNum<10;cellNum++){ final Cell cell = row.createCell(cellNum); cell.setCellValue(cellNum); } } System.out.println("over"); final FileOutputStream fileOutputStream = new FileOutputStream(PATH+" test .xlsx"); workbook.write(fileOutputStream); fileOutputStream.close(); /* Clear temporary files */ ((SXSSFWorkbook)workbook).dispose(); final long end = System.currentTimeMillis(); System.out.println((double)(end-begin)/1000); }
POI-Excel read
07/03 edition
@Test
public void test03() throws IOException {
// Get file stream
FileInputStream fileInputStream = new FileInputStream(PATH+"ABC.xls");
// Create a workbook . Use excel Any operation that can be completed can be completed here
Workbook workbook = new HSSFWorkbook(fileInputStream);
// Get the table
final Sheet sheetAt = workbook.getSheetAt(0);
/* Get row */
final Row row = sheetAt.getRow(0);
final int RowNum = sheetAt.getLastRowNum();
/* Get column */
final Cell cell = row.getCell(0);
final String stringCellValue = cell.getStringCellValue();
System.out.println(stringCellValue);
System.out.println(RowNum);
fileInputStream.close();
}
07 edition :
@Test
public void test03() throws IOException {
// Get file stream
FileInputStream fileInputStream = new FileInputStream(PATH+"ABC.xlsx");
// Create a workbook . Use excel Any operation that can be completed can be completed here
Workbook workbook = new XSSFWorkbook(fileInputStream);
// Get the table
final Sheet sheetAt = workbook.getSheetAt(0);
/* Get row */
final Row row = sheetAt.getRow(0);
final int RowNum = sheetAt.getLastRowNum();
/* Get column */
final Cell cell = row.getCell(0);
final String stringCellValue = cell.getStringCellValue();
System.out.println(stringCellValue);
System.out.println(RowNum);
fileInputStream.close();
}
Read different data types
a key : Data conversion type !
@Test
public void test07Demo() throws IOException {
// Get file stream
FileInputStream fileInputStream = new FileInputStream(PATH+"ABC.xlsx");
// Create a workbook . Use excel Any operation that can be completed can be completed here
Workbook workbook = new XSSFWorkbook(fileInputStream);
// Get the table
Sheet sheetAt = workbook.getSheetAt(0);
/* Get the number of lines */
Row row = sheetAt.getRow(0);
if (row!=null){
/* Get the number of all rows */
final int physicalNumberOfCells = row.getPhysicalNumberOfCells();
for (int CellNum = 0; CellNum < physicalNumberOfCells; CellNum++) {
final Cell cell = row.getCell(CellNum);
if (cell!=null){
/* Get the type of row */
CellType cellType = cell.getCellType();
String stringCellValue = cell.getStringCellValue();
System.out.print(stringCellValue+" ");
}
}
System.out.println();
}
// Get the data in the table ( Number of columns )
int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();
for (int RowNum = 1; RowNum < physicalNumberOfRows; RowNum++) {
final Row row1 = sheetAt.getRow(RowNum);
if (row1!=null){
// Read column
final int physicalNumberOfCells = row1.getPhysicalNumberOfCells();
for (int cellNumber = 0; cellNumber < physicalNumberOfCells; cellNumber++) {
final Cell cell = row1.getCell(cellNumber);
// Match the data type of the column
if (cell!=null){
CellType cellType = cell.getCellType();
String cellValue = "";
/* Judgment type */
switch (cellType){
case STRING:
System.out.println(" character string ");
cellValue= cell.getStringCellValue();
break;
case BOOLEAN:
System.out.println(" Boolean type ");
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case BLANK:
System.out.println(" It's empty ");
break;
case NUMERIC: // Numbers ( Dates and ordinary numbers )
if (HSSFDateUtil.isCellDateFormatted(cell)){
// date
System.out.println(" The date type ");
Date date = cell.getDateCellValue();
cellValue = new DateTime(date).toString("yyyy-MM-dd");
}else {
System.out.println(" Numbers ");
cellValue = String.valueOf(cell.getNumericCellValue());
}
break;
case ERROR:
System.out.println(" Wrong array type ");
break;
}
System.out.println(cellValue);
}
}
}
}
fileInputStream.close();
}
Calculation formula :
@Test
public void testFormula() throws IOException {
FileInputStream fileInputStream = new FileInputStream(PATH + "Documents test .xlsx");
Workbook workbook= new XSSFWorkbook(fileInputStream);
Sheet sheetAt = workbook.getSheetAt(0);
Row row = sheetAt.getRow(4);
Cell cell = row.getCell(0);
// Get the formula eval
FormulaEvaluator xssfFormulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) workbook);
// Output the contents of the cell
CellType cellType = cell.getCellType();
switch (cellType){
case FORMULA: // The formula
String cellFormula = cell.getCellFormula();
System.out.println(cellFormula);
// Calculation
CellValue evaluate = xssfFormulaEvaluator.evaluate(cell);
String CellValue = evaluate.formatAsString();
System.out.println(CellValue);
break;
}
}
边栏推荐
- orthofinder直系同源蛋白分析及结果处理
- Enumeration? Constructor? Interview demo
- 第十一章 信号(一)- 概念
- Demand visual Engineer
- Digital ic-1.9 understands the coding routine of state machine in communication protocol
- RockerMQ消息发送模式
- IO pin configuration and pinctrl drive
- (original) custom drawable
- 我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
- Semi supervised learning—— Π- Introduction to model, temporary assembling and mean teacher
猜你喜欢

Understanding mvcc in MySQL transactions is super simple

0号进程,1号进程,2号进程

this,构造器,静态,之间调用,必须搞懂啊!
![[cloud native] 2.3 kubernetes core practice (Part 1)](/img/f8/dbd2546e775625d5c98881e7745047.png)
[cloud native] 2.3 kubernetes core practice (Part 1)

Semi supervised learning—— Π- Introduction to model, temporary assembling and mean teacher

我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!

Getting started with webrtc: 12 Rtendpoint and webrtcendpoint under kurento

粗读DS-TransUNet: Dual Swin Transformer U-Net for Medical Image Segmentation

Matlab tips (19) matrix analysis -- principal component analysis

Understand neural network structure and optimization methods
随机推荐
ThreadLocal再次挖掘它的知识点
June 26, 2022 (LC 6100 counts the number of ways to place houses)
Static code block vs construction code block
vim 从嫌弃到依赖(20)——global 命令
RMAN-08137 主库无法删除归档文件
ServletConfig and ServletContext
MATLAB小技巧(19)矩阵分析--主成分分析
Demand visual Engineer
Markem Imaje Marken IMAS printer maintenance 9450e printer maintenance
2022.06.26(LC_6100_统计放置房子的方式数)
Correctly understand MySQL mvcc
1098 insertion or heap sort (PAT class a)
内部类~锁~访问修饰符
[ 扩散模型(Diffusion Model) ]
Hitek power supply maintenance X-ray machine high voltage generator maintenance xr150-603-02
即构「畅直播」,全链路升级的一站式直播服务
ucore lab4
[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy
ThreadLocal digs its knowledge points again
Analysis log log