Java POI autosize columun

时间:2017-01-30 08:57:58

标签: java excel apache-poi autosize

对于我的项目,使用java和POI lib我创建了一个excel文件。 我有几张纸,还有很多不同的信息。对于一些我可以使用模板,只需插入数据。

但对于其他一些数据,我不知道我将获得的信息的长度。

我需要excel才能很好地呈现,所以我使用不同的样式,我的问题是自动调整大小:

    /**
 * Remplit les cellules d'un onglet
 * @param nomOnglet Le nom de l'onglet à remplir
 * @param cellules Les valeurs à insérer dans l'onglet
 * @throws TechniqueException
 */
private void remplirOnglet(HSSFWorkbook classeur, String nomOnglet, List<CelluleExport> cellules) throws TechniqueException {
    HSSFSheet onglet = classeur.getSheet(nomOnglet);
    if(onglet == null)
        onglet = classeur.createSheet(nomOnglet);
    int colMax = 0;
    for (CelluleExport cellule : cellules) {
        int idLigne = cellule.getRow()-1;
        int idColonne = cellule.getColumn()-1;
        colMax = Math.max(colMax, idColonne);
        HSSFRow ligne = onglet.getRow(idLigne);
        if(ligne == null)
            ligne = onglet.createRow(idLigne);
        HSSFCell poiCell = ligne.getCell(idColonne);
        if(poiCell == null)
            poiCell = ligne.createCell(idColonne);
        poiCell.setCellType(HSSFCell.CELL_TYPE_STRING);
        poiCell.setCellValue(cellule.getValeur());
        if(cellule.isStyled()) {
            applyStyle(cellule, poiCell);
            if(cellule.getStyleType().equals(CelluleExport.CELL_STYLE_TYPE.TITRE_BLOC))
                fusionnerDroite(onglet, cellule, 2);
        }
    }
    for(int i=0; i <= colMax; i++){
        onglet.autoSizeColumn(i, true);
    }
}

Auosize在大多数情况下工作正常。对于一些单元格,使用粗体或更大的字体,它不起作用。

有没有人知道避免这个问题的方法?我没有在网上找到任何东西,我认为这是lib的一个问题。

1 个答案:

答案 0 :(得分:0)

对于那些感兴趣的人,我通过在autoSize之后添加一个特定值来纠正了这个问题:

onglet.autoSizeColumn(i, true); 
onglet.setColumnWidth(i, onglet.getColumnWidth(i) + 3*256);

256表示一个字符的大小。

它并不完美,但它适用于大多数情况。