我正在尝试将数据从数据库导出到 Excel。我将数据导出并当前存储在 ArrayList 中(可以更改)。我已经能够将数据导出到 Excel,但所有值都作为字符串导出,我需要它们保持其数据类型,即货币/数字。
我正在使用 Apache POI,并且很难将字段的数据类型设置为字符串以外的任何内容。我错过了什么吗?有人可以告诉我更好的方法吗?对此的任何帮助将不胜感激。
public static void importDataToExcel(String sheetName, ArrayList header, ArrayList data, File xlsFilename, int sheetNumber)
throws HPSFException, FileNotFoundException, IOException {
POIFSFileSystem fs = new POIFSFileSystem();
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(xlsFilename));
HSSFSheet sheet = wb.createSheet(sheetName);
int rowIdx = 0;
short cellIdx = 0;
// Header
HSSFRow hssfHeader = sheet.createRow(rowIdx);
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
for (Iterator cells = header.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfHeader.createCell(cellIdx++);
hssfCell.setCellStyle(cellStyle);
hssfCell.setCellValue((String) cells.next());
}
// Data
rowIdx = 1;
for (Iterator rows = data.iterator(); rows.hasNext();) {
ArrayList row = (ArrayList) rows.next();
HSSFRow hssfRow = (HSSFRow) sheet.createRow(rowIdx++);
cellIdx = 0;
for (Iterator cells = row.iterator(); cells.hasNext();) {
HSSFCell hssfCell = hssfRow.createCell(cellIdx++);
hssfCell.setCellValue((String) cells.next());
}
}
Logfile.log("sheetNumber = " + sheetNumber);
wb.setSheetName(sheetNumber, sheetName);
try {
FileOutputStream out = new FileOutputStream(xlsFilename);
wb.write(out);
out.close();
} catch (IOException e) {
throw new HPSFException(e.getMessage());
}
}