Ali Baba EasyExcel use (2) - highlighting and merging cells

Continue the previous EasyExcel, this mission are: ① Highlight the cells of data specified row, ② merger specified cell.

The main part of the code ~ red

First, a cell style custom

public class CustomCellWriteHandler implements CellWriteHandler { 
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomCellWriteHandler.class);
    //标黄行宽集合
    private Set<Integer> yellowRowIndexs;

    //构造
    public CustomCellWriteHandler(Set<Integer> yellowRowIndexs) {
        this.yellowRowIndexs = yellowRowIndexs;
    }

    public CustomCellWriteHandler() {
    }

    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, 
Integer columnIndex, Integer relativeRowIndex, Boolean isHead) { LOGGER.info(
"beforeCellCreate~~~~"); } @Override public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) { LOGGER.info(
"afterCellCreate~~~~"); } @Override public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> cellDataList,
Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
// here may be made to any cell operation LOGGER.info ( "first row {}, {} the first column write to complete." , Cell.getRowIndex (), cell.getColumnIndex ()); IF (CollectionUtils.isNotEmpty (yellowRowIndexs) ) { the Workbook Workbook = writeSheetHolder.getSheet () GetWorkbook ();. the CellStyle CellStyle = workbook.createCellStyle (); // Font the Font cellFont = workbook.createFont (); cellFont.setBold ( to true ); cellStyle.setFont (cellFont); // marked yellow, to set together cellStyle.setFillPattern (FillPatternType.SOLID_FOREGROUND); // set the foreground fill pattern cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());//前景填充色 if (yellowRowIndexs.contains(cell.getRowIndex())) { cell.setCellStyle(cellStyle); } } } }

Second, the test method

 / ** 
     * written to the fixed file, highlight a line 
     * 
     * @throws IOException
      * / 
    @Test 
    public  void writeToExcelFile3 () {
         // Here a custom cell format (standard yellow highlighted line display) 
        Integer [] = {yellowRows. 3,. 5,. 7,. 9}; 
        the Set <Integer> = yellowRowsSet new new HashSet <> (Arrays.asList (yellowRows)); 
        CustomCellWriteHandler customCellWriteHandler = new new CustomCellWriteHandler (yellowRowsSet);

         // write text excel file 
        String fileName = "the I: \\ \\ writeDemo3.xlsx the TEMP" ;
         / * ------------------------------ division line ------------------------------ * / 
        // get header and content strategy
        HorizontalCellStyleStrategy = HorizontalCellStyleStrategy getHorizontalCellStyleStrategy (); 

        // column width strategy, the width is small units 
        Integer columnWidthArr [] = {3000, 3000, 2000, 6000 }; 
        List <Integer> = columnWidths has Arrays.asList (columnWidthArr); 
        CustomSheetWriteHandler customSheetWriteHandler = new new CustomSheetWriteHandler (columnWidths has); 

        // the field definitions derived from the 
        String [] = {filds "UID", "name", "Age", "Birthday" }; 

        String [] headers = { "unique identifier", "name "," age "," birthday " };

        Head List = getHeadByFilds (headers); 

        // Get the simulated data set entity
        List <the User> userList = getUserList (); 

        // specify the name of the head here to write, and then written to the first sheet, the name for the template file and then automatically shut down the flow 
        EasyExcel.write (fileName) 
                .head (head) 
                . registerWriteHandler (horizontalCellStyleStrategy) 
                .registerWriteHandler (customSheetWriteHandler) 
                // registration unit format 
                .registerWriteHandler (customCellWriteHandler) 
                .includeColumnFiledNames (Arrays.asList (filds)) 
                .sheet ( "template" ) 
                .doWrite (userList); 
    }

effect

 

 

 

Third, custom merged cell policy

/ ** 
 * from consolidation strategy definition, refer to the official documentation LoopMergeStrategy 
 * / 
public  class MyMergeStrategy the extends AbstractMergeStrategy {
     // consolidated set of coordinates 
    Private List <CellRangeAddress> cellRangeAddresss; 

    // constructor 
    public MyMergeStrategy (List <CellRangeAddress> cellRangeAddresss) {
         the this . = cellRangeAddresss cellRangeAddresss; 
    } 

    / ** 
     * Merge 
     * 
     * @param Sheet 
     * @param Cell 
     * @param head 
     * @paramrelativeRowIndex
      * / 
    @Override 
    protected  void Merge (Sheet Sheet, the Cell Cell, Head head, Integer relativeRowIndex) {
         // the merged cell 
        / ** 
         * **** add determination: if (cell.getRowIndex () == 1 && cell.getColumnIndex () == 0) {} **** 
         * to ensure that every cell be combined once, if not the above determination, as a cell is a cell operation, 
         * such as incorporating A2: A3, when the cell is A2, combined A2, A3, but when the cell as A3, is combined A2, A3, 
         * but this time A2, A3 is already a merged cell 
         * / 

        iF (CollectionUtils.isNotEmpty (cellRangeAddresss)) {
             iF ( cell.getRowIndex () && cell.getColumnIndex. 1 == () == 0) {
                 for (CellRangeAddress Item: cellRangeAddresss) { 
                    Sheet.addMergedRegionUnsafe(item);
                }
            }
        }
    }
}

To add here if (cell.getRowIndex () == 1 && cell.getColumnIndex () == 0) {} determination condition, or will be error, users have been described, can verify ~ 

 

Fourth, the test merge

  / ** 
     * analog merged cell location 
     * 
     * @return 
     * / 
    Private List <CellRangeAddress> () {getCellRangeAddresss 
        List <CellRangeAddress> List = new new the ArrayList <> ();
         // combined line. 4 
        CellRangeAddress ITEM1 = new new CellRangeAddress ( 3, 3, 0, 3 );
         // combined line 6 first and second columns 
        CellRangeAddress ITEM2 = new new CellRangeAddress (. 5,. 5, 0,. 1 );
         // combined and the line 9, line 10 
        CellRangeAddress = Item3 new new CellRangeAddress (10,. 11, 0,. 3 );

        list.add(item1);
        list.add(item2);
        list.add(item3);
        return list;

    }
  

/ ** * written to the fixed file, the merged cell * * @throws IOException * / @Test public void writeToExcelFile4 () { // definition of a coordinate range of the merged cell List <CellRangeAddress> cellRangeAddresss = getCellRangeAddresss (); // merge cells defined strategy myMergeStrategy myMergeStrategy = new new myMergeStrategy (cellRangeAddresss); // text file written to excel String fileName = "the I: \\ \\ writeDemo4.xlsx the TEMP" ; / * ---------- --------------------Dividing line---------------------------- - * / // here a custom cell format (standard yellow highlighted line display) Integer [] = {yellowRows. 3,. 5,. 7,. 9 }; the Set <Integer> = yellowRowsSet new new HashSet <> (Arrays.asList (yellowRows)); CustomCellWriteHandler customCellWriteHandler = new new CustomCellWriteHandler (yellowRowsSet); // Get header and content policy horizontalCellStyleStrategy horizontalCellStyleStrategy = getHorizontalCellStyleStrategy (); // column width strategy, the width is small units Integer columnWidthArr [] = {3000, 3000, 2000, 6000 }; List <Integer> = columnWidths has Arrays.asList (columnWidthArr); CustomSheetWriteHandler customSheetWriteHandler =new new CustomSheetWriteHandler (columnWidths has); // The custom fields derived String [] = {filds "UID", "name", "Age", "Birthday" }; String [] headers = { "unique identifier", " name "," age "," birthday " }; List head = getHeadByFilds (headers); // acquired analog data entity set List <the User> userList = getUserList (); // name of the head to write here, then written to the first sheet, the name for the template file and then automatically shut down the flow EasyExcel.write (fileName) .head (head) .registerWriteHandler (horizontalCellStyleStrategy) .registerWriteHandler (customSheetWriteHandler) // registration unit format .registerWriteHandler (customCellWriteHandler) // Register consolidation strategy .registerWriteHandler (myMergeStrategy) .includeColumnFiledNames (Arrays.asList (filds)) .sheet ( "template" ) .doWrite (userList); }

 

Effect (ps: bold border region is combined together manually to see the effect)

 

V. Summary

Today released financial systems, products and test version is being made - just a little spare time to good use ~

 

Guess you like

Origin www.cnblogs.com/coloz/p/12522229.html