POI之导入Excel

注:请根据实际的开发情况更改方法

1.导入依赖

 
 
 org.apache.poi
 poi
 3.6
 
 
 org.apache.poi
 poi-ooxml
 3.17
 
 
 org.apache.poi
 poi-scratchpad
 3.17
 
POI之导入Excel

2.工具类方法(请根据实际应用更改)

 /**
 *
 * @param filePath:文件地址(D:/123.xls)
 * @param column:表格列数
 */
 public static void getDataFromExcel(String filePath,int column) {
 //判断是否为excel类型文件
 if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx")) {
 System.out.println("文件不是excel类型");
 }
 FileInputStream fis =null;
 Workbook wookbook = null;
 try {
 //获取一个绝对地址的流
 fis = new FileInputStream(filePath);
 } catch(Exception e) {
 e.printStackTrace();
 }
 try {
 //2003版本的excel,用.xls结尾
 wookbook = new HSSFWorkbook(fis);//得到工作簿
 } catch (Exception ex) {
 //ex.printStackTrace();
 try {
 //2007版本的excel,用.xlsx结尾
 wookbook = new XSSFWorkbook(fis);//得到工作簿
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
 //得到一个工作表
 Sheet sheet = wookbook.getSheetAt(0);
 //获得表头
 Row rowHead = sheet.getRow(0);
 //判断表头是否正确
 if(rowHead.getPhysicalNumberOfCells() != column) {
 System.out.println("表头的数量不对!");
 }
 //获得数据的总行数
 int totalRowNum = sheet.getLastRowNum();
 //要获得属性
 String on="";
 String name = "";
 String age = "";
 //获得所有数据
 for(int i = 1 ; i <= totalRowNum ; i++)
 {
 //获得第i行对象
 Row row = sheet.getRow(i);
 //获得获得第i行第0列
 Cell cell = row.getCell((short)0);
 on = cell.getStringCellValue();
 //获得获得第i行第1列
 cell = row.getCell((short)1);
 name = cell.getStringCellValue();
 //获得获得第i行第2列
 cell = row.getCell((short)2);
 age = cell.getStringCellValue();
 System.out.println("编号:"+on+",名字:"+name+",年龄:"+age);
 }
 }
POI之导入Excel

3.测试

@Test
 public void t1(){
 getDataFromExcel("D:\\下载\\人员档案列表.xls",3);
 }
POI之导入Excel

表格内容:

POI之导入Excel

POI之导入Excel

结果如下:

POI之导入Excel

POI之导入Excel


分享到:


相關文章: