当前位置:网站首页>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 20pxBe 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);
CellRangeAddresssource :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 !边栏推荐
- Basic DOS commands
- C language interview to write a function to find the first public string in two strings
- dolphinscheduler3.x本地启动
- string(讲解)
- C language (structure) defines a user structure with the following fields:
- vim映射大K
- [SOC FPGA] peripheral PIO button lights up
- 软件测试的几个关键步骤,你需要知道
- ST表预处理时的数组证明
- 力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)
猜你喜欢

Open the blue screen after VMware installation

go-microservice-simple(2) go-Probuffer

Etcd database source code analysis -- starting from the start function of raftnode

Markdown displays pictures side by side
![[FPGA] EEPROM based on I2C](/img/28/f4f2efda4b5feb973c9cf07d9d908f.jpg)
[FPGA] EEPROM based on I2C

tkinter窗口选择pcd文件并显示点云(open3d)

线性代数(一)

力扣62 不同路径(从矩阵左上到右下的所有路径数量) (动态规划)

Which foreign language periodicals are famous in geology?

HKUST & MsrA new research: on image to image conversion, fine tuning is all you need
随机推荐
Crudini profile editing tool
[Shell]常用shell命令及测试判断语句总结
Ideas of high concurrency and high traffic seckill scheme
Markdown 并排显示图片
C interview 24 (pointer) define a double array with 20 elements a
Overview of FlexRay communication protocol
如何解决数据库插入数据显示SQLSTATE[HY000]: General error: 1364 Field ‘xxxxx‘ doesn‘t have a default value错误
win系统下安装redis以及windows扩展方法
How to set up in touch designer 2022 to solve the problem that leap motion is not recognized?
线性代数(一)
进程间通信之共享内存
Audio distortion analysis of DSP and DAC based on adau1452
Basic DOS commands
直击2022ECDC萤石云开发者大会:携手千百行业加速智能升级
港科大&MSRA新研究:关于图像到图像转换,Fine-tuning is all you need
Tkinter window selects PCD file and displays point cloud (open3d)
Laravel uses Tencent cloud cos5 full tutorial
Experience of Niuke SQL
C语言整理(待更新)
C language sorting (to be updated)