1,如果一行中没有合并单元格的单元格那就比较简单了可以直接调用api
XSSFWorkbook workbook = new XSSFWorkbook("文件路径或者文件流");
XSSFSheet sheet = workbook.getSheet(sheetIndex);
XSSFRow xssfRow = sheet.getRow(rowIndex);
CTRow ctRow = xssfRow.getCTRow();
ctRow.setCustomHeight(false);
2,如果有合并的单元格,因为excel不支持合并单元格自动行高就需要自己设计一下了。
得到简单思路就是计算合并单元格的总宽度和它的内容,然后把宽度设置在一个没有用到的单元格
把合并单元格的样式都复制在这个测试单元格内,内容也设置在该单元格内最后调用自动调整行高的api就可以准确得到行高了再把测试单元格删除掉就行了。而且比传统方法计算行高更加准确。大致代码如下不可直接用需要自己调整。
public static void cellAndSetRowHeigt(Sheet sheet, XSSFRow sourceRow) {
int count=1;
int maxColumnIndex=30;
for (int cellIndex = sourceRow.getFirstCellNum(); cellIndex <= sourceRow.getPhysicalNumberOfCells(); cellIndex++,count++) {
if (cellIndex < 0) continue;
XSSFCell sourceCell = sourceRow.getCell(cellIndex);
//获取内容
String cellContent = getCellContentAsString(sourceCell);
if (null == cellContent || "".equals(cellContent)) {
continue;
}
//得到列宽
Map<String, Object> cellInfoMap = getCellInfo(sourceCell);
Integer cellWidth = (Integer) cellInfoMap.get("width");
if(getMergeColumNum(sourceCell,sheet)!=1){
sheet.setColumnWidth(maxColumnIndex+count,cellWidth);
XSSFCell cell = sourceRow.createCell(maxColumnIndex+ count);
CellStyle newStyle = sheet.getWorkbook().createCellStyle();
template2.copyCellStyle(sourceCell.getCellStyle(),newStyle, sheet.getWorkbook());
cell.setCellStyle(newStyle);
//cell.getCellStyle().setFont(sourceCell.getCellStyle().getFont());
cell.setCellValue(getCellContentAsString(sourceCell));
}
}
sourceRow.getCTRow().setCustomHeight(false);
for (int i=30;i<60;i++){
sheet.setColumnHidden(i,true);
}
}