【环境】
poi-ooxml 4.0.1、java 8
【核心代码】
XSSFRichTextString value = new XSSFRichTextString("红色黑色");
value.applyFont(0, 2, redFont);
【完整代码】
package excel.write;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRichTextTest {
public static void main(String[] args) {
String filePath =
"E:\\tmp\\test\\excelTest\\richText_" + System.currentTimeMillis() + ".xlsx";
File folder = new File(filePath.substring(0, filePath.lastIndexOf(File.separator)));
if (!folder.exists()) {
folder.mkdirs();
}
Workbook wb = null;
FileOutputStream out = null;
try {
wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
XSSFRichTextString value = new XSSFRichTextString("红色黑色");
Font redFont = wb.createFont();
redFont.setColor(Font.COLOR_RED);
redFont.setBold(true);
redFont.setFontName("宋体");
// 给[0, 2)位置设置以上格式
value.applyFont(0, 2, redFont);
Font blackFont = wb.createFont();
blackFont.setColor(Font.COLOR_NORMAL);
blackFont.setBold(true);
blackFont.setFontName("宋体");
value.applyFont(2, value.length(), blackFont);
cell.setCellValue(value);
out = new FileOutputStream(filePath);
wb.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (wb != null) {
wb.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
【效果】
【说明】
Excel显示的效果确实为红色+宋体,但是在字体属性这一块显示的是默认的,双击单元格后字体属性就显示正常了。
做了双击单元格操作之后,点击关闭Excel,会提示是否要保存,选择保存,然后再次打开Excel,字体属性这一块就显示对了。
【猜测】
有可能是POI写的Excel文件内部格式和软件写的不同,打开软件后的字体属性未能正确读取到这些格式(但显示是对的),然后双击单元格后,软件应该修改了Excel文件内部的格式,保存后就能正常读取了。