效果

Java ApachePOI Excel 设置强制换行_可编辑

文章超过长度了自动换行.

核心设置样式代码

CellStyle wrapText = workbook.createCellStyle();
wrapText.setWrapText(true); // 设置强制换行的

然后cell设置演示代码

cell.setCellStyle(wrapText);

下面是项目代码,仅供参考

关注注释中带//!!!的代码即可,其它代码都是业务代码,你们看了没啥用.

public <T> void insertValueIntoExcel(Collection collection, SXSSFSheet sheet,
SXSSFWorkbook workbook) throws IllegalAccessException {
CellStyle unlockedCellStyle = workbook.createCellStyle();//创建CellStyle
unlockedCellStyle.setLocked(false); //将使用此样式的单元格设置为解锁(输入false就是解锁)



CellStyle wrapText = workbook.createCellStyle();//!!!!!!!!!!!!!!!!!!!!
wrapText.setWrapText(true); // 设置强制换行的//!!!!!!!!!!!!!!!!!!!!

Class<?> clazz = collection.iterator().next().getClass();
Field[] fields = clazz.getDeclaredFields();
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint numberConstraint = helper.createNumericConstraint(DataValidationConstraint.ValidationType.INTEGER, DataValidationConstraint.OperatorType.BETWEEN,
"-99999999999", "99999999999");
CellRangeAddressList addressList = new CellRangeAddressList(1, collection.size(), 10, 10);
//创建验证对象
DataValidation validation = helper.createValidation(numberConstraint, addressList);
validation.createErrorBox("自然销量输入格式错误", "只能输入正整数、零、负整数");
//设置是否显示错误窗口
validation.setShowErrorBox(true);
sheet.addValidationData(validation);

int i = 1;
for (Object o : collection) {
SXSSFRow row = sheet.createRow(i++);

for (Field field : fields) {
InExcelAndSort annotation = field.getAnnotation(InExcelAndSort.class);
if (annotation == null) {
continue;
}
field.setAccessible(true);

SXSSFCell cell = row.createCell(annotation.sort());
String name = field.getName();
if ("natureSaleCount".equals(name)) { // 当字段等"natureSaleCount"的时候,设置为解锁状态,
// 解锁状态就是可编辑状态
cell.setCellStyle(unlockedCellStyle); // 这里设置cell样式
} else {
cell.setCellStyle(wrapText); //!!!!!!!!!!!!!!!!!!!!
}

cell.setCellValue(exportExcelUtil.checkData(field.get(o)));
}
}

}