我想使用 Apache POI 创建一个带有一些标记的工作簿。
我尝试使用更现代的 XSSF 包来这样做,但最终它们甚至无法用于最简单的目的,例如更改颜色。
我给你我的测试类,你自己试试(只需在 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();
它应该可以工作。
关于java - 为什么 Apache POI 中的文本格式不适用于 XSSF 而适用于 HSSF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24656691/