当前位置:网站首页>Import and export using poi
Import and export using poi
2022-07-25 03:05:00 【Live learning programming ideas】
Use poi Import and export
Official website :https://poi.apache.org/
1、ApachePOI Introduce
ApachePOI Yes, it is Java Write free open source cross platform JavaAPI,ApachePOI Provide API to Java Program pair MicrosoftOffice Format file reading and writing functions , One of the most used is the use of POI operation Excel file .
2、 Use ApachePOI Used jar Packet dependency
<!-- poi My bag 3.15 After the version, the method of getting cell type has been adjusted -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.1</version>
</dependency>
3、POI The use of API Explain
3.1、 structure
HSSF- Provide reading and writing Microsoft Excel XLS The function of format file
XSSF- Provide reading and writing Microsoft ExcelOOXML XLSX The function of format file
HWPF- Provide reading and writing Microsoft Word DOC The function of format file
HSLF- Provide reading and writing MicrosoftPowerPoint The function of format file
HDGF- Offer to read MicrosoftVisio The function of format file
HPBF- Offer to read MicrosoftPublisher The function of format file
HSMF- Offer to read MicrosoftOutlook The function of format file
3.2、 object
3.2.1、.xls and .xlsx The difference between :
excel There are two suffixes , The early xls And later xlsx,
- HSSFWorkbook: Is the operation Excel2003 before ( Include 2003) Version of , The extension is .xls, The maximum number of rows exported is 65535 That's ok , beyond 65536 After the entry, the system will report an error
- XSSFWorkbook: Is the operation Excel2007 Version of , The extension is .xlsx, Export at most 1048576 That's ok ,
SXSSFWorkbook from POI 3.8 Version start , Provides a XSSF Of low memory usage SXSSF The way . For large excel File creation , A key issue is , Make sure there is no memory overflow . Actually , Even if it generates very small excel( How about Mb), It uses far more memory than excel The document is actually size Of . If the cell has various formats ( such as , In bold , The background is marked red or something ), Then it takes up more memory . For large excel Created without memory overflow , Only SXSSFWorkbook 了 . Its principle is very simple , Swap hard disk space for memory ( It's like hash map Trade space for time ).
3.2.2、xls and xlsx Medium Content-type difference
- 2003 Excel edition .xls Of Content-type by
application/vnd.ms-excel - 2010 Excel edition .xlsx Of Content-type by
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Reference resources :https://blog.csdn.net/xiaoyu19910321/article/details/79279364
3.2.3、xls Common components :
HSSFWorkbook : excel Document object for
HSSFSheet : excel Form for
HSSFRow : excel The line of
HSSFCell : excel The grid unit of
HSSFFont : excel typeface
HSSFDataFormat: Date format
HSSFHeader : sheet head
HSSFFooter : sheet tail ( You can only see the effect when you print it )
3.2.4 style
HSSFCellStyle : cell style
3.2.5 Auxiliary operations include :
HSSFDateUtil : date
HSSFPrintSetup : Print
HSSFErrorConstants : Error message table
3.2.6 xlsx Common components :
XSSFWorkbook : excel Document object for
XSSFSheet: excel Form for
XSSFRow: excel The line of
XSSFCell: excel The grid unit of
XSSFFont: excel typeface
XSSFDataFormat : Date format
3.2.7 Description of the common field type of the two components
In fact, the two components are aimed at excel Two formats of , Most of the operations are the same .
3.2.8 Operation steps
With HSSF For example ,XSSF Same operation .
First , Understand a Excel The organization form of the document , One Excel The file corresponds to a workbook(HSSFWorkbook), One workbook There can be multiple sheet(HSSFSheet) form , One sheet It's made up of many row(HSSFRow) form , One row It's made up of many cell(HSSFCell) form .
1、 use HSSFWorkbook Open or create “Excel File object ”
2、 use HSSFWorkbook Object returns or creates Sheet object
3、 use Sheet Object returns the row object , Get by row object Cell object
4、 Yes Cell Object reading and writing .
4、 Import / Upload code display
package com.example.demo.utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import static org.apache.poi.ss.usermodel.CellType.*;
import static org.apache.poi.ss.usermodel.CellType.NUMERIC;
/** * @author lvxu * @create 2022-07-10 13:30 */
public class PoiUtil {
private final static Logger logger = LoggerFactory.getLogger(PoiUtil.class);
private final static String xls = ".xls";
private final static String xlsx = ".xlsx";
/** * Read in excel file , After parsing, return * * @param file * @throws IOException */
public static List<String[]> readExcel(MultipartFile file) throws IOException {
// Check the documents
checkFile(file);
// get Workbook Workbook object
Workbook workbook = getWorkBook(file);
// Create return object , Take the values in each row as an array , All rows are returned as a collection
List<String[]> list = new ArrayList<String[]>();
if (workbook != null) {
// Go through each one workbook How many workbook objects sheet use workbook.getNumberOfSheets() This is the way to get sheet Number
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
// Get the current sheet Worksheet object
Sheet sheet = workbook.getSheetAt(sheetNum);
if (sheet == null) {
continue;
}
// Get the current sheet The beginning of the line
int firstRowNum = sheet.getFirstRowNum();
// Get the current sheet End line of
int lastRowNum = sheet.getLastRowNum();
// Loop all lines except the first one
for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
// Get the current line
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
// Get the start column of the current row
int firstCellNum = row.getFirstCellNum();
// Gets the number of columns in the current row
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
// Loop current line Traverse from the first column of the current row To the last column
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
workbook.close();
}
return list;
}
public static void checkFile(MultipartFile file) throws IOException {
// Judge whether the file exists
if (null == file) {
logger.error(" file does not exist !");
throw new FileNotFoundException(" file does not exist !");
}
// Get the filename
String fileName = file.getOriginalFilename();
// Determine if the document is excel file
if (!fileName.endsWith(xls) && !fileName.endsWith(xlsx)) {
logger.error(fileName + " No excel file ");
throw new IOException(fileName + " No excel file ");
}
// File format verification
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xLsx)")) {
throw new IOException(fileName + " No excel file ");
}
}
public static Workbook getWorkBook(MultipartFile file) {
// Get the filename
String fileName = file.getOriginalFilename();
// establish Workbook Workbook object , Represents the whole excel
Workbook workbook = null;
try {
// obtain excel Of documents io flow
InputStream is = file.getInputStream();
// Depending on the file suffix (xls and xlsx) Get different Workbook Implementation class object
if (fileName.endsWith(xls)) {
//2003
workbook = new HSSFWorkbook(is);
} else if (fileName.endsWith(xlsx)) {
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
logger.info(e.getMessage());
}
return workbook;
}
public static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// Think of numbers as String To read , Avoid 1 Read into 1.0 The situation of
if (cell.getCellType() == NUMERIC) {
cell.setCellType(STRING);
}
// Determine the type of data
switch (cell.getCellType()) {
case NUMERIC: // Numbers
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case STRING: // character string
cellValue = String.valueOf(cell.getStringCellValue());
break;
case BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA: // The formula
cellValue = String.valueOf(cell.getCellFormula());
break;
case BLANK: // Null value
cellValue = "";
break;
case ERROR: // fault
cellValue = " Illegal characters ";
break;
default:
cellValue = " Unknown type ";
break;
}
return cellValue;
}
}
Reference link :https://blog.csdn.net/xingxingmingyue/article/details/111468329
https://blog.csdn.net/weixin_43952697/article/details/107249935
https://blog.csdn.net/Smallextremely/article/details/121035673
边栏推荐
- mysql_ Record the executed SQL
- Concurrent programming day01
- Daily three questions 7.16
- Common Oracle commands
- Use unicloud cloud function to decode wechat motion steps in applet
- JS foundation -- regular expression
- Use reflection to convert RDD to dataframe
- Eslint error
- JS construction linked list
- Query the information of students whose grades are above 80
猜你喜欢

Resolve the error: org.apache.ibatis.binding.bindingexception

Reasons for not sending requests after uni app packaging

Stm32cubemx quadrature encoder

Tp5.1 login configuration method of whether to login public functions (complete login case)

Study notes of filebeat

Use pytest + allure to show the chart results (3)
![[Kali's sshd service is enabled]](/img/1b/180534d51049177254e30c4b783eba.png)
[Kali's sshd service is enabled]

Request and response

mysql_ Record the executed SQL
![[pyGame practice] nostalgic classic - do you remember the name of this chess game for children? (must collect)](/img/b3/075ad2d555118272efede5a9969319.png)
[pyGame practice] nostalgic classic - do you remember the name of this chess game for children? (must collect)
随机推荐
Vulntarget vulnerability shooting range -vulntarget-b
Banana pie bpi-m5 toss record (3) -- compile BSP
Go multiplexing
Learning record Xi
Ctfshow misc introduction
List.stream common operations
Hashcode details
C: wechat chat software instance (wpf+websocket+webapi+entityframework)
[stm32f103rct6] can communication
How to switch terminators in PostgreSQL?
mysql_ Case insensitive
Using one stack to sort another stack
Concurrent programming day01
What should I do when the interface encounters jsonstring
Details of happens before rules
Color space (1) - RGB
Dc-1-practice
Backtracking to solve subset problem
Jenkins plug-in development -- plug-in expansion
Beginners must see the markdown User Guide