Java使用Apache POI操作excel文件

发表于:2014-9-01 10:54

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:博客园    来源:51Testing软件测试网采编

  官方介绍
  HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
  从官方文档中了解到: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();
}
31/3123>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号