2013-10-30 32 views
4

我有一个java程序,它将头和数据作为输入并生成一个excel文件。自动包装在Apache POI(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 
} 

如果有人能指出我的一些例子可在网上。

感谢您的阅读!

回答

30

你应该能够与小区风格来实现这一点,我试图拼凑一个例子来说明:

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

祝您好运!