我在测试的时候经常需要去改动case,如果把所有case直接写在单元测试中,非常冗余,我希望可以直接从excel去读取我的测试数据,经过几次试验终于成功了,读取excel主要借助poi jar包,源码如下所示。poi jar包下载地址http://down.51cto.com/data/2012838
ps:因为测试数据仅string类型已够用,所以代码只支持string类型的cell 内容,如果是想支持其他数据类型,需要进一步对cell内容进行判断,此处略过~
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; 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 readExcelSelf { public static void main (String[] args) throws IOException{ String filePath = "F:\\ExcelDemo.xlsx"; FileInputStream isr = new FileInputStream(filePath); BufferedInputStream bis = new BufferedInputStream(isr); int startRowIndex = 1;//从指定行开始读取数据,因为通常第一行都是作为标题行 String[][] content = getContent(bis,startRowIndex);//excel的数据存如"行*列"的二维数组 bis.close(); int contentLength = content.length; for (int i=0;i<contentLength;i++){ for(int j=0;j<content[i].length;j++){ System.out.print(content[i][j]+"\t"); } System.out.println(); } } private static String[][] getContent(BufferedInputStream bis, int sri) throws IOException { XSSFWorkbook xw = new XSSFWorkbook(bis); XSSFRow row = null; XSSFCell cell = null; XSSFSheet sheet = null; List<String[]> rowArrays = new ArrayList<String[]>(); int maxColumnSize = 0; for (int i=0;i<xw.getNumberOfSheets();i++){ sheet = xw.getSheetAt(i); for (int rowIndex=sri;rowIndex<=sheet.getLastRowNum();rowIndex++){ row = sheet.getRow(rowIndex); if(row == null){ continue; } int columnSize = row.getLastCellNum(); if(columnSize>maxColumnSize){ maxColumnSize = columnSize; } String[] rowValue = new String[columnSize]; Arrays.fill(rowValue, ""); boolean isRowValueNull = false; for (int columnIndex=0;columnIndex<columnSize;columnIndex++){ cell = row.getCell(columnIndex); if(cell== null || cell.getStringCellValue().trim().equals("")){ continue; } else{ rowValue[columnIndex]=cell.getStringCellValue(); } isRowValueNull = true; } if(isRowValueNull){ rowArrays.add(rowValue); } } } String[][] rowColumnArray = new String[rowArrays.size()][maxColumnSize]; for(int i=0;i<rowArrays.size();i++){ rowColumnArray[i]=rowArrays.get(i); } return rowColumnArray; } }
原文地址:http://smileyes.blog.51cto.com/6027700/1626369