Add date into cell with formating
// create a new cell style from the workbook.
CellStyle cellStyle = workbook.createCellStyle();
CreationHelper createHelper = workbook.getCreationHelper();
// Set the date format of date
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(
"dd/MM/yyyy hh:mm:ss"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
Set date by using Calendar
// You also can set date as java.util.Calendar object.
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
Check cell type (using HSSFDateUtil)
String JAVA_TOSTRING = "EEE MMM dd HH:mm:ss zzz yyyy";
Object value = "";
switch(cell.getCellType())
{
case HSSFCell.CELL_TYPE_NUMERIC:
value = cell.getNumericCellValue();
if(HSSFDateUtil.isCellDateFormatted(cell))
{
if(HSSFDateUtil.isValidExcelDate(value))
{
Date date = HSSFDateUtil.getJavaDate(value);
SimpleDateFormat dateFormat = new SimpleDateFormat(JAVA_TOSTRING);
value = dateFormat.format(date);
}
else
{
throw new Exception("Invalid Date value found at row number " +
row.getRowNum()+" and column number "+cell.getCellNum());
}
}
else
{
value = value + "";
}
break;
case HSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case HSSFCell.CELL_TYPE_BLANK:
value = null;
break;
Evaluate formula of Workbook
// evaluate all formula cells in workbook
HSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
Không có nhận xét nào:
Đăng nhận xét