当前位置:网站首页>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;
}
}
边栏推荐
- 0号进程,1号进程,2号进程
- Correctly understand MySQL mvcc
- About the problem that the El date picker Click to clear the parameter and make it null
- Collection framework generic LinkedList TreeSet
- 三道基础面试题总结
- JVM common garbage collector
- Redis transactions
- How much memory does the data type occupy? LongVsObject
- Matlab tips (18) matrix analysis -- entropy weight method
- 2022.6.26-----leetcode.710
猜你喜欢
RockerMQ消息发送与消费模式
Obsidian 一周使用心得(配置、主题和插件)
Understanding mvcc in MySQL transactions is super simple
粗读DS-TransUNet: Dual Swin Transformer U-Net for Medical Image Segmentation
Markem Imaje Marken IMAS printer maintenance 9450e printer maintenance
力扣84柱状图中最大的矩形
Five basic types of redis
DataV轮播表组件dv-scroll-board宽度问题
MATLAB小技巧(19)矩阵分析--主成分分析
HiTek电源维修X光机高压发生器维修XR150-603-02
随机推荐
Semi-supervised Learning入门学习——Π-Model、Temporal Ensembling、Mean Teacher简介
不容置疑,这是一个绝对精心制作的项目
RockerMQ消息发送模式
三道基础面试题总结
[vivid understanding] the meanings of various evaluation indicators commonly used in deep learning TP, FP, TN, FN, IOU and accuracy
2022.06.26(LC_6100_统计放置房子的方式数)
今日3大面试Demo[Integer ASCII 类关系]
0号进程,1号进程,2号进程
Markem Imaje Marken IMAS printer maintenance 9450e printer maintenance
Today's three interviews demo[integer ASCII class relationship]
Static code block vs construction code block
E+h secondary meter repair pH transmitter secondary display repair cpm253-mr0005
力扣84柱状图中最大的矩形
【云原生】2.3 Kubernetes 核心实战(上)
看看volatile你深知多少
我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
初步认识pytorch
Design of a solar charge pump power supply circuit
[ 扩散模型(Diffusion Model) ]
Persistence mechanism of redis