【问题标题】:Generate excel file using java with different column width使用java生成具有不同列宽的excel文件
【发布时间】:2013-06-13 12:19:52
【问题描述】:

我正在做一个 java 应用程序 (J2SE),我必须生成一个 excel 文档 (.xls)。我确实生成了文件,但我无法根据同一单元格中具有最大长度的内容动态更改单元格宽度。

这是我的编码...

     try {

      ResultSet rs = com.dss.system.DBORCL.search("sql statement");

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("Excel Sheet");
        HSSFRow rowhead = sheet.createRow((short) 0);

        rowhead.createCell((short) 0).setCellValue("Site");
        rowhead.createCell((short) 1).setCellValue("Part No");
        rowhead.createCell((short) 2).setCellValue("Part Description");
        int index = 1;
        while (rs.next()) {

            HSSFRow row = sheet.createRow((short) index);

            row.createCell((short) 0).setCellValue(rs.getString("site"));
            row.createCell((short) 1).setCellValue(rs.getString("part_no"));
            row.createCell((short) 1).setCellValue(rs.getString("description"));
            index++;
            }           


        FileOutputStream fileOut = new FileOutputStream("F:\\IFS\\IFSDOC" +    txtPLCode.getText() + "[" + currentDate + "-" + usesecond + "]" + ".xls");
        wb.write(fileOut);
        fileOut.close();
        System.out.println("Data is saved in excel file.");
        //  rs.close();

【问题讨论】:

  • 您没有尝试过使用 setColumnWidth() 吗? poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/…, int)
  • 老兄,我刚刚尝试了这个。没有错误。但是在我的 excel 报告中,当我使用 setColumnWidth((short) 1,(short) 10) 时,该列没有出现。你知道吗?跨度>

标签: java file-io resultset java-io


【解决方案1】:
sheet.autoSizeColumn(0) //for first column
sheet.autoSizeColumn(1) //for second column ... etc

参考:http://poi.apache.org/spreadsheet/quick-guide.html#Autofit

【讨论】:

  • 我试过了,但在 autoSizeColumn(0) 中出现错误。我不知道为什么会这样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 1970-01-01
  • 2011-04-11
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
相关资源
最近更新 更多