org.apache.poi создает книгу Excel с ячейками даты

1

У меня есть дата в java в таком формате: "2014.01.31 14:24:28". Я хотел бы поместить его в excel, используя библиотеку apache poi с типом ячейки: "date". Как я могу добиться этого?

Теги:
excel
date
apache-poi

2 ответа

5
Лучший ответ

Проверьте здесь: измените дату в нужном формате и используйте это.

Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");

// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow(0);

// Create a cell and put a date value in it.  The first cell is not styled
// as a date.
Cell cell = row.createCell(0);
cell.setCellValue(new Date());

// we style the second cell as a date (and time).  It is important to
// create a new cell style from the workbook otherwise you can end up
// modifying the built in style and effecting not only this cell but other cells.
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("yyyy/mm/dd hh:mm:ss"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

//you can also set date as java.util.Calendar
cell = row.createCell(2);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
2

Попробуй это

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); HSSFCell myCell; myCell.setCellValue(dateFormat.format("2014.01.31 14:24:28"));

Ещё вопросы

Сообщество Overcoder
Наверх
Меню