1、导入的jar包
dom4j-1.6.1.jar
poi-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
xmlbeans-2.3.0.jar
2、读取Excel2007中的内容,并在控制台打印
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class TestExcel { public static String filePath = "E:\userTemplate.xlsx"; public static void main(String[] args) { try {
FileInputStream is = new FileInputStream(filePath); //创建对Excel工作簿文件的引用 XSSFWorkbook wookbook = new XSSFWorkbook(is); // 在Excel文档中,第一张工作表的缺省索引是0 // 其语句为:HSSFSheet sheet = workbook.getSheetAt(0); XSSFSheet sheet = wookbook.getSheet("人员信息"); //获取到Excel文件中的所有行数 int rows = sheet.getPhysicalNumberOfRows(); System.out.println(rows); for(int i=0;i<rows;i++){ //读取左上端单元格 XSSFRow row = sheet.getRow(i); //行不为空 if(row != null){ //获取到Excel文件中的所有列 int cells = row.getPhysicalNumberOfCells(); String value = ""; //遍历列 for(int j=0;j<cells;j++){ //获取到列的值 XSSFCell cell = row.getCell(j); if(cell != null){ switch (cell.getCellType()){ case XSSFCell.CELL_TYPE_FORMULA: break; case XSSFCell.CELL_TYPE_NUMERIC: value += cell.getNumericCellValue()+","; break; case XSSFCell.CELL_TYPE_STRING: value += cell.getStringCellValue()+","; break; default: value +="0"; break; } } } System.out.println(value); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }