一看就会的超详细教程:SpringBoot整合MybatisPlus!>>>
1、需求
在导出excel的过程中,使Excel的cell宽度适应字长度;
2、代码
代码语言:javascript复制Field[] fields = cls.getDeclaredFields();//获取类下字段
int maxColumn = fields.length;
for (int i = 0; i <= maxColumn; i )
{
sheet.autoSizeColumn(i);
}
//获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = 0; columnNum <= maxColumn; columnNum )
{
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum )
{
Row currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null)
{
currentRow = sheet.createRow(rowNum);
}
else
{
currentRow = sheet.getRow(rowNum);
}
if(currentRow.getCell(columnNum) != null)
{
Cell currentCell = currentRow.getCell(columnNum);
int length = currentCell.toString().getBytes("GBK").length;
if (columnWidth < length 1)
{
columnWidth = length 1;
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 256);
}
每天进步一点点