1.3 POI简单读取Excel数据
代码部分:
- package com.vintage.testpoi;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStream;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFRow;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- /**
- * POI入门 :简单读取excel数据
- * @author VintageYu
- *
- */
- public class ReadExcelTest {
- public static void read(InputStream inputStream) throws IOException{
- //初始整个Excel
- HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
- //获取第一个Sheet表
- HSSFSheet sheet = workbook.getSheetAt(0);//或者 HSSFSheet sheet = workbook.getSheet("Sheet1");
- //获取第一行
- HSSFRow row0 = sheet.getRow(0);
- //获取第一行的第一个单元格
- HSSFCell cell = row0.getCell(0);
- //打印
- System.out.println(cell.getRichStringCellValue().getString());
- }
- public static void main(String[] args) {
- InputStream inputStream = null;
- try {
- //读取文件流
- inputStream = new FileInputStream(new File("E:\\read1.xls"));
- read(inputStream);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }finally{
- try {
- if(inputStream != null){
- inputStream.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
输入结果见图2
![](http://hi.csdn.net/attachment/201109/1/0_1314858758ZNnc.gif)
为了进一步贴近实际,将上面部分代码进行如下修改
- //获取第一个Sheet表
- HSSFSheet sheet = workbook.getSheetAt(0);//或者 HSSFSheet sheet = workbook.getSheet("Sheet1");
- //获取第一行
- HSSFRow row0 = sheet.getRow(0);
- //获取第一行的第一个单元格
- HSSFCell cell = row0.getCell(0);
- //打印
- System.out.println(cell.getRichStringCellValue().getString());
- 将这部分代码改为
- //循环workbook中所有sheet
- for(int sheetIndex = 0; sheetIndex < workbook.getNumberOfSheets(); sheetIndex++){
- HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
- System.out.println("sheet序号:"+sheetIndex+",sheet名称:"+workbook.getSheetName(sheetIndex));
- //循环该sheet中的有数据的每一行
- for(int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++){
- HSSFRow row = sheet.getRow(rowIndex);
- if(row == null){
- continue;
- }
- //循环该行的每一个单元格
- for(int cellnum = 0; cellnum < row.getLastCellNum(); cellnum++){
- HSSFCell cell = row.getCell(cellnum);
- System.out.println("第"+rowIndex+"行 第"+cellnum+"列 内容为:"+cell.getRichStringCellValue().getString());
- }
- }
- System.out.println("---------------------------------------------------------");
- }
打印结果如图3
图3
注:
workbook.getNumberOfSheets()= 3 --- 测试用Excel(图1)有3个sheet,得到的就是sheet的个数
sheet.getLastRowNum()= 3 --- 测试用Excel(图1)中Sheet1表有4行数据,所以得到的数据是POI中行序列的3
row.getLastCellNum()= 4 --- 测试用Excel(图1)中Sheet1表有4列数据,所以得到的数据是POI中列数