当前位置:网站首页>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
![a3e87a41d6bd9fc93357d62a5a50336b.png](/img/40/9e4e3a7039ad1f647b3bedcc2a42b9.png)
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
![5aba8b47951ea4f9812414b34feac62b.png](/img/9b/657c521d66379cbf9eaa43b02b405d.png)
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
![f602bfd0d9c3c7b93a74a3c547d85b6a.png](/img/e5/590b68ae65edf411deeaa230f9068f.png)
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 ");
![8700dcd7106cd67078eee972fb513bca.png](/img/38/48e28cbadda5f89470d58af71fee60.png)
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 !
边栏推荐
- Crudini profile editing tool
- C language interview to write a function to find the first public string in two strings
- 哈趣投影黑马之姿,仅用半年强势突围千元投影仪市场!
- Symmetric binary tree [tree traversal]
- Rk3399 platform development series explanation (WiFi) 5.52. Introduction to WiFi framework composition
- Wechat applet hides the progress bar component of the video tag
- 直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级
- Redis(二)—Redis通用命令
- js装饰器@decorator学习笔记
- You don't know the complete collection of recruitment slang of Internet companies
猜你喜欢
Common problems of caching in high concurrency scenarios
Ideas of high concurrency and high traffic seckill scheme
Markdown displays pictures side by side
Ha Qu projection dark horse posture, only half a year to break through the 1000 yuan projector market!
当我们谈论不可变基础设施时,我们在谈论什么
开发者别错过!飞桨黑客马拉松第三期链桨赛道报名开启
Handling hardfault in RT thread
3428. Put apples
你不知道的互联网公司招聘黑话大全
地质学类比较有名的外文期刊有哪些?
随机推荐
MySQL(十)
Postgresql中procedure支持事务语法(实例&分析)
Ant manor safety helmet 7.8 ant manor answer
Symmetric binary tree [tree traversal]
C面试24. (指针)定义一个含有20个元素的double型数组a
Find duplicate email addresses
JVM in-depth
Qtthread, one of many methods of QT multithreading
【OpenCV】形态学滤波(2):开运算、形态学梯度、顶帽、黑帽
Postgresql源码(59)分析事务ID分配、溢出判断方法
基本Dos命令
C语言面试 写一个函数查找两个字符串中的第一个公共字符串
ST表预处理时的数组证明
ICML 2022 | 探索语言模型的最佳架构和训练方法
Redisl garbled code and expiration time configuration
693. Travel sequencing
Test the foundation of development, and teach you to prepare for a fully functional web platform environment
Three updates to build applications for different types of devices | 2022 i/o key review
VIM mapping large K
Audio distortion analysis of DSP and DAC based on adau1452