Java导出Excel表,POI实现自适应宽度

来源:互联网 发布:java中的this 编辑:程序博客网 时间:2024/06/08 11:15
//列宽自适应,只对英文和数字有效          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);          } 
原创粉丝点击