好的,所以我知道您必须在将所有数据输入工作表和工作簿后添加 autoSizeColumns() 方法。这就是我正在做的,但它只是调整到最后输入的单元格的宽度?
public void writeFile() {
Workbook wb = new HSSFWorkbook();
Sheet s = wb.createSheet();
try {
FileOutputStream out = new FileOutputStream(
this.getSelectedFile());
// create a new workbook
// create a new sheet
// declare a row object reference
Row r = null;
// declare a cell object reference
Cell c = null;
// in case of plain ascii
wb.setSheetName(0, "Street Light Report");
// create a sheet with 30 rows (0-29)
// int rownum;
// short rownum;
// PrintWriter printOut = new PrintWriter(
// this.getSelectedFile());
String[] colName = { "Light Id", "Flagged",
"Malfunction", "Comments", "Location", "Date" };
// printOut.println("Light Id,Flagged,Malfunction,Comments,Location,Date");
Connections.connect();
String[][] data = Connections.searchForFlagged();
for (int i = 0; i < data.length; i++) {
r = s.createRow(i);
}
r.setRowNum(0);
for (int j = 0; j < 6; j++) {
c = r.createCell(j);
switch (j) {
case 0:
c.setCellValue(colName[j]);
break;
case 1:
c.setCellValue(colName[j]);
break;
case 2:
c.setCellValue(colName[j]);
break;
case 3:
c.setCellValue(colName[j]);
break;
case 4:
c.setCellValue(colName[j]);
break;
case 5:
c.setCellValue(colName[j]);
break;
}
}
for (int i = 0; i < data.length; i++) {
r.setRowNum(i + 1);
for (int j = 0; j < data[i].length; j++) {
c = r.createCell(j);
// System.out.println(data[i][j]);
switch (j) {
case 0:
c.setCellType(Cell.CELL_TYPE_NUMERIC);
c.setCellValue(Integer.parseInt(data[i][j]));
break;
case 1:
if (data[i][j].equals("true"))
c.setCellValue("Yes");
else
c.setCellValue("No");
break;
case 2:
if (data[i][j].equals("I"))
c.setCellValue("Intermittent");
else
c.setCellValue("Not Functional");
break;
case 3:
c.setCellValue(data[i][j]);
break;
case 4:
c.setCellValue(data[i][j]);
break;
case 5:
c.setCellValue(data[i][j]);
break;
}
}
}
wb.getSheetAt(0).setPrintGridlines(true);
for (int j = 0; j < 6; j++) {
s.autoSizeColumn(j);
}
wb.write(out);
out.close();
} catch (Exception ex) {
}
};