java Apache POI 设置单元格字体和字体颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10630677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:54:01  来源:igfitidea点击:

Apache POI set cell Font and font color

javaapache-poi

提问by Lalit Chattar

I am reading an xlsxfile using XSSF of Apache POI. When reading the font of a particular cell and applying in new cell that font is applied for the whole sheet not for that perticular cell. i want for Example:

我正在xlsx使用 Apache POI 的 XSSF读取文件。当读取特定单元格的字体并在新单元格中应用该字体时,该字体应用于整个工作表而不是该特定单元格。我想要例如:

        column1 column2      column3 
row1    ARIAL   TIMES ROMAN  ARIAL

row2    TIMES ROMAN ARIAL   ARIAL   

row3     ARIAL   ARIAL   ARIAL   

I want the same font in each cell that was in original file.

我希望在原始文件中的每个单元格中使用相同的字体。

My code is:

我的代码是:

public XSSFCellStyle setFontOnCell(XSSFCellStyle cellStyle, XSSFCell cell)
    {
        try {
            font = cell.getCellStyle().getFont();
            new_font.setFontName(font.getFontName());
            new_font.setBoldweight(font.getBoldweight());
            new_font.setFontHeight((short)font.getFontHeight());
            new_font.setFamily(font.getFamily());
            cellStyle.setFont(new_font);
            return cellStyle;
        } catch (Exception e) {
            //System.out.println(e.getMessage());
            return cellStyle;
        }
    }

采纳答案by Kilian Foth

Your new_fontseems to be a global variable, and you keep changing it and then injecting it into cells. It should be local to setFontOneCell()so that each cell gets its own Fontinstance, instead of all of them actually using the same object,

new_font似乎是一个全局变量,您不断更改它然后将其注入到单元格中。它应该是本地的,setFontOneCell()以便每个单元格都有自己的Font实例,而不是所有单元格实际上都使用相同的对象,