赞
踩
xlsx
单元格中的富文本,注意不是 xls
,xls
的 api 不一样,试了很久没成功。斜体字
、上下标
,其它的实现方式应该类似。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"); } }
<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>
-----第1行----- 斜体内容为:猛虎 斜体内容为:蔷薇 -----第2行----- 上标内容为:-2 -----第3行----- 斜体内容为:U 斜体内容为:k -----第4行----- 斜体内容为:U 斜体内容为:rel 下标内容为:rel 斜体内容为:k
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。