【问题标题】:How can I remove Date from Time Object?如何从时间对象中删除日期?
【发布时间】:2014-08-28 17:22:42
【问题描述】:

我正在尝试使用 Apache POI 在 excel 单元格中节省时间 [hh:mm:ss]。我写的代码如下-

  FileOutputStream out = new FileOutputStream("dateFormat.xls");
  HSSFWorkbook hssfworkbook = new HSSFWorkbook();
  HSSFSheet sheet = hssfworkbook.createSheet("new sheet");
  HSSFCellStyle cs = hssfworkbook.createCellStyle();
  HSSFDataFormat df = hssfworkbook.createDataFormat();
  cs.setDataFormat(df.getFormat("h:mm:ss"));
  HSSFRow row = sheet.createRow((short)0);
  HSSFCell cell = row.createCell((short)0);
  //cell.setCellValue(new Time(567898));
  cell.setCellValue(new Time(1, 6, 55));
  cell.setCellStyle(cs);
  hssfworkbook.write(out);
  out.close();

现在的问题是它包含日期和时间。当我在此代码生成的 Excel 工作表中执行 sum 时。它给出了incorrect 结果。

 cell.setCellValue(new Time(3, 4, 4));  --->01-01-1970  03:04:04 AM [in excel sheet]
 cell2.setCellValue(new Time(1, 6, 51)); --->01-01-1970  01:06:55 AM [in excel sheet]

我尝试赋予String 值的另一种方式,在这种情况下,结果是Zero

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

    您需要设置单元格的样式才能使格式生效:

    cell.setStyle(cs);
    

    【讨论】:

    • 感谢您的回答,我忘了提到我已经在我的代码中写了cell.setStyle(cs)。您能否提出其他解决方案。
    【解决方案2】:

    这个问题的工作代码是:

      FileOutputStream out = new FileOutputStream("dateFormat.xls");
      HSSFWorkbook hssfworkbook = new HSSFWorkbook();
      HSSFSheet sheet = hssfworkbook.createSheet("new sheet");
      HSSFCellStyle cs = hssfworkbook.createCellStyle();
      HSSFDataFormat df = hssfworkbook.createDataFormat();
      HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(hssfworkbook);
    
      cs.setDataFormat(df.getFormat("h:mm:ss"));
      HSSFRow row = sheet.createRow((short)0);
      HSSFCell cell = row.createCell((short)0);
    
    
      cell.setCellFormula("TIME(0,3,24)");//this method only sets the formula string and does not calculate the formula value
      cell.setCellType(Cell.CELL_TYPE_FORMULA);//Set the cells type (numeric, formula or string)
    
      evaluator.evaluateFormulaCell(cell);// it evaluates the formula, and saves the result of the formula
      cell.setCellStyle(cs);
    
    
    
      HSSFRow row2 = sheet.createRow((short)1);
      HSSFCell cell2 = row2.createCell((short)0);
    
    
      cell2.setCellFormula("TIME(0,9,54)");
      cell2.setCellType(Cell.CELL_TYPE_FORMULA);
      evaluator.evaluateFormulaCell(cell2);
      cell2.setCellStyle(cs);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 2012-12-26
      • 2019-05-25
      • 1970-01-01
      • 2017-09-09
      • 2020-01-23
      相关资源
      最近更新 更多