1. 总体介绍
- 该方法是解析
xlsx
单元格中的富文本,注意不是 xls
,xls
的 api 不一样,试了很久没成功。
- 只实现了解析
斜体字
、上下标
,其它的实现方式应该类似。
2. 具体实现
2.1 代码
package util;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelItalic {
public static void cell(XSSFCell cell) {
XSSFRichTextString rts = cell.getRichStringCellValue();
String value = rts.getString();
int size = rts.numFormattingRuns();// 该富文本使用的格式的数量
for (int i = 0; i < size; i++) {
XSSFFont font = rts.getFontOfFormattingRun(i);// 该格式对应的字体
if (font == null) {
continue;
}
// 斜体
if (font.getItalic()) {// 字体是斜体
int start = rts.getIndexOfFormattingRun(i);// 该格式在该富文本的起始位置索引
int length = rts.getLengthOfFormattingRun(i);// 该格式在该富文本覆盖的字符长度
if (length > 0) {
System.out.println("斜体内容为:" + value.substring(start, start + length));
}
}
short tos = font.getTypeOffset();
// 上标
if (Font.SS_SUPER == tos) {
int start = rts.getIndexOfFormattingRun(i);// 该格式在该富文本的起始位置索引
int length = rts.getLengthOfFormattingRun(i);// 该格式在该富文本覆盖的字符长度
if (length > 0) {
System.out.println("上标内容为:" + value.substring(start, start + length));
}
}
// 下标
if (Font.SS_SUB == tos) {
int start = rts.getIndexOfFormattingRun(i);// 该格式在该富文本的起始位置索引
int length = rts.getLengthOfFormattingRun(i);// 该格式在该富文本覆盖的字符长度
if (length > 0) {
System.out.println("下标内容为:" + value.substring(start, start + length));
}
}
}
}
public static void wb(String path) {
XSSFWorkbook wb = null;
InputStream input = null;
try {
input = new FileInputStream(path);
wb = new XSSFWorkbook(input);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
}
}
}
XSSFSheet sheet = wb.getSheetAt(0);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
System.out.println("\n-----第" + (i + 1) + "行-----");
XSSFRow row = sheet.getRow(i);
for(int j = 0; j < row.getLastCellNum(); j++){
cell(row.getCell(j));
}
}
}
public static void main(String[] args) {
wb("D:\\test\\1.xlsx");
}
}
2.2 依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
2.3 excel内容
2.4 输出
-----第1行-----
斜体内容为:猛虎
斜体内容为:蔷薇
-----第2行-----
上标内容为:-2
-----第3行-----
斜体内容为:U
斜体内容为:k
-----第4行-----
斜体内容为:U
斜体内容为:rel
下标内容为:rel
斜体内容为:k