2014-08-28 38 views
1

我想在使用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

回答

1

這樣做的工作代碼問題是:

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

您需要設置單元格樣式,以便格式的工作:

cell.setStyle(cs); 
+0

感謝您的回答,我忘了提及我已經在我的代碼中寫入'cell.setStyle(cs)'。你可以請建議一些其他的解決方案。 – Priyank 2014-08-28 04:43:21

+1

查看http://stackoverflow.com/a/13466371/1651233 – BobTheBuilder 2014-08-28 04:59:15

相關問題