簡體   English   中英

如何從時間對象中刪除日期?

[英]How can I remove Date from Time Object?

我試圖使用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

您需要設置單元格的樣式才能使格式生效:

cell.setStyle(cs);

此問題的工作代碼是:

  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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM