数据驱动第一章节:使用Apache POI实现对Excel的操作

1.Apache POI 简介

   POI是Apache提供的开源库,主要依赖于Apache POI(HSSF+ XSSF),它支持Excel 库的所有基本功能;

2.主要的操作类

数据驱动第一章节:使用Apache POI实现对Excel的操作

数据驱动第一章节:使用Apache POI实现对Excel的操作

3.本博客以xlsx为例,fromxls.xlsx的内容如下:

数据驱动第一章节:使用Apache POI实现对Excel的操作

4.具体操作类如下:

package com.common;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.filechooser.FileSystemView;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
 * @Description:该类的功能描述
 * @ClassName:FromXls.java
 * @version:v1.0.0
 * @author:bingkele
 * @date:2020年5月30日上午10:16:27
 */
public class FromXls {
    /**
     * @Description:获取文件模板,当未创建时进行创建,并返回此文件
     * @ClassName:getFileTemplate
     * @return File  
     * @version:v1.0.0
     * @author:bingkele
     * @date:2020年5月31日下午15:51:11
     */
    public static File getFileTemplate() throws IOException{
        String projectPath=System.getProperty("user.dir");  //获取工作目录,即和src在同一目录
        String filePath = projectPath+"/fromxls.xlsx";
        File file = new File(filePath);
        if(!file.exists()){                                        //若文件不存在则创建文件
            file.createNewFile();
            //写入模板
            FileOutputStream outputStream = new FileOutputStream(file);
            XSSFWorkbook workBook = new XSSFWorkbook();              //创建工作薄
            XSSFSheet sheet = workBook.createSheet("Sheet1");     //创建表
            XSSFRow row = sheet.createRow(0);                     //创建行
            row.createCell(0).setCellValue("#编号");               //创建单元格并赋值
            row.createCell(1).setCellValue("#定位方式");
            row.createCell(2).setCellValue("#控件值");
            row.createCell(3).setCellValue("#备注");        
            workBook.setActiveSheet(0);                            //**表单
            workBook.write(outputStream);
            outputStream.close();
        }                
        return file;
    }
    /**
     * @Description:向xls中写入数据
     * @ClassName:createElementData
     * @param EleNumber
     *        控件编号
     * @param ElePositionMethod
     *        控件定位方式
     * @param ElePositionValue
     *        控件值
     * @param content
     *        备注                  
     * @version:v1.0.0
     * @author:bingkele
     * @date:2020年5月31日下午15:51:11
     */
    public static void createElementData(String EleNumber,String ElePositionMethod,String ElePositionValue,String content){                
        FileInputStream fs;
        try{
            fs = new FileInputStream(getFileTemplate());      //读取已存在的文件
//            POIFSFileSystem ps = new POIFSFileSystem(fs);
//            HSSFWorkbook wb=new HSSFWorkbook(ps);
            XSSFWorkbook  wb = new XSSFWorkbook(fs);         //创建工作薄,将文件输入流作为入参
            XSSFSheet sheet = wb.getSheetAt(0);              //获取工作表
            XSSFRow row = sheet.getRow(0);                   //获取行
            int hang=0;
            if("".equals(row)||row==null){                  //当行为null或为空时将行置为0
                hang=0;
            }else{
                 hang=sheet.getLastRowNum();               //获取行数,从0开始
                 hang=hang+1;                               //行+1为需要写的行数
            }       
            FileOutputStream out=new FileOutputStream(getFileTemplate());  //获取文件输出流
            row=sheet.createRow(hang);                                     //常见需要写的行
            row.createCell(0).setCellValue(EleNumber);                     //写入元素
            row.createCell(1).setCellValue(ElePositionMethod);
            row.createCell(2).setCellValue(ElePositionValue);
            row.createCell(3).setCellValue(content);
            out.flush();                                                   //刷新输出流
            wb.write(out);  
            out.close();                                                   //关闭输出流
        }catch(IOException e){
            e.printStackTrace();
        }
        
    }
    /**
     * @Description:获取全部的xls数据
     * @ClassName:getAllXlsData
     * @version:v1.0.0
     * @author:bingkele
     * @date:2020年5月31日下午15:51:11
     */
    public static void getAllXlsData() throws FileNotFoundException, IOException{
        FileInputStream fs = new FileInputStream(getFileTemplate());
        BufferedInputStream bs = new BufferedInputStream(fs);
        XSSFWorkbook wb = new XSSFWorkbook(bs);
        XSSFSheet sheet = wb.getSheetAt(0);                       //获取工作表 
        int lastRowIndex = sheet.getPhysicalNumberOfRows();       //获取物理行数,从1开始
        for(int i = 0;i<lastRowIndex;i++){
            XSSFRow row = sheet.getRow(i);                        
            if(row == null){
                break;
            }
            short lastCellNum = row.getLastCellNum();             //获取每行的单元格数
            for(int j = 0;j<lastCellNum;j++){
                String cellValue = row.getCell(j).getStringCellValue();     //获取列的值
                System.out.println(cellValue);
            }
        }        
       bs.close();
    }
    /**
     * @Description:获取xls的指定元素
     * @ClassName:getXlsParaContent
     * @param CustomField
     *        传入的指定参数名
     * @version:v1.0.0
     * @author:bingkele
     * @date:2020年5月31日下午15:51:11
     */
    public static String getXlsParaContent(String CustomField) throws FileNotFoundException, IOException{
        String field = null;
        FileInputStream fs = new FileInputStream(getFileTemplate());
        BufferedInputStream bs = new BufferedInputStream(fs);
        XSSFWorkbook wb = new XSSFWorkbook(bs);
        XSSFSheet sheet = wb.getSheetAt(0);
        int lastRowIndex = sheet.getPhysicalNumberOfRows();
        for(int i = 1;i<lastRowIndex;i++){
            XSSFRow row = sheet.getRow(i);
            if(row == null){
                break;
            }
            if(row.getCell(0).getStringCellValue().equals(CustomField)){ //当第一列的值为入参CustomField时进行赋值
                field = row.getCell(2).getStringCellValue();
                break;
            }
        }
        bs.close();
        return field;
    }

}
5.使用testNG进行测试

package com.testngdemo;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.filechooser.FileSystemView;
import org.testng.annotations.Test;
import com.common.FromXls;
public class TestFromXls {
  @Test
  public void createXlsData() throws Exception{  //添加元素
      FromXls.createElementData("@loginEntr", "cssSelector", "#span_userinfo > a:nth-child(1)", "登录入口");
      FromXls.createElementData("@loginName", "cssSelector", "#LoginName", "用户名");
      FromXls.createElementData("@password", "cssSelector", "#Password", "密码");
      FromXls.createElementData("@loginsubmit", "cssSelector", "#submitBtn > span.ladda-label", "提交按钮");      
  }
  @Test
  public void getAllXlsData() throws FileNotFoundException, IOException{  //输出所有元素
      FromXls.getAllXlsData();
  }
  @Test
  public void getCustomXlsData() throws FileNotFoundException, IOException{    //获取指定控件元素
      System.out.println("控件元素:"+FromXls.getXlsParaContent("@loginsubmit"));
      
  }
}
6.结果如下(打印太多,只截一部分):

数据驱动第一章节:使用Apache POI实现对Excel的操作

7.依赖包如下:数据驱动第一章节:使用Apache POI实现对Excel的操作