我正在尝试使用Apache的Java POI将Dates添加到电子表格中。但是,我最终将日期格式化的单元格中的日期不被单元格识别为日期,而是作为字符串。然而,当我随后打开电子表格时,只需点击进入单元格 - 即编辑它而不进行有效更改 - 并自动识别日期格式。如何在不需要干涉的情况下让我的程序执行最后一步?非常感谢,提前!
CreationHelper creationHelper = wb.getCreationHelper();
XSSFCellStyle cellStyleDate = wb.createCellStyle();
LocalDate start = LocalDate.of(2000, 1, 1);
LocalDate end = LocalDate.of(2000, 12, 31);
cellStyleDate.setDataFormat(creationHelper.createDataFormat().getFormat("dd.mm.yyyy"));
int i = 1;
for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
// wb.getSheetAt(0).createRow(i).createCell(0).setCellValue(date);
wb.getSheetAt(0).createRow(i).createCell(0).setCellValue(date.toString());
// wb.getSheetAt(0).createRow(i).createCell(0).setCellValue(date.getDayOfMonth() + "." + date.getMonthValue() + "." + date.getYear());
wb.getSheetAt(0).getRow(i).getCell(0).setCellStyle(cellStyleDate);
i++;
}
答案 0 :(得分:4)
截至documented,有两种可能的方法来设置日期值。 setCellValue(java.util.Calendar value)和setCellValue(java.util.Date value)。直到现在才支持使用java.time.LocalDate
。
因此,在设置为单元格值之前,您必须将LocalDate转换为java.util.Date
。
示例:
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.Date;
import java.time.LocalDate;
import java.time.ZoneId;
import java.awt.Desktop;
class LocalDateTest {
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
CreationHelper creationHelper = wb.getCreationHelper();
CellStyle cellStyleDate = wb.createCellStyle();
LocalDate start = LocalDate.of(2000, 1, 1);
LocalDate end = LocalDate.of(2000, 12, 31);
cellStyleDate.setDataFormat(creationHelper.createDataFormat().getFormat("dd.mm.yyyy"));
int i = 1;
for (LocalDate localdate = start; localdate.isBefore(end.plusDays(1)); localdate = localdate.plusDays(1)) {
Date date = Date.from(localdate.atStartOfDay(ZoneId.systemDefault()).toInstant());
wb.getSheetAt(0).createRow(i).createCell(0).setCellValue(date);
wb.getSheetAt(0).getRow(i).getCell(0).setCellStyle(cellStyleDate);
i++;
}
OutputStream out = new FileOutputStream("LocalDateTest.xlsx");
wb.write(out);
wb.close();
System.out.println("Done");
File outputfile = new File("LocalDateTest.xlsx");
Desktop.getDesktop().open(outputfile);
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}
答案 1 :(得分:0)