以下内容为测试代码:
packagecom.lzz.hssf;
importjava.io.FileInputStream;
importjava.io.InputStream;
importjava.util.Iterator;
importorg.apache.poi.hssf.extractor.ExcelExtractor;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFDateUtil;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 读取上篇中的xls文件的内容,并打印出来
*/
public classPoiReadTable {
/**读取一个excel文件的内容 */
public static void main(String[] args) throwsException {
//extractor();
readTable();
}
//对单元格遍历的形式来获取信息
public static void readTable() throwsException{
InputStream ips=new FileInputStream("d://test2-1.xls");
HSSFWorkbook wb=newHSSFWorkbook(ips);
HSSFSheet sheet=wb.getSheetAt(0);
for(Iterator ite=sheet.rowIterator();ite.hasNext();){
HSSFRow row=(HSSFRow)ite.next();
System.out.println();
for(Iterator itet=row.cellIterator();itet.hasNext();){
HSSFCell cell=(HSSFCell)itet.next();
switch(cell.getCellType()){
caseHSSFCell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue()+" ");
break;
caseHSSFCell.CELL_TYPE_NUMERIC:
//检查是否是日期格式
if(HSSFDateUtil.isCellDateFormatted(cell)){
//读取日期格式
System.out.print(cell.getDateCellValue()+" ");
}else{
//读取数字
System.out.print(cell.getNumericCellValue()+" ");
}
break;
caseHSSFCell.CELL_TYPE_FORMULA:
//读取公式
System.out.print(cell.getCellFormula()+" ");
break;
caseHSSFCell.CELL_TYPE_STRING:
//读取String
System.out.print(cell.getRichStringCellValue().toString()+" ");
break;
}
}
}
}
//抽取excel中的数据
public static void extractor() throwsException{
InputStream ips=new FileInputStream("d://test2-1.xls");
HSSFWorkbook wb=newHSSFWorkbook(ips);
ExcelExtractor ex=newExcelExtractor(wb);
ex.setFormulasNotResults(true);
ex.setIncludeSheetNames(false);
String text=ex.getText();
System.out.println(text);
}
}