当前位置:网站首页>Enterprise level development and use POI stepping on pit inventory

Enterprise level development and use POI stepping on pit inventory

2022-06-21 07:19:00 SteveCode.

Active address : Graduation season · The technique of attack er

  • Just two years after graduation ,2020.06-2022.06 Haha, I just graduated from the epidemic area . To tell you the truth, it was really difficult to find a job when I graduated . Many small businesses have closed down because of the epidemic ! Forget about the past

The code is confidential I won't write it all for you Different business scenarios . Use the method for reference !

Today is mainly about POI In this framework

First excel It is equivalent to the table data that cannot be found in our database . Field attributes corresponding to the header . The following data corresponds to each record in the database .

I won't say the basic usage ! Let's talk about the enterprise level development process , We will encounter all kinds of situation . Summary questions :

poi Three ways to set adaptive column widths

sheet.autoSizeColumn(i); ( The version cannot be too old )
sheet.autoSizeColumn(i, true);( Merged cells use )
sheet.setColumnWidth(i, “ Name ”.getBytes().length*2*256);( Chinese applicable )

POi Report errors 2:For input string: “null”

This problem usually results in an error , How to solve ?

  • Export process : Check the data in the database before exporting 、 In writing data into each cell .
if (CommUtil.notEquals("null", entry.getValue().toString())) {
    
                        cell.setCellValue(Double.valueOf(entry.getValue().toString()));
                    } else {
    
                        cell.setCellValue(0);
                    }

And so on . Just judge ···· It's rough

POi frame When importing, the cells are : Scientific counting (4.8e9)

        String content; 
        {
      //  value type :
  //  Fix scientific counting problem 
NumberFormat numberFormat = NumberFormat.getInstance();
content = numberFormat.format(cell.getNumericCellValue());
 if (content.indexOf(",") >= 0) {
    
 content = content.replace(",", "");
   }
 log.debug("handleRow: cell.getNumericCellValue(){}:{}",i,content);
            }

Center cell contents text type

    /** *  The cell content is centered   Text type  * @param wb * @return */
    private XSSFCellStyle setStyle(XSSFWorkbook wb) {
    
        XSSFCellStyle cellStyle = wb.createCellStyle();
        XSSFDataFormat dataFormat = wb.createDataFormat();
        // Text type 
        cellStyle.setDataFormat(dataFormat.getFormat("@"));
        // Centered around 
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        return cellStyle;
    }

Set the unit to : value type ( When making statements : More important )

    /** *  value type  * @param wb * @return */
    private XSSFCellStyle setStyle(XSSFWorkbook wb) {
    
        XSSFCellStyle cellStyle = wb.createCellStyle();
         cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
        return cellStyle;
    }

Tell you a secret

  • Format the cells first - Setting the cell type ! If it's the opposite , He won't take effect Ha ha ha ** Pay attention **
            //  Change to numerical type 
            cell.setCellStyle(hssfCellStyleDouble);
            //  Insert the formula into the total column 
            cell.setCellFormula(sumString);

How to write in a cell excel Function of

Here's an example Sum the total

        String colString;// The length is converted to ABC The last column 
    
        String sumString;// Summation formula 
        //  total 
        int totalColumn = 0;
        // Get the total number of columns 
        int cells = sheet.getRow(0).getPhysicalNumberOfCells();
        // Get the total number 
        int rowNum=sheet.getLastRowNum();
        //  Get the total line 
        XSSFRow xssfRow = sheet.createRow(1);
        XSSFCell cell = xssfRow.createCell(0);
        cell.setCellValue(" total :");
        //  Traverse each column 
        for (int i = totalColumn, size = cells; i < size; i++) {
    
            cell = xssfRow.createCell(i);
            // The length is converted to ABC Column 
            colString = CellReference.convertNumToColString(i);
            if (rowNum == 2) {
    
                sumString = "SUM(" + colString + "3"+")";
            } else {
    
                // Summation formula   seek  2  to   Total number of lines   Sum of cells 
                sumString = "SUM(" + colString + "3:" + colString + rowNum+1 + ")";
            }
            //  Change to numerical type 
            cell.setCellStyle(hssfCellStyleDouble);
            //  Insert the formula into the total column 
            cell.setCellFormula(sumString);
            totalColumn++;
        }

Cell settings drop-down

/** *  Set the drop-down box  * @param sheet  Appoint sheet page  * @param values  The value of the drop-down box  * @param firstRow  Start line number  * @param lastRow  Terminate line number  * @param firstCol  Starting column number  * @param lastCol  Terminate column number  */
    public static void setDropDownBox(XSSFSheet sheet, String[] values, Integer firstRow, Integer lastRow,
            Integer firstCol, Integer lastCol) {
    
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(
                values);
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
        // These two rows set that the cells can only be the contents of the list , Otherwise, the report will be wrong 
        validation.setSuppressDropDownArrow(true);
        validation.setShowErrorBox(true);
        sheet.addValidationData(validation);
    }

Import / export interface Try to use void Ha

Later I met bug I will continue to add and Tell us the solution

You can actually import and export data through reflection annotation solution . I will give you time later Publish a version

Active address : Graduation season · The technique of attack er

原网站

版权声明
本文为[SteveCode.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210711551762.html