当前位置:网站首页>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 !
边栏推荐
- "Parse" focalloss to solve the problem of data imbalance
- Handling hardfault in RT thread
- c面试 加密程序:由键盘输入明文,通过加密程序转换成密文并输出到屏幕上。
- 隐马尔科夫模型(HMM)学习笔记
- Wechat applet hides the progress bar component of the video tag
- C language (structure) defines a user structure with the following fields:
- MySQL(十)
- 谷歌 Chrome 浏览器发布 103.0.5060.114 补丁修复 0-day 漏洞
- 缓存在高并发场景下的常见问题
- 计算模型 FPS
猜你喜欢
Jmeter自带函数不够用?不如自己动手开发一个
软件测试的几个关键步骤,你需要知道
Experience sharing of contribution of "management world"
Markdown 并排显示图片
JMeter's own functions are not enough? Why don't you develop one yourself
线性代数(一)
Redis(一)——初识Redis
进程间通信之共享内存
Developers don't miss it! Oar hacker marathon phase III chain oar track registration opens
Haqi projection Black Horse posture, avec seulement six mois de forte pénétration du marché des projecteurs de 1000 yuans!
随机推荐
Symmetric binary tree [tree traversal]
C interview encryption program: input plaintext by keyboard, convert it into ciphertext through encryption program and output it to the screen.
程序员的日常 | 每日趣闻
线性代数(一)
当我们谈论不可变基础设施时,我们在谈论什么
谷歌 Chrome 浏览器发布 103.0.5060.114 补丁修复 0-day 漏洞
jmeter 函数助手 — — 随机值、随机字符串、 固定值随机提取
[solution] final app status- undefined, exitcode- 16
ETCD数据库源码分析——从raftNode的start函数说起
Google Chrome browser released patch 103.0.5060.114 to fix the 0-day vulnerability
Redis (II) - redis General Command
Markdown displays pictures side by side
博士申请 | 上海交通大学自然科学研究院洪亮教授招收深度学习方向博士生
VIM mapping large K
How can I check the DOI number of a foreign document?
Several key steps of software testing, you need to know
可极大提升编程思想与能力的书有哪些?
你不知道的互联网公司招聘黑话大全
Party A's requirements for those who have lost 800 yuan
Doctoral application | Professor Hong Liang, Academy of natural sciences, Shanghai Jiaotong University, enrolls doctoral students in deep learning