簡體   English   中英

為什么Apache POI中的文本格式不能與XSSF一起使用,而與HSSF一起使用?

[英]Why is text formatting in Apache POI not working with XSSF but HSSF?

我想通過使用Apache POI創建帶有一些標記的工作簿。

我嘗試使用更現代的XSSF軟件包來這樣做,但最終它們甚至不能用於最簡單的目的,例如更改顏色。

我給您我的Test類,您可以自己嘗試(只需在main方法中將xssf的調用更改為hssf)。

import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

import com.cisamag.projects.basiclibrary.logical.file.FileHelper;

public class Test {

private static File path = new File("pathtofile");

    public static void main(String[] args) throws IOException{
        xssf();
    }


    public static void xssf() throws IOException {
        File f = new File(path);
        if(f.exists()){
            f.delete();
        }
        f.createNewFile();

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();
        XSSFCell c = sheet.createRow(1).createCell(1);
        XSSFCellStyle cellStyle = c.getCellStyle();

        Font font = workbook.createFont();
        font.setItalic(true);
        font.setColor(Font.COLOR_RED);
        cellStyle.setFont(font);
        c.setCellStyle(cellStyle);
        c.setCellValue("HELLO");

        workbook.write(new FileOutputStream(f));
        Desktop.getDesktop().open(f);
    }

    public static void hssf() throws IOException {
        File f = new File(path);
        if(f.exists()){
            f.delete();
        }
        f.createNewFile();

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        HSSFCell c = sheet.createRow(1).createCell(1);
        HSSFCellStyle cellStyle = c.getCellStyle();

        Font font = workbook.createFont();
        font.setItalic(true);
        font.setColor(new HSSFColor.RED().getIndex());
        cellStyle.setFont(font);
        c.setCellStyle(cellStyle);
        c.setCellValue("HELLO");

        workbook.write(new FileOutputStream(f));
        Desktop.getDesktop().open(f);
    }
}

您需要首先創建CellStyle-在您的示例c.getCellStyle()返回默認的CellStyle(根據api docs ),顯然不能修改。

因此,更換

    XSSFCellStyle cellStyle = c.getCellStyle();

在你的例子中

    XSSFCellStyle cellStyle = workbook.createCellStyle();

它應該工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM