我正在使用 POI 的事件 API 处理大量记录,没有任何内存占用问题。 Here是它的引用。
当我处理 XLSX 工作表时,我得到的日期值格式与 Excel 工作表中的指定格式不同。 Excel 工作表中列的日期格式为“dd-mm-yyyy”,因为我以“mm/dd/yy”格式获取值。
有人能告诉我如何获得 Excel 工作表中给出的实际格式吗?下面给出了代码片段的引用。
ContentHandler handler = new XSSFSheetXMLHandler(styles, strings,
new SheetContentsHandler() {
public void startRow(int rowNum) {
}
public void endRow() {
}
public void cell(String cellReference, String formattedValue) {
System.out.println(formattedValue);
} catch (IOException e) {
System.out.println(
"Exception during file writing");
}
}
在日期列的单元格方法中获取格式化值类似于“mm/dd/yy”,因此我无法在我的 pl/sql 程序中正确执行验证。
最佳答案
要记住两点:
- 原始 Excel 单元格的格式可能不适合您 或者可以格式化为一般文本。
- 您可能想要精确控制日期、时间或数值 被格式化。
另一种控制日期和其他数值格式的方法是提供您自己的自定义 DataFormatter 扩展 org.apache.poi.ss.usermodel.DataFormatter。
您只需覆盖 formatRawCellContents() 方法(或其他方法,具体取决于您的需要):
构建解析器/处理程序的示例代码:
public void processSheet(Styles styles, SharedStrings strings,
SheetContentsHandler sheetHandler, InputStream sheetInputStream)
throws IOException, SAXException {
DataFormatter formatter = new CustomDataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler,
formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch (ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
private class CustomDataFormatter extends DataFormatter {
@Override
public String formatRawCellContents(double value, int formatIndex, String formatString,
boolean use1904Windowing) {
// Is it a date?
if (DateUtil.isADateFormat(formatIndex, formatString)) {
if (DateUtil.isValidExcelDate(value)) {
Date d = DateUtil.getJavaDate(value, use1904Windowing);
try {
return new SimpleDateFormat("yyyyMMdd").format(d);
} catch (Exception e) {
logger.log(Level.SEVERE, "Bad date value in Excel: " + d, e);
}
}
}
return new DecimalFormat("##0.#####").format(value);
}
}
关于java - POI XSSF 和 SAX(事件 API)的日期格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17318229/