[英]Why is text formatting in Apache POI not working with XSSF but HSSF?
I want to create a workbook with some markup by using Apache POI. 我想通过使用Apache POI创建带有一些标记的工作簿。
I tried to do so with the more modern XSSF packages but ended up with them not working for even the simpliest purposes like changing colors. 我尝试使用更现代的XSSF软件包来这样做,但最终它们甚至不能用于最简单的目的,例如更改颜色。
I give you my Test-class, to try it yourself (just change the call of xssf to hssf in the main method). 我给您我的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);
}
}
You need to create the CellStyle first - in your example c.getCellStyle()
returns the default CellStyle (according to the api docs ), which apparently cannot be modified. 您需要首先创建CellStyle-在您的示例c.getCellStyle()
返回默认的CellStyle(根据api docs ),显然不能修改。
So, replace 因此,更换
XSSFCellStyle cellStyle = c.getCellStyle();
in your example with 在你的例子中
XSSFCellStyle cellStyle = workbook.createCellStyle();
and it should work. 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.