当前位置:网站首页>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

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);
  1. 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

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 ):

  1. 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 , Just map.put(i, list.add(length)), And then use Collections.max(map.get(i)) To get the first i The longest length of the column

  2. Still 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

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

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 !
原网站

版权声明
本文为[Java notes shrimp]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070152078160.html