org.apache.poi创建Excel工作簿包含日期细胞 [英] org.apache.poi create excel workbook with date cells

查看:233
本文介绍了org.apache.poi创建Excel工作簿包含日期细胞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种格式在java中日期:2014年1月31日14时24分28秒。我希望把它变成Excel中使用Apache POI库单元格格式日期。
我怎样才能achive呢?

I have date in java in this format: "2014.01.31 14:24:28". I would like to put it into excel using apache poi library with cell format type: "date". How can I achive this?

推荐答案

:更改日期在你想要的格式,并使用

Check here: Change the date in your desired format and use that.

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

这篇关于org.apache.poi创建Excel工作簿包含日期细胞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆