如何通过POI Excel以编程方式拉伸列以适合文本?

时间:2016-11-29 14:37:18

标签: java excel apache-poi

这就是我所拥有的:

enter image description here

这就是我想要的:

enter image description here

我正在使用POIExcel创建Excel文档并以编程方式设置相应的标题,如下所示。然后,我在printSubnetInfo()方法中添加了下面的其他行。我想要做的是确保在打开文档时拉伸列以适合文本。忽略粗体!

String outputs = "\\outputs\\";
String filename = homepath + outputs + customer + ".xls";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Subnet Information"); 

// Create Excel document header row
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell(0).setCellValue("Default Gateway");
rowhead.createCell(1).setCellValue("CIDR Signature");
rowhead.createCell(2).setCellValue("Netmask");
rowhead.createCell(3).setCellValue("Network Address");
rowhead.createCell(4).setCellValue("Broadcast Address");
rowhead.createCell(5).setCellValue("Lowest Address");
rowhead.createCell(6).setCellValue("Highest Address");
rowhead.createCell(7).setCellValue("# of Subnet Addresses");

// Add rows to Excel document
for (int rowNum = 1; rowNum < (defaultGWsList).size(); rowNum++) {
    String defaultGWAddr = defaultGWsList.get(i);
    printSubnetInfo(subnetInfo, defaultGWAddr, homepath, customer, sheet, rowNum);
}

// Create Excel file
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");

1 个答案:

答案 0 :(得分:3)

sheet.autoSizeColumn(colNumber);

在填写完所有数据后运行它。