---
title: "POI学习笔记（一）"
author: "canfly2010"
date: "2010-06-29T15:10:33Z"
tags: []
categories: ["编程语言"]
slug: "poi"
draft: false
lastmod: "2010-06-29T15:10:33Z"
id: 701722
url: "https://canfly2010.iteye.com/blog/701722"
---

项目中经常要解析和生成Excel文件，最常用的开源组件有poi与jxl。jxl是韩国人开发的，发行较早，但是更新的很慢，目前似乎还不支持excel2007。[poi](http://poi.apache.org/)是apache下的一个子项目，poi应该是处理ms的office系列文档最好的组件了。poi3.6版本已经开始支持excel2007了。但是由于excel2007底层的实现似乎变成xml与excel2003底层存储发生了本质的变化，因此poi解析excel的类就存在差异了。

      现在简单的介绍下poi常用的接口。

      经常用的类一般都在org.apache.poi.hssf.usermodel（excel2003）或org.apache.poi.xssf.usermodel  
（excel2007）。

- 工作薄：  WorkBook是操作Excel的入口，HSSFWorkbook, XSSFWorkbook实现了该接口。
- 页：Sheet表示工作薄的分页。HSSFSheet， XSSFChartSheet, XSSFDialogsheet, XSSFSheet实现了该接口。
- Row：表示页中的一行。HSSFRow, XSSFRow实现了该接口。
- Cell：行中的一个单元格。HSSFCell, XSSFCell实现了该接口。

从上面的介绍得知：页是通过工作薄对象创建的，行是通过页对象创建的，单元格是通过行对象创建的。接下来，我们就开始发掘poi的强大功能吧。

1. 创建一个空白的工作薄

Java代码 [![复制代码](http://yunzhongxia.iteye.com/images/icon_copy.gif)](http://yunzhongxia.iteye.com/blog/558998 "复制代码")

01. **import** java.io.FileOutputStream;
02. **import** org.apache.poi.hssf.usermodel.HSSFWorkbook;
03. **import** org.apache.poi.ss.usermodel.Workbook;
04. **import** org.apache.poi.xssf.usermodel.XSSFWorkbook;
05. //2003版本
06. Workbook wb = **new** HSSFWorkbook();
07. FileOutputStream fileOut = **new** FileOutputStream("workbook.xls");
08. wb.write(fileOut);
09. fileOut.close();
10. //2007版本
11. // Workbook wb = new XSSFWorkbook();
12. // FileOutputStream fileOut = new FileOutputStrea("workbook.xlsx");
13. // wb.write(fileOut);
14. // fileOut.close();

```
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//2003版本
Workbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
 fileOut.close();

//2007版本
// Workbook wb = new XSSFWorkbook();
// FileOutputStream fileOut = new FileOutputStrea("workbook.xlsx");
// wb.write(fileOut);
// fileOut.close();
```

 注意：Workbook 是org.apache.poi.ss.usermodel包下的一个接口，注意与以前版本的不同，HSSFWorkbook和XSSFWorkbook实现了该接口，这样就达到了面前接口编程。下面的excel工具类中要用到此点知识。

 2. 创建两个空白页

 

 

Java代码 [![复制代码](http://yunzhongxia.iteye.com/images/icon_copy.gif)](http://yunzhongxia.iteye.com/blog/558998 "复制代码")

1. Workbook wb = **new** HSSFWorkbook();
2. //Workbook wb = new XSSFWorkbook();
3. Sheet sheet1 = wb.createSheet("new sheet");
4. Sheet sheet2 = wb.createSheet("second sheet");
5. FileOutputStream fileOut = **new** FileOutputStream("workbook.xls");
6. wb.write(fileOut);
7. fileOut.close();

```
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
Sheet sheet2 = wb.createSheet("second sheet");
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
```

 

3\. 创建单元格

 

Java代码 [![复制代码](http://yunzhongxia.iteye.com/images/icon_copy.gif)](http://yunzhongxia.iteye.com/blog/558998 "复制代码")

01. **public** **void** createRow() **throws** Exception {
02. Workbook wb = **new** HSSFWorkbook();
03. // Workbook wb = new XSSFWorkbook();
04. CreationHelper createHelper = wb.getCreationHelper();
05. Sheet sheet = wb.createSheet("new sheet");
06. //创建一行并放一些单元格到该行中，行的索引是以0开始的
07. Row row = sheet.createRow((**short**) 0);
08. // 创建一个单元格并填充一个整数的值
09. Cell cell = row.createCell(0);
10. cell.setCellValue(1);
11. //链式写法
12. row.createCell(1).setCellValue(1.2);
13. row.createCell(2).setCellValue(
14. createHelper.createRichTextString("This is a string"));
15. row.createCell(3).setCellValue(**true**);
16. //输出文件
17. FileOutputStream fileOut = **new** FileOutputStream("workbook.xls");
18. wb.write(fileOut);
19. fileOut.close();
20. }

```
public void createRow() throws Exception {
		Workbook wb = new HSSFWorkbook();
		// Workbook wb = new XSSFWorkbook();
		CreationHelper createHelper = wb.getCreationHelper();
		Sheet sheet = wb.createSheet("new sheet");

		//创建一行并放一些单元格到该行中，行的索引是以0开始的
		Row row = sheet.createRow((short) 0);
		// 创建一个单元格并填充一个整数的值
		Cell cell = row.createCell(0);
		cell.setCellValue(1);

		//链式写法
		row.createCell(1).setCellValue(1.2);
		row.createCell(2).setCellValue(
				createHelper.createRichTextString("This is a string"));
		row.createCell(3).setCellValue(true);

		//输出文件
		FileOutputStream fileOut = new FileOutputStream("workbook.xls");
		wb.write(fileOut);
		fileOut.close();

	}
```

 

 4. 创建日期单元格

 

Java代码 [![复制代码](http://yunzhongxia.iteye.com/images/icon_copy.gif)](http://yunzhongxia.iteye.com/blog/558998 "复制代码")

01. **public** **void** createDateCell() **throws** Exception {
02. Workbook wb = **new** HSSFWorkbook();
03. // Workbook wb = new XSSFWorkbook();
04. CreationHelper createHelper = wb.getCreationHelper();
05. Sheet sheet = wb.createSheet("new sheet");
06. // Create a row and put some cells in it. Rows are 0 based.
07. Row row = sheet.createRow(0);
08. // Create a cell and put a date value in it. The first cell is not
09. // styled
10. // as a date.
11. Cell cell = row.createCell(0);
12. cell.setCellValue(**new** Date());
13. // we style the second cell as a date (and time). It is important to
14. // create a new cell style from the workbook otherwise you can end up
15. // modifying the built in style and effecting not only this cell but
16. // other cells.
17. CellStyle cellStyle = wb.createCellStyle();
18. cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(
19. "yyyy/MM/dd hh:mm"));
20. cell = row.createCell(1);
21. // cell.setCellValue(new Date());
22. Date date = **new** Date();
23. cell.setCellValue(createHelper.createRichTextString(date.toString()));
24. cell.setCellStyle(cellStyle);
25. // you can also set date as java.util.Calendar
26. cell = row.createCell(2);
27. cell.setCellValue(Calendar.getInstance());
28. cell.setCellStyle(cellStyle);
29. // Write the output to a file
30. FileOutputStream fileOut = **new** FileOutputStream("workbook.xls");
31. wb.write(fileOut);
32. fileOut.close();
33. }

```
public void createDateCell() throws Exception {
		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"));
		cell = row.createCell(1);
		// cell.setCellValue(new Date());
		Date date = new Date();

		cell.setCellValue(createHelper.createRichTextString(date.toString()));
		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();

	}
```

 

5.  创建不同的单元格样式

 

Java代码 [![复制代码](http://yunzhongxia.iteye.com/images/icon_copy.gif)](http://yunzhongxia.iteye.com/blog/558998 "复制代码")

01. **public** **void** createCellType() **throws** Exception{
02. Workbook wb = **new** HSSFWorkbook();
03. Sheet sheet = wb.createSheet("new sheet");
04. Row row = sheet.createRow((**short**)2);
05. row.createCell(0).setCellValue(1.1);
06. row.createCell(1).setCellValue(**new** Date());
07. row.createCell(2).setCellValue(Calendar.getInstance());
08. row.createCell(3).setCellValue("a string");
09. row.createCell(4).setCellValue(**true**);
10. row.createCell(5).setCellType(HSSFCell.CELL\_TYPE\_ERROR);
11. // Write the output to a file
12. FileOutputStream fileOut = **new** FileOutputStream("workbook.xls");
13. wb.write(fileOut);
14. fileOut.close();
15. }

```
public void createCellType() throws Exception{
		Workbook wb = new HSSFWorkbook();
	    Sheet sheet = wb.createSheet("new sheet");
	    Row row = sheet.createRow((short)2);
	    row.createCell(0).setCellValue(1.1);
	    row.createCell(1).setCellValue(new Date());
	    row.createCell(2).setCellValue(Calendar.getInstance());
	    row.createCell(3).setCellValue("a string");
	    row.createCell(4).setCellValue(true);
	    row.createCell(5).setCellType(HSSFCell.CELL_TYPE_ERROR);

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

 

6.  设置单元格水平垂直对齐方式

 

Java代码 [![复制代码](http://yunzhongxia.iteye.com/images/icon_copy.gif)](http://yunzhongxia.iteye.com/blog/558998 "复制代码")

01. **public** **static** **void** main(String\[] args)  **throws** Exception {
02. Workbook wb = **new** XSSFWorkbook(); //or new HSSFWorkbook();
03. Sheet sheet = wb.createSheet();
04. Row row = sheet.createRow((**short**) 2);
05. row.setHeightInPoints(30);
06. createCell(wb, row, (**short**) 0, XSSFCellStyle.ALIGN\_CENTER, XSSFCellStyle.VERTICAL\_BOTTOM);
07. createCell(wb, row, (**short**) 1, XSSFCellStyle.ALIGN\_CENTER\_SELECTION, XSSFCellStyle.VERTICAL\_BOTTOM);
08. createCell(wb, row, (**short**) 2, XSSFCellStyle.ALIGN\_FILL, XSSFCellStyle.VERTICAL\_CENTER);
09. createCell(wb, row, (**short**) 3, XSSFCellStyle.ALIGN\_GENERAL, XSSFCellStyle.VERTICAL\_CENTER);
10. createCell(wb, row, (**short**) 4, XSSFCellStyle.ALIGN\_JUSTIFY, XSSFCellStyle.VERTICAL\_JUSTIFY);
11. createCell(wb, row, (**short**) 5, XSSFCellStyle.ALIGN\_LEFT, XSSFCellStyle.VERTICAL\_TOP);
12. createCell(wb, row, (**short**) 6, XSSFCellStyle.ALIGN\_RIGHT, XSSFCellStyle.VERTICAL\_TOP);
13. // Write the output to a file
14. FileOutputStream fileOut = **new** FileOutputStream("xssf-align.xlsx");
15. wb.write(fileOut);
16. fileOut.close();
17. }
18. /\**
19. * Creates a cell and aligns it a certain way.
20. \*
21. * @param wb     the workbook
22. * @param row    the row to create the cell in
23. * @param column the column number to create the cell in
24. * @param halign the horizontal alignment for the cell.
25. \*/
26. **private** **static** **void** createCell(Workbook wb, Row row, **short** column, **short** halign, **short** valign) {
27. Cell cell = row.createCell(column);
28. cell.setCellValue(**new** XSSFRichTextString("Align It"));
29. CellStyle cellStyle = wb.createCellStyle();
30. cellStyle.setAlignment(halign);
31. cellStyle.setVerticalAlignment(valign);
32. cell.setCellStyle(cellStyle);
33. }