我尝试使用RichTextString
来获取单个字符的字体,但是它仅对应用了至少一种不同样式的单元格有效。对于在整个单元格中应用相同样式的情况:
font1 = workbook.getFontAt(richString.getFontAtIndex(i))
在这里,richString.getFontAtIndex(i)
返回0,因此整个字体对象为空。
答案 0 :(得分:0)
以下代码适用于至少应用了一种不同样式的单元格。如果单元格具有相同的样式,richString对象将返回0,这将产生“空”字体对象
def fontStyles() {
String a="",styles="",value="",dummy="",newLine=""
int flag=0
Short[] rgb = new Short[3];
Font font1=null
HSSFFont font =null
InputStream inputStream = new FileInputStream("page.xls")
Workbook workbook = new HSSFWorkbook(inputStream)
HSSFSheet sheet = workbook.getSheetAt(0)
for(Row row:sheet) {
value=""
for(Cell cell:row) {
flag=0
value=""
RichTextString richString = cell.getRichStringCellValue()
println "richString ${richString}"
String string = richString.toString()
HSSFCellStyle cs = cell.getCellStyle()
println "richString.length() ${richString.length()}"
for(int i=0;i<richString.length();i++) {
newLine=""
println "${i} ${styles}"
font = workbook.getFontAt(richString.getFontAtIndex(i))
if(i<richString.length()-1) {
font1 = workbook.getFontAt(richString.getFontAtIndex(i+1))
} else {
font1 = workbook.getFontAt(richString.getFontAtIndex(i))
}
if(!(string.charAt(i).toString().equals(" "))){
HSSFPalette paletteIns = ((HSSFWorkbook)workbook).getCustomPalette()
HSSFColor color = paletteIns.getColor(font.getColor())
HSSFColor color1 = paletteIns.getColor(font1.getColor())
Short[] r = color.getTriplet()
rgb[0] = r[0]
rgb[1] = r[1]
rgb[2] = r[2]
if( (font.getItalic()) && (font.getUnderline()) ) {
dummy="<i><u>"+string.charAt(i).toString()+"</i></u>"
} else if(font.getItalic()) {
dummy="<i>"+string.charAt(i).toString()+"</i>"
} else if(font.getUnderline()) {
dummy="<u>"+string.charAt(i).toString()+"</u>"
} else {
dummy=string.charAt(i).toString()
}
if(string.charAt(i).toString().equals("\n")) {
flag=1;
newLine="<br>"
}
if( (font.getFontName().equals(font1.getFontName()))
&&(font.getFontHeightInPoints().equals(font1.getFontHeightInPoints()))
&&(Arrays.equals(color.getTriplet(),color1.getTriplet()))
&& (!(string.charAt(i).toString().equals("\n"))) ) {
value=value+dummy
}else {
styles="<span style=\"font-family:"+font.getFontName()+";font-size:"+font.getFontHeightInPoints()+"px;color:rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+");\">"+value+""+dummy+""+"</span>"+newLine
a=a+styles
value=""
flag=1
}
}else {
value=value+" "
}
}
if(flag==0) {
styles="<span style=\"font-family:"+font.getFontName()+";font-size:"+font.getFontHeightInPoints()+"px;color:rgb("+rgb[0]+","+rgb[1]+","+rgb[2]+");\">"+value+""+"</span>"+newLine
}
a=a+styles
}
}
render view:"excelToHTML", model:[str:a]
}
答案 1 :(得分:0)
if(richString.getFontAtIndex(i)==0){
font = workbook.getFontAt(cs.getFontIndex());
font1 = workbook.getFontAt(cs.getFontIndex());
} else {
font = workbook.getFontAt(richString.getFontAtIndex(i))
font1 = workbook.getFontAt(richString.getFontAtIndex(i))
}