最近工作中遇到了一个问题,就是业务需要将在导入EXCEL时,保留EXCEL得格式,加粗,换行等等。
经过我多天潜心研究,使用富文本格式可以实现该需求
需要注意得是使用得是XSSFRichTextString,因此excel模板只支持xlsx,在研究过程中,发现HSSFRichTextString,实现不了需求
以下是导入得部分关键代码
public DataResult importTest(MultipartFile file,HttpServletResponse response) {
try {
InputStream inputStream = file.getInputStream();
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
XSSFRichTextString richStringCellValue = null;
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.STRING) {
//富文本形式,需要注意得是加粗得判断无法判断第一部分是否加粗,因此需要特殊处理下
Font font = workbook.getFontAt(cell.getCellStyle().getFontIndex());
richStringCellValue = (XSSFRichTextString)cell.getRichStringCellValue();
if (font.getBold()) {
Font boldFont = workbook.createFont();
boldFont.setBold(true);
String string1=richStringCellValue.getCTRst().getRList().get(0).getT();
richStringCellValue.applyFont(0,string1.length(),boldFont);
}
cell.setCellValue(richStringCellValue);
}
}
}
workbook.close();
} catch (HrException hrException) {
log.error("导入失败:" + hrException.getErrMsg());
throw hrException;
} catch (Exception e) {
throw new HrException("导入失败:请检查数据!"+e);
}
return DataResult.ok("导入成功");
}
将得到得cell保存入库,然后再需要导出得时候插入到指定得cell中就可以了
这里有一个需要注意得地方,就是再导出得时候需要将cell设置为自动换行,否则得换导出得excel不会自动换行
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true);
cell.setCellStyle(cellStyle);
cell.setCellValue(richStringCellValue);

1625

被折叠的 条评论
为什么被折叠?



