从官方文档中了解到:POI提供的HSSF包用于操作 Excel '97(-2007)的.xls文件,而XSSF包则用于操作Excel2007之后的.xslx文件。
需要的jar包
POI官网上下载包并解压获取java操作excel文件必须的jar包:
其中dom4j-1.6.1.jar和xbean.jar(下载地址:http://mirror.bjtu.edu.cn/apache/xmlbeans/binaries/ 网站:http://xmlbeans.apache.org
并不包含在POI提供的jar包中,需要单独下载,否则程序会抛出异常:java.lang.ClassNotFoundException:org.apache.xmlbeans.XmlOptions。
具体代码
在Eclipse中创建一个java project,将上面列出来的jar包都加入到工程的classpath中,否则引用不到jar包会报错。
直接上代码(代码基本框架来自Apache POI官方网站,自行调整部分):
创建excel文件并写入内容:
public static void createWorkbook() throws IOException {
Workbook wb = new HSSFWorkbook();
String safeName1 = WorkbookUtil.createSafeSheetName("[O'sheet1]");
Sheet sheet1 = wb.createSheet(safeName1);
CreationHelper createHelper = wb.getCreationHelper();
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet1.createRow((short) 0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1234);
// Or do it on one line.
row.createCell(2).setCellValue(
createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// 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(
"m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
// you can also set date as java.util.Calendar
CellStyle cellStyle1 = wb.createCellStyle();
cellStyle1.setDataFormat(createHelper.createDataFormat().getFormat(
"yyyyMMdd HH:mm:ss"));
cellStyle1.setBorderBottom(CellStyle.BORDER_THIN);
cellStyle1.setBottomBorderColor(IndexedColors.BLACK.getIndex());
cellStyle1.setBorderLeft(CellStyle.BORDER_THIN);
cellStyle1.setLeftBorderColor(IndexedColors.GREEN.getIndex());
cellStyle1.setBorderRight(CellStyle.BORDER_THIN);
cellStyle1.setRightBorderColor(IndexedColors.BLUE.getIndex());
cellStyle1.setBorderTop(CellStyle.BORDER_MEDIUM_DASHED);
cellStyle1.setTopBorderColor(IndexedColors.BLACK.getIndex());
cell = row.createCell(4);
cell.setCellValue(Calendar.getInstance());
cell.setCellStyle(cellStyle1);
FileOutputStream fileOut = new FileOutputStream("e:/test/workbook.xls");
wb.write(fileOut);
fileOut.close();
}