View Javadoc

1   
2   package oscon2006.hello;
3   
4   import org.apache.poi.hssf.usermodel.*;
5   import java.io.*;
6   import java.util.*;
7   
8   public class HelloPoi
9   {
10  
11  	public static void main(String[] args) throws Exception
12  	{
13  		
14  		createWorkbook("hello-poi.xls");
15  		
16  		readWorkbook("hello-poi.xls");
17  		
18  	}
19  
20  	private static void createWorkbook(String filename) throws Exception
21  	{
22  		
23  		HSSFWorkbook wb = new HSSFWorkbook();
24  		
25  		HSSFSheet sheet = wb.createSheet("mySheet");
26  
27  		sheet.setZoom(2, 1);
28  		
29  		HSSFFont font = wb.createFont();
30  		font.setFontHeightInPoints( (short) 18 );
31  		font.setFontName("Arial");
32  		font.setItalic(true);
33  		
34  		HSSFCellStyle style = wb.createCellStyle();
35  		style.setFont(font);
36  		
37  		for (int rownum = 0; rownum < 5; rownum++)
38  		{
39  			HSSFRow row = sheet.createRow(rownum);
40  			for (short cellIndex = 0; cellIndex < 5; cellIndex++)
41  			{
42  				HSSFCell cell = row.createCell(cellIndex);
43  				cell.setCellStyle(style);
44  				cell.setCellValue(cellIndex + (rownum * 10));
45  			}
46  		}
47  		
48  		FileOutputStream fos = null;
49  		
50  		fos = new FileOutputStream("hello-poi.xls");
51  		
52  		wb.write(fos);
53  		
54  		fos.flush();
55  		
56  		fos.close();
57  		
58  	}
59  
60  	private static void readWorkbook(String filename) throws Exception
61  	{
62  		
63  		InputStream input = new FileInputStream(filename);
64  		
65  		HSSFWorkbook wb = new HSSFWorkbook(input);
66  		
67  		for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++)
68  		{
69  			HSSFSheet sheet = wb.getSheetAt(sheetIndex);
70  			Iterator rowIter = sheet.rowIterator();
71  			while (rowIter.hasNext())
72  			{
73  				HSSFRow row = (HSSFRow) rowIter.next();
74  				Iterator cellIter = row.cellIterator();
75  				while (cellIter.hasNext())
76  				{
77  					HSSFCell cell = (HSSFCell) cellIter.next();
78  					printCellValue(cell);
79  				}
80  			}
81  		}
82  		
83  		input.close();
84  	}
85  		
86  
87  	private static void printCellValue(HSSFCell c)
88  	{
89  		
90  		int cellType = c.getCellType();
91  		
92  		if (cellType == HSSFCell.CELL_TYPE_BOOLEAN)
93  		{
94  			System.out.println(c.getBooleanCellValue());
95  		}
96  		else if (cellType == HSSFCell.CELL_TYPE_STRING)
97  		{
98  			System.out.println(c.getRichStringCellValue().getString());
99  		}
100 		else if (cellType == HSSFCell.CELL_TYPE_FORMULA)
101 		{
102 			System.out.println(c.getCellFormula());
103 		}
104 		else if (cellType == HSSFCell.CELL_TYPE_NUMERIC)
105 		{
106 			System.out.println(c.getNumericCellValue());
107 		}
108 		else if (cellType == HSSFCell.CELL_TYPE_ERROR)
109 		{
110 			System.out.println(c.getErrorCellValue());
111 		}
112 	}
113 }