java POI excel 導出復合樣式(一個單元格兩個字體)


前言:java poi 導出 excel 時,需要設置一個單元格有多個字體樣式,有點類似於富文本。

想要達到的效果(一個單元格里):

 

我使用的 poi 版本是

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>    

 

具體實現:

工具類方法:

/**
     * 設置值和樣式,富文本 復合樣式(一個單元格多個字體)
     * @param cell 當前單元格
     * @param wholeStr 整個字符串
     * @param strArray 字符串分割的數組
     * @param strFontList 字符串分割后一一對應的字體
     */
    public static void setRichTextCellValue(Cell cell, String wholeStr, String[] strArray, List<Font> strFontList){
        HSSFRichTextString hssfRichTextString = new HSSFRichTextString(wholeStr);
        int strLength = 0;
        for(int i = 0; i < strArray.length; i++){
            hssfRichTextString.applyFont(strLength, strLength + strArray[i].length(), strFontList.get(i));
            strLength = strArray[i].length();
        }
        cell.setCellValue(hssfRichTextString);
    }

設置第0行第0列的代碼:

        List<Font> strFontList = new ArrayList<>();
            strFontList.add(GenerateFontUtil.getRedFont(workbook));
            Font font = GenerateFontUtil.getCommonFont(workbook);
            font.setFontHeightInPoints((short) 14);
            strFontList.add(font);
            GenerateCellStyleUtil.setRichTextCellValue(sheet.getRow(0).getCell(0), "紅色字體 黑色字體"
                    , new String[]{"紅色字體", " 黑色字體"}, strFontList);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM