JAVA POI 应用系列(2)--读取Excel

添加maven依赖

     <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>

实现代码:

 package com.yanwu.www.spring_hibernate.util;

 import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFileToList {
public static void main(String[] args) throws IOException { String fileName="C:\\Users\\IBM_ADMIN\\Desktop\\promotion\\a.xls";
FileInputStream fis = new FileInputStream(fileName);
Workbook workbook = null;
//判断excel的两种格式xls,xlsx
if(fileName.toLowerCase().endsWith("xlsx")){
workbook = new XSSFWorkbook(fis);
}else if(fileName.toLowerCase().endsWith("xls")){
workbook = new HSSFWorkbook(fis);
} //得到sheet的总数
int numberOfSheets = workbook.getNumberOfSheets(); System.out.println("一共"+numberOfSheets+"个sheet"); //循环每一个sheet
for(int i=0; i < numberOfSheets; i++){ //得到第i个sheet
Sheet sheet = workbook.getSheetAt(i);
System.out.println(sheet.getSheetName()+" sheet"); //得到行的迭代器
Iterator<Row> rowIterator = sheet.iterator(); int rowCount=0;
//循环每一行
while (rowIterator.hasNext())
{
System.out.print("第"+(rowCount++)+"行 "); //得到一行对象
Row row = rowIterator.next(); //得到列对象
Iterator<Cell> cellIterator = row.cellIterator(); int columnCount=0; //循环每一列
while (cellIterator.hasNext())
{
//System.out.print("第"+(columnCount++)+"列: "); //得到单元格对象
Cell cell = cellIterator.next(); //检查数据类型
switch(cell.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue()+" ");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue()+" ");
}
} //end of cell iterator System.out.println(); } //end of rows iterator } //end of sheets for loop System.out.println("\nread excel successfully..."); //close file input stream
fis.close(); }
}

效果:

JAVA POI 应用系列(2)--读取Excel

上一篇:canvas 图片拖拽旋转之二——canvas状态保存(save和restore)


下一篇:tcpdump抓包具体分析