当前位置:网站首页>POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
POI export to excel: set font, color, row height adaptation, column width adaptation, lock cells, merge cells
2022-07-07 06:32:00 【Java notes shrimp】
Click on the official account , utilize Fragment time to learn
1. Preface
poi The framework can support us in java In the code , Export data to excel , In actual development , It is often necessary to set excel typeface , Color , Row height , Column width and other attributes , Sometimes you need to lock cells , Prevent others from tampering with data at will .
I don't say much nonsense , Go straight to the code
2. Lock cell
export excel , Naturally, there is excel 了 , For example, export some data , Modify some and import them , But at this moment , We don't want users to modify some basic information at will , It's here excel Lock of
sheet.protectSheet( password )
Code :
// establish Excel file
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(DateUtils.getDate("yyyyMMdd"));
// lock sheet
sheet.protectSheet("zgd");
In this case , This sheet Will be locked in
But we also want to open some cells that can be modified , At this time, fine-grained settings are required
Create a cellStyle:
CellStyle unlockCell = workbook.createCellStyle();
unlockCell.setLocked(false);
Then on cells we don't need to lock , Give it this cellStyle
// Set up dataRow At the end of the line i Cells are not locked
dataRow.getCell(i).setCellStyle(unlockCell);
Set column width It's locked in sheet after , There's a problem , Even the column width can't be changed
I can't help it at this time , You can only set the column width by yourself , Now there are several methods to set column width found on the Internet :
1. Adaptive column width :
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(1, true);
Both methods are adaptive column width , But note that this method is only available in later versions ,poi Don't be too old . Be careful : The first method does not work well when merging cells , The second method must be used .
After testing , This adaptive api When encountering data with a little more rows , It will take a lot of time ,1000 All right, it's time 2 minute !!! So try not to use
sheet.trackAllColumnsForAutoSizing();
sheet.autoSizeColumn(i);
And these two methods are good for English numbers , Support for Chinese is not good : See the picture
2. Set the approximate width with an array , Manual set Width
int[] width = {xxx,xxx};
for loop
sheet.setColumnWidth(i,width[i]);
3. Set the width according to the longest string length in a column of data
So you still have to take care of yourself diy :
Determine the longest string in this column , then
int length = str.getBytes().length;
sheet.setColumnWidth((short) Number of columns ,(short)(length*256));
Here, after my repeated attempts , Personally, I think the maximum width is limited to 10000 To 15000 Left and right is more appropriate , Then leave the rest to excel Word wrap for
Like me, there are many lines of data , I don't know which line is the longest , Here are two simple ideas ( There are many ways , If you can achieve your goal ):
Use one
Map<Integer, List>
, key Which column does it refer to , List The length of the contents of this column in each row , One column per row , Justmap.put(i, list.add(length))
, And then useCollections.max(map.get(i))
To get the first i The longest length of the columnStill the same , Use one map:
Map<Integer, Integer>
,key Which column does it refer to ,value Is the length of the contents of this column in each row ,map.put(i,Math.max(length,map.get(i)))
, To make sure that map Medium key Corresponding value Always the maximum length at present .
The second one I use here :
After setting auto wrap , Do not set a fixed row height , Otherwise, the excess will also be covered and not displayed
// establish Excel file
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet");
// Set the style
CellStyle blackStyle = workbook.createCellStyle();
// Word wrap * important *
blackStyle.setWrapText(true);
// Store the maximum column width
Map<Integer,Integer> maxWidth = new HashMap<>();
// Title Line
HSSFRow titleRow = sheet.createRow(0);
titleRow.setHeightInPoints(20);// The purpose is to set the row height to 20px
titleRow.createCell(0).setCellValue("sku Number ");
titleRow.createCell(1).setCellValue(" Commodity title ");
titleRow.createCell(2).setCellValue(" Trade name ");
// Initialize the column width of the title , typeface
for (int i= 0; i<=3;i++){
maxWidth.put(i,titleRow.getCell(i).getStringCellValue().getBytes().length * 256 + 200);
titleRow.getCell(i).setCellStyle(blackStyle);// Set auto wrap
}
for (Map<String, Object> map : list) {
int currentRowNum = sheet.getLastRowNum() + 1;
// data row
HSSFRow dataRow = sheet.createRow(currentRowNum);
// Record the length of each column of this row
List<Object> valueList = new ArrayList<Object>();
String val0 = map.get("skuId") == null ? "—" : ((Double) (map.get("skuId"))).intValue()+"";
valueList.add(val0);
dataRow.createCell(0).setCellValue(val0);
String val1 = map.get("title") == null ? "" : map.get("title").toString();
valueList.add(val1);
dataRow.createCell(1).setCellValue(val1);
String val2 = map.get("goodsName") == null ? "" : map.get("goodsName").toString();
valueList.add(val2);
dataRow.createCell(2).setCellValue(val2);
String val3 = map.get("catName") == null ? "" : map.get("catName").toString();
valueList.add(val3);
dataRow.createCell(3).setCellValue(val3);
String val4 = map.get("brandName") == null ? "" : map.get("brandName").toString();
for(int i = 0;i<=3;i++){
int length = valueList.get(i).toString().getBytes().length * 256 + 200;
// Here, the maximum width is limited to 15000
if (length>15000){
length = 15000;
}
maxWidth.put(i,Math.max(length,maxWidth.get(i)));
dataRow.getCell(i).setCellStyle(blackStyle);// Set auto wrap
}
}
for (int i= 0; i<=3;i++){
// Set column width
sheet.setColumnWidth(i,maxWidth.get(i));
}
Now, , Although the column width is relatively stiff, it is set by applying the content length , But it's much better than before , The column width cannot exceed 256*256
Of , Otherwise, an error will be reported , So the maximum column width I set here is 15000, The excess will wrap automatically
4. Set row height
It's easy to be tall ,
titleRow.setHeightInPoints(20);// The purpose is to set the row height to 20px
Be careful , Fixed row height is set , Auto wrap will not adapt to the row height
5. Set the font , Color
establish CellStyle , Then create HSSFFont , And then HSSFFont Inject into CellStyle , In the CellStyle to cell Set up
// Set the font
CellStyle redStyle = workbook.createCellStyle();
HSSFFont redFont = workbook.createFont();
// Color
redFont.setColor(Font.COLOR_RED);
// Set font size
redFont.setFontHeightInPoints((short) 10);
// typeface
//redFont.setFontName(" Song style ");
redStyle.setFont(redFont);
HSSFCell cell13 = titleRow.createCell(13);
cell13.setCellStyle(redStyle);
cell13.setCellValue(" Be careful : Only the sales price can be modified , Supply price , Market price and inventory ");
6. merge cell
If you merge cells , It is recommended to merge , After the merger , In the first row and first column of the merge set The value will do
// Here stands for in the 0 OK, let's start , To 0 End of line , from 0 Column start , To 10 End of column , A merger , That is, merge the second 0 Yes 0-10 A cell
CellRangeAddress cellRange1 = new CellRangeAddress(0, 0, (short) 0, (short) 10);
sheet.addMergedRegion(cellRange1);
CellRangeAddress
source :zzzgd.blog.csdn.net/article/details/80627175
recommend :
The most comprehensive java Interview question bank
PS: Because the official account platform changed the push rules. , If you don't want to miss the content , Remember to click after reading “ Looking at ”, Add one “ Star standard ”, In this way, each new article push will appear in your subscription list for the first time . spot “ Looking at ” Support us !
边栏推荐
- Ant manor safety helmet 7.8 ant manor answer
- 693. Travel sequencing
- 怎样查找某个外文期刊的文献?
- Postgresql源码(60)事务系统总结
- A very good JVM interview question article (74 questions and answers)
- Software testing knowledge reserve: how much do you know about the basic knowledge of "login security"?
- postgresql 数据库 timescaledb 函数time_bucket_gapfill()报错解决及更换 license
- How to solve sqlstate[hy000]: General error: 1364 field 'xxxxx' doesn't have a default value error
- Qtthread, one of many methods of QT multithreading
- Google Chrome browser released patch 103.0.5060.114 to fix the 0-day vulnerability
猜你喜欢
Redis(二)—Redis通用命令
LM small programmable controller software (based on CoDeSys) Note 23: conversion of relative coordinates of servo motor operation (stepping motor) to absolute coordinates
线性代数(一)
rt-thread 中对 hardfault 的处理
MySQL卸载文档-Windows版
基于FPGA的VGA协议实现
Matlab / envi principal component analysis implementation and result analysis
[SOC FPGA] peripheral PIO button lights up
学习笔记|数据小白使用DataEase制作数据大屏
基于ADAU1452的DSP及DAC音频失真分析
随机推荐
POI导出Excel:设置字体、颜色、行高自适应、列宽自适应、锁住单元格、合并单元格...
When we talk about immutable infrastructure, what are we talking about
ceres-solver和g2o性能比较
进程间通信之共享内存
【从零开始】win10系统部署Yolov5详细过程(CPU,无GPU)
C语言面试 写一个函数查找两个字符串中的第一个公共字符串
Rk3399 platform development series explanation (WiFi) 5.52. Introduction to WiFi framework composition
ST表预处理时的数组证明
哈趣投影黑馬之姿,僅用半年强勢突圍千元投影儀市場!
拼多多败诉:“砍价免费拿”侵犯知情权但不构成欺诈,被判赔400元
雷特智能家居龙海祁:从专业调光到全宅智能,20年专注成就专业
Postgresql源码(59)分析事务ID分配、溢出判断方法
vim映射大K
力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
[solution] final app status- undefined, exitcode- 16
The difference between string constants and string objects when allocating memory
A program lets you understand what static inner classes, local inner classes, and anonymous inner classes are
2022 Android interview essential knowledge points, a comprehensive summary
Oracle迁移中关于大容量表使用数据泵(expdp、impdp)导出导入容易出现的问题和注意事项
Shared memory for interprocess communication