package cn.poi.com;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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;
import org.apache.poi.ss.usermodel.Cell;
public class ReadExcelUtils {
/**
* @param pathName
* @throws IOException
* @throws FileNotFoundException
*/
public void readExcel(String pathName) throws IOException,
FileNotFoundException {
//1.找到一个已经存在的excel(工作簿)
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(pathName));
readSheetsFromWorkbook(workbook);
}
/**
* 读取所有的工作表
* @param workbook
*/
private void readSheetsFromWorkbook(HSSFWorkbook workbook) {
//2.选定一个工作表
for(int sheetIndex = 0;sheetIndex<workbook.getNumberOfSheets();sheetIndex++){
HSSFSheet sheet = workbook.getSheetAt(sheetIndex);
System.out.println("工作表名称:"+sheet.getSheetName());
readRowFromSheet(sheet);
}
}
/**
* 读取所有行
* @param sheet
*/
private void readRowFromSheet(HSSFSheet sheet) {
//3.选定行
for(int rowIndex = 0;;rowIndex++){
HSSFRow row = sheet.getRow(rowIndex);
if(row==null){
break;
}
readCellValueFromRow(row);
System.out.println();
}
}
/**
* 读取一行的所有列
* @param row
*/
private void readCellValueFromRow(HSSFRow row) {
//4.选定列,单元格
for(int cellnum = 0; ; cellnum++){
HSSFCell cell = row.getCell(cellnum);
if(cell==null){
break;
}
// int cellType = cell.getCellType();
// if(Cell.CELL_TYPE_NUMERIC==cellType){
// double cellValue = cell.getNumericCellValue();
// if(cellnum!=0){
// System.out.print("\t");
// }
// System.out.print(cellValue);
// }else if(Cell.CELL_TYPE_STRING==cellType){
// String cellValue = cell.getStringCellValue();
// if(cellnum!=0){
// System.out.print("\t");
// }
// System.out.print(cellValue);
// }
//魔法方法:把各种类型统一转成string类型
//5.根据单元格的类型调用不同的取值方法
cell.setCellType(Cell.CELL_TYPE_STRING);
String cellValue = cell.getStringCellValue();
if(cellnum!=0){
System.out.print("\t");
}
System.out.print(cellValue);
}
}
}
评论1
最新资源