poi读取excel文件,需要引入poi相关的jar包:poi-3.8.jar、poi-ooxml-3.8.jar、poi-ooxml-schemas-3.8.jar、xmlbeans-2.3.0.jar、stax-api-1.0.1.jar
package com.utils.poi;
import java.util.ArrayList;
import java.util.List;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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;
/**
* 解析excel工作表
* 2015-04-17
* @author guoyinggui
*/
public class PaserExcel {
/**
* 读取excel工作表方法
* @param filePath
* @return
* @throws IOException
*/
public List<List<String>> readExcel(String filePath) throws IOException {
/**
* rowData 用于存储读取的excel表的数据
*/
List<List<String>> rowData = new ArrayList<List<String>>();
FileInputStream in = null;
Workbook workBook = null;
try {
in = new FileInputStream(filePath);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
//读取03版本的excel表
if(filePath.toLowerCase().endsWith(".xls")){
workBook = new HSSFWorkbook(in);
}
//读取07版本的excel表
if(filePath.toLowerCase().endsWith(".xlsx")){
workBook = new XSSFWorkbook(in);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(workBook.getNumberOfSheets());
// 循环读取工作表
for (int numSheet = 0; numSheet < workBook.getNumberOfSheets(); numSheet++) {
//获得工作表对象
Sheet sheet = workBook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
// 循环行Row
// System.out.println("====头部:"+sheet.getHeader());
// System.out.println("====sheet名称:"+sheet.getSheetName());
// System.out.println("====获取最后一行:"+sheet.getLastRowNum());
for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
//获得工作表的行对象
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
// 循环列Cell
// System.out.println("====获取最后一列:"+row.getLastCellNum());
// arrCell:用于存储行的所有列
List<String> arrCell = new ArrayList<String>();
for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
//获得列对象
Cell cell = row.getCell(cellNum);
if (cell == null) {
continue;
}
//将列的值存入到List<String>集合中
arrCell.add(getValue(cell));
}
rowData.add(arrCell);
}
}
return rowData;
}
private String getValue(Cell cell) {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
public static void main(String[] args) throws IOException {
PaserExcel paser = new PaserExcel();
List<List<String>> rowData = new ArrayList<List<String>>();
rowData = paser.readExcel("D:\\test\\频道管理.xlsx");
for (List<String> cell : rowData) {
for (String str : cell) {
System.out.print(str + ", ");
}
System.out.println();
}
}
}