自动换成Apache POI(Excel) [英] Auto wrap in apache POI (Excel)

查看:83
本文介绍了自动换成Apache POI(Excel)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java程序,该程序将标头和数据作为输入并生成一个excel文件.

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

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

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

由于标题的原因,我将不得不向下滚动到右侧以查看尾端列的内容.

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

有没有一种方法可以解决此问题,因此,如果单元格中的内容较大,然后说x,则自动换行发生并自动调整行高,并固定列宽.

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.

我要寻找的粗略算法是:

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.

感谢阅读!

推荐答案

您应该可以使用Cell样式实现此目的,我尝试将一个示例组合在一起显示:

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

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();
        }
    }
}       

祝你好运!

这篇关于自动换成Apache POI(Excel)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆