【问题标题】:Auto wrap in apache POI (Excel)在 apache POI (Excel) 中自动换行
【发布时间】:2013-10-30 07:56:48
【问题描述】:

我有一个 java 程序,它将标头和数据作为输入并生成一个 excel 文件。

但是,有时当标题值很长并且列数更多时,我的 Excel 工作表往往会变得不必要的宽。

由于标题,我必须向下滚动才能看到尾端列的内容。

有没有办法解决这个问题,如果单元格中的内容比值 x 大,则自动换行并自动调整行高并固定列宽。

我正在寻找的粗略算法是:

 if(content.size is more then 50 chars){
       - apply auto wrap with centred text
       - adjust the row height accordingly
       - adjust all the cells in the column accordingly
 }

如果有人可以指出一些在线可用的示例。

感谢阅读!

【问题讨论】:

    标签: java apache-poi xssf


    【解决方案1】:

    你应该可以使用 Cell 样式来实现这一点,我尝试整理一个示例来展示:

    public class SO{
        public static void main(String[] args) {
    
            try {
                FileInputStream is = new FileInputStream(new File("D:\\Users\\user2777005\\Desktop\\bob.xlsx"));
                XSSFWorkbook wb = new XSSFWorkbook(is);
                String header = "123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789123456789";
                Sheet sheet = wb.getSheet("Sheet1");
                sheet.setColumnWidth(0, 18000);
                Row row = sheet.createRow(0);
                Cell cell = row.createCell(0);
    
                if(header.length() > 50){ //Length of String for my test
                    sheet.setColumnWidth(0, 18000); //Set column width, you'll probably want to tweak the second int
                    CellStyle style = wb.createCellStyle(); //Create new style
                    style.setWrapText(true); //Set wordwrap
                    cell.setCellStyle(style); //Apply style to cell
                    cell.setCellValue(header); //Write header
                }
    
                wb.write(new FileOutputStream(new File("D:\\Users\\user2777005\\Desktop\\bob.xlsx")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }       
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      相关资源
      最近更新 更多