use of org.apache.poi.ss.usermodel.RichTextString in project poi by apache.
the class SheetUtil method getCellWidth.
/**
* Compute width of a single cell
*
* @param cell the cell whose width is to be calculated
* @param defaultCharWidth the width of a single character
* @param formatter formatter used to prepare the text to be measured
* @param useMergedCells whether to use merged cells
* @return the width in pixels or -1 if cell is empty
*/
public static double getCellWidth(Cell cell, int defaultCharWidth, DataFormatter formatter, boolean useMergedCells) {
Sheet sheet = cell.getSheet();
Workbook wb = sheet.getWorkbook();
Row row = cell.getRow();
int column = cell.getColumnIndex();
// FIXME: this looks very similar to getCellWithMerges below. Consider consolidating.
// We should only be checking merged regions if useMergedCells is true. Why are we doing this for-loop?
int colspan = 1;
for (CellRangeAddress region : sheet.getMergedRegions()) {
if (region.isInRange(row.getRowNum(), column)) {
if (!useMergedCells) {
// If we're not using merged cells, skip this one and move on to the next.
return -1;
}
cell = row.getCell(region.getFirstColumn());
colspan = 1 + region.getLastColumn() - region.getFirstColumn();
}
}
CellStyle style = cell.getCellStyle();
CellType cellType = cell.getCellTypeEnum();
// for formula cells we compute the cell width for the cached formula result
if (cellType == CellType.FORMULA)
cellType = cell.getCachedFormulaResultTypeEnum();
Font font = wb.getFontAt(style.getFontIndex());
double width = -1;
if (cellType == CellType.STRING) {
RichTextString rt = cell.getRichStringCellValue();
String[] lines = rt.getString().split("\\n");
for (String line : lines) {
String txt = line + defaultChar;
AttributedString str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
if (rt.numFormattingRuns() > 0) {
// TODO: support rich text fragments
}
width = getCellWidth(defaultCharWidth, colspan, style, width, str);
}
} else {
String sval = null;
if (cellType == CellType.NUMERIC) {
// Try to get it formatted to look the same as excel
try {
sval = formatter.formatCellValue(cell, dummyEvaluator);
} catch (Exception e) {
sval = String.valueOf(cell.getNumericCellValue());
}
} else if (cellType == CellType.BOOLEAN) {
sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase(Locale.ROOT);
}
if (sval != null) {
String txt = sval + defaultChar;
AttributedString str = new AttributedString(txt);
copyAttributes(font, str, 0, txt.length());
width = getCellWidth(defaultCharWidth, colspan, style, width, str);
}
}
return width;
}
Aggregations