Java 自动换行 apache POI (Excel)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19676714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:19:13  来源:igfitidea点击:

Auto wrap in apache POI (Excel)

javaapache-poixssf

提问by Vicky

I have a java program which takes header and data as the input and produces an excel file.

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

However, sometimes when the header values are long and the number of columns are more, my excel sheet tends to be unnecessarily wide.

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

Because of the headers, I will have to scroll down to right to see the content of the tail end columns.

由于标题,我将不得不向下滚动到右侧才能看到尾端列的内容。

Is there a way I can resolve this such that if the content in the cell is bigger then say value x, then auto wrap occurrs and automatically the row height gets adjusted and the column width gets fixed.

有没有一种方法可以解决这个问题,如果单元格中的内容大于值 x,然后自动换行并自动调整行高并固定列宽。

The rough algorithm for what I am looking for is:

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

 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
 }

If someone could point me to some example available online.

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

Thanks for reading!

谢谢阅读!

采纳答案by Levenal

You should be able to achieve this with a Cell style, I have tried to put together an example to show:

您应该可以使用 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();
        }
    }
}       

Good Luck!

祝你好运!