Java 如何从时间对象中删除日期?
我试图使用ApachePOI在excel单元格中节省时间[hh:mm:ss]。我所写的守则如下:Java 如何从时间对象中删除日期?,java,apache-poi,Java,Apache Poi,我试图使用ApachePOI在excel单元格中节省时间[hh:mm:ss]。我所写的守则如下: FileOutputStream out = new FileOutputStream("dateFormat.xls"); HSSFWorkbook hssfworkbook = new HSSFWorkbook(); HSSFSheet sheet = hssfworkbook.createSheet("new sheet"); HSSFCellStyle cs = hssfwo
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表格中由该代码生成的单元格进行求和时。它给出的结果不正确
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);
感谢您的回答,我忘了提到我已经在代码中编写了cell.setStyle(cs)
。你能推荐一些其他的解决方案吗。