问题需求
我需要将excel的每个sheet页转成一张jpeg图片,同时获取到每个单元格在图片中的像素位置。但是在某些sheet页下会存在单元格位置偏移。下面的样本中,sheet2没有偏移,其他sheet页都存在偏移。
aspose-cells 版本:24.11
excel样本和转出的图片.zip (2.1 MB)
实现方式
excel转图片
Worksheet sheet = workbook.getWorksheets().get(pageIndex);
sheet.setVisible(true);
sheet.getPageSetup().setLeftMargin(0);
sheet.getPageSetup().setRightMargin(0);
sheet.getPageSetup().setTopMargin(0);
sheet.getPageSetup().setBottomMargin(0);
ImageOrPrintOptions options = new ImageOrPrintOptions();
options.setOnePagePerSheet(true);
options.setOnlyArea(true);
SheetRender sheetRender = new SheetRender(sheet, options);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
sheetRender.toImage(0, outputStream);
pageBase64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
计算单元格在图片中的位置
Cells cells = sheet.getCells();
final int maxRow = cells.getMaxRow();
final int maxColumn = cells.getMaxColumn();
cumRowHeightPixel = new int[maxRow + 2];
cumColumnWidthPixel = new int[maxColumn + 2];
for (int rowIndex = 0; rowIndex <= maxRow; rowIndex++) {
int height = cells.getRowHeightPixel(rowIndex);
rowHightPixel[rowIndex] = height;
cumRowHeightPixel[rowIndex + 1] = cumRowHeightPixel[rowIndex] + height;
}
pageHeight = cumRowHeightPixel[maxRow + 1];
for (int columnIndex = 0; columnIndex <= maxColumn; columnIndex++) {
int width = cells.getColumnWidthPixel(columnIndex);
columnWidthPixel[columnIndex] = width;
cumColumnWidthPixel[columnIndex + 1] = cumColumnWidthPixel[columnIndex] + width;
}
// 省略一部分处理合并的单元格的过程,最终每个单元格像素位置的获取方式如下
int posLeft = cumColumnWidthPixel[col];
int posTop = cumRowHeightPixel[row];
int posRight = cumColumnWidthPixel[col + colspan];
int posBottom = cumRowHeightPixel[row + rowspan];