当前位置:网站首页>POI framework learning - Import and export cases
POI framework learning - Import and export cases
2022-07-16 07:45:00 【Yi Tianyu】
Catalog
3、 ... and Case study ( Import and export )
3.3 Export case ( Return to file flow mode )
3.4 Export case ( return URL The way )
One POI brief introduction
Apache POI Yes, it is Java Write free open source cross platform Java API,Apache POI Provide API to Java Program pair Microsoft Office Format file reading and writing functions . It is a popular import and Export excel frame .
Official website :Apache POI - the Java API for Microsoft Documentshttps://poi.apache.org/
Two Row limit
HSSFWorkbook:
shortcoming : At most The reason is 65536 That's ok , Otherwise, it will throw the exception
advantage : Write cache in process , Do not operate disk , Finally, inhale the disk at one time , Fast
XSSFWorkbook: Maximum data :1048576 That's ok ,16384 Column ,
shortcoming : When writing data Very slow , Very memory intensive , Memory overflow can also occur , Such as 100 Ten thousand .
advantage : Can write Large amount of data , Such as 20 Ten thousand .
SXSSFWorkbook:
advantage : Can write a very large amount of data , Such as 100 Ten thousand or more data can be written quickly , Take up less memory
Be careful :
- In the process
Produce temporary documents, Need to clean up temporary filesDefault by 100 Records are stored in memory, If it's more than that , The first data is written to the temporary file- If you want to customize the amount of data in memory , have access to
new SXSSFWorkbook( Number )
3、 ... and Case study ( Import and export )
3.1 Import dependence
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.0</version>
</dependency>
3.2 Import case
controller entrance :
@PostMapping("import")
public Response importRepayReconciliate(MultipartFile file,HttpServletRequest request){
try {
// Determine if the file is empty
if (!file.isEmpty()) {
// File save path
String message = repayService.import(file.getInputStream(),request);
return new Response(MessageConstants.MSG_SUCCESS, null, null);
} else {
return new Response(MessageConstants.MSG_SYS_ERROR, null, " The file is empty , Please upload the file !");
}
} catch (Exception e) {
log.error(" operation failed , Please contact the system administrator !",e,e.getMessage());
return new Response(MessageConstants.MSG_SYS_ERROR, null, e.getMessage());
}
}
service class :
Workbook book = WorkbookFactory.create(inputStream); // Create Workbook
Sheet sheet = book.getSheetAt(0);// Get worksheet
int lastRowNum = sheet.getLastRowNum();// Get the last row of the table
if (lastRowNum < 1 ) {
return " You have not imported any data , Please add data and import ...";
}
Row row = sheet.getRow(2);
Cell cell = row.getCell(1);
String type = cell.getStringCellValue();row = sheet.getRow(i);
cell = row.getCell(1);
cell.setCellType(CellType.STRING);// Get cell values ( Important for text )
String value = new DataFormatter().formatCellValue(cell);
3.3 Export case ( Return to file flow mode )
Summary of key words :
The way 1:
HSSFWorkbook book = new HSSFWorkbook(); // There is a limit on the number of rows Not greater than 65536 That's ok
HSSFSheet sheet = book.createSheet();The way 2:
XSSFWorkbook book = new XSSFWorkbook(); // There is no line limit
XSSFSheet sheet = book.createSheet();The way 3:
SXSSFWorkbook book = new SXSSFWorkbook();// There is no line limit Do not occupy memory ( Universal )
book.setCompressTempFiles(true); // Open the compression configuration itemXSSFRow titleRow = sheet.createRow(0);
// Set cell width
sheet.setColumnWidth(i, 2000);.....
book.write(out);
response.flushBuffer();
book.dispose(); // Temporary files need to be explicitly deleted manually , call dispose Method that will do
out.close();
book.close();
Style management :
The style of a HSSF
HSSFCellStyle cellStyle = book.createCellStyle();
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// Set the following
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// Set left
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// Set right
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// Set the top
cellStyle.setWrapText(true); // Set auto wrap
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// Horizontal center
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// Vertical center
Style 2 -SXSSFWorkbook
CellStyle cellStyle = book.createCellStyle();
cellStyle.setBorderBottom(BorderStyle.THIN); // Under the frame
cellStyle.setBorderLeft(BorderStyle.THIN);// The left margin
cellStyle.setBorderTop(BorderStyle.THIN);// On the border
cellStyle.setBorderRight(BorderStyle.THIN);// Right margin
cellStyle.setWrapText(true); // Set auto wrap
cellStyle.setAlignment(HorizontalAlignment.CENTER);// Set the horizontal center of the cell
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// Set the vertical center of the cell
merge cell Start line End line Start column End column
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 3));
Set the font
HSSFFont font = book.createFont();
font.setBold(true);// Set bold
font.setFontHeightInPoints((short) 18);// Set font size
font.setFontName(" In black ");// Set the font
font.setColor(Font.COLOR_RED);// Set font color
cellStyle.setFont(font);// Apply fonts to styles
Clone style :
HSSFCellStyle cellStyle2 = book.createCellStyle();
cellStyle2.cloneStyleFrom(cellStyle);// Clone the previous style
Bank management :
HSSFRow row = sheet.createRow(0);
row.setHeightInPoints(50); // Set row height
Column management :
HSSFCell cell = row.createCell(0);
cell.setCellValue(" Comprehensive test "); // Set the value of the column
cell.setCellStyle(cellStyle); // Apply styles to each cell
controller entrance :
@RequestMapping(params = "enterpriseBaseInfoExport")
public void export(JSONObject data,HttpServletRequest request, HttpServletResponse response) {
try {
String fileName = "XXX.xls";
response.setHeader("content-disposition","attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
ServletOutputStream out = response.getOutputStream();
dataService.export(data,out);
} catch (Exception e) {
logger.error(" The reason for the export error is :" + e.getMessage());
e.printStackTrace();
}
}
service Common export methods :
3.4 Export case ( return URL The way )
String fileName = UUID.randomUUID().toString().replace("-","");
String path = request.getSession().getServletContext().getRealPath(File.separator) + File.separator +
"upload" + File.separator + "download" + File.separator;
File file = new File(path);
if (!file.exists()) {
file.mkdir();
}
fileName = fileName + ".xlsx";
String filePath = path + fileName;
FileOutputStream out = new FileOutputStream(filePath);
book.setCompressTempFiles(true);
book.write(out);
out.close();
response.flushBuffer();
book.dispose(); // Temporary files need to be explicitly deleted manually , call dispose Method that will do
}
3.5 Load template export
Template location :

XSSFWorkbook wb = new XSSFWorkbook(POIUtil.getInputStream("/statistic/download_template/excel/first_loan_info.xlsx"));
SXSSFWorkbook book = new SXSSFWorkbook(wb);
Sheet sheet = book.getSheetAt(0);
book.setCompressTempFiles(true);
public static InputStream getInputStream(String filePath) throws Exception{
ClassPathResource classPathResource = new ClassPathResource(filePath);
if(!classPathResource.exists()){
throw new RuntimeException(" file does not exist :{}"+filePath);
}
return classPathResource.getInputStream();
}边栏推荐
猜你喜欢

1、 Disk data recovery experiment report

VLAN and trunnk

Is it reliable to switch to software testing at the age of 30? The mental journey of a person who came here is for you who are confused

数制转换与子网划分

TCP协议详解

POI框架学习-导入导出案例

最长上升子序列 最长公共子序列 最大字段和 最长不重复子串

to flash back

回溯

Obtaining control coordinates and control properties in appium
随机推荐
appium中desired_caps参数记录
[sword finger offer] special summary of linked list
“挤破脑袋进的腾讯,你凭什么要辞职?”
help one another in defense work
Flask基础入门七-Cookie和Session
2021/12/12 attack and defense world crypto question making record
Code quality inspection based on sonarqube
Flink on Yan ha mode construction problem
[software quality assurance notes] software quality assurance
从软件测试培训班出来之后找工作的经历,教会了我这五件事...
【LeetCode】2024. The most perplexing degree of examination
30岁转行软件测试靠谱吗?一个过来人的心路历程送给迷茫的你
作为测试开发岗的面试官,我都是怎么选人的?
"Why do you want to resign, Tencent, which broke its head?"
Pytest系列-01-安装与入门
Recursion in binary tree
Minimum cycle section in KMP
【LeetCode】307. 区域和检索 - 数组可修改
测试人的职场危机是35岁?不是,而是中年被裁!
回溯