操纵Excel文件的 ExcelUtil 类 !

  1 package FileDemo1;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 
  9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 10 import org.apache.poi.ss.usermodel.Row;
 11 import org.apache.poi.ss.usermodel.Sheet;
 12 import org.apache.poi.ss.usermodel.Workbook;
 13 import org.apache.poi.xssf.usermodel.XSSFCell;
 14 import org.apache.poi.xssf.usermodel.XSSFRow;
 15 import org.apache.poi.xssf.usermodel.XSSFSheet;
 16 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 17 
 18 public class ExcleUtil {
 19     private static XSSFSheet ExcelWSheet;
 20     private static XSSFWorkbook ExcelWBook;
 21     private static XSSFCell Cell;
 22     private static XSSFRow Row;
 23 
 24     // 设定要设置的Excel的文件路径和Excel 中Sheet名;
 25     // 在读/写Excel 的时候先要调用此方法
 26     public static void setExcleFile(String FilePath, String sheetName) throws Exception {
 27         FileInputStream ExcleFile;
 28         try {
 29             // 实例化Excle文件的FileInputStream 对象;
 30             ExcleFile = new FileInputStream(FilePath);
 31             // 实例化Excle文件的XSSFWorkbook 对象;
 32             ExcelWBook = new XSSFWorkbook(ExcleFile);
 33             /*
 34              * 实例化XSSFSheet 对象,指定ExcelFile中的sheet名称,用于后续对sheet中行和列的操作;
 35              * 
 36              */
 37             ExcelWSheet = ExcelWBook.getSheet(sheetName);
 38 
 39         } catch (Exception e) {
 40             e.getStackTrace();
 41         }
 42     }
 43     /*
 44      * 读取excle文件指定单元格的函数 ;
 45      * 
 46      */
 47 
 48     public static String getCell(int row, int col) throws Exception {
 49 
 50         try {
 51             // 通过函数参数指定单元格的行号和列,获取指定单元格的对象;
 52             Cell = ExcelWSheet.getRow(row).getCell(col);
 53             /*
 54              * 1.如果单元格的类型为字符串类型,使用getStringCellValue();来获取单元格的内容;
 55              * 2.如果单元格的类型为数字类型,使用getNumberricCellValue();来获取单元格的内容;
 56              * 注意:getNumberricCellValue();返回的值为double类型,转为为字符串类型,必须在
 57              * getNumberricCellValue();前面加上(" ")双引号,用于强制转换为String类型,不加双引号
 58              * 则会抛错;double类型无法转换为String类型的异常;
 59              * 
 60              */
 61             String CellData = Cell.getCellType() == XSSFCell.CELL_TYPE_STRING ? Cell.getStringCellValue() + ""
 62                     : String.valueOf(Math.round(Cell.getNumericCellValue()));
 63             return CellData;
 64         } catch (Exception e) {
 65             e.getStackTrace();
 66             return "";
 67         }
 68 
 69     }
 70     /*
 71      * 在Excle中执行单元格写入数据;
 72      * 
 73      * 
 74      */
 75 
 76     public static void setCellData(int rownum, int colnum, String Result) throws Exception {
 77 
 78         try {
 79             // 获取excle文件的中行对象;
 80             Row = ExcelWSheet.getRow(rownum);
 81             // 如果单元格为空则返回null;
 82             Cell = Row.getCell(colnum, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL);
 83             if (Cell == null) {
 84                 // 当单元格为空是则创建单元格
 85                 // 如果单元格为空无法调用单元格对象的setCellValue方法设定单元格的值 ;
 86                 Cell = Row.createCell(colnum);
 87                 // 创建单元格和后可以通过调用单元格对象的setCellValue方法设置单元格的值了;
 88                 Cell.setCellValue(Result);
 89             } else {
 90                 // 单元格中有内容,则可以直接调用单元格对象的 setCellValue 方法来设置单元格的值;
 91                 Cell.setCellValue(Result);
 92             }
 93             FileOutputStream fileout = new FileOutputStream(Constant.testDataExcelFilePath);
 94             // 将内容写到Excel文件中 ;
 95             ExcelWBook.write(fileout);
 96             // j调用flush方法强制刷新写入文件;
 97             fileout.flush();
 98             fileout.close();
 99 
100         } catch (Exception e) {
101             System.out.println(e.getMessage() + e.getStackTrace());
102             throw (e);
103         }
104 
105     }
106 
107     public static void TangsetCellData(int RowNum, int ColNum, String Result) {
108         try {
109             // 获取行对象
110             Row = ExcelWSheet.getRow(RowNum);
111             // 如果单元格为空,则返回null
112             Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
113             if (Cell == null) {
114                 // 当单元格对象是Null时,则创建单元格
115                 // 如果单元格为空,无法直接调用单元格的setCellValue方法设定单元格的值
116                 Cell = Row.createCell(RowNum);
117                 // 调用setCellValue方法设定单元格的值
118                 Cell.setCellValue(Result);
119             } else {
120                 // 单元格中有内容,则可以直接调用seCellValue方法设定单元格的值
121                 Cell.setCellValue(Result);
122             }
123             // 实例化写入Excel文件的文件输出流对象
124             FileOutputStream fileOut = new FileOutputStream(Constant.testDataExcelFilePath);
125             // 将内容写入Excel中
126             ExcelWBook.write(fileOut);
127             fileOut.flush();
128             fileOut.close();
129         } catch (Exception e) {
130             // TODO: handle exception
131             e.printStackTrace();
132         }
133     }
134 
135     // 从excel 文件中获取测试数据的静态方法;
136     public static Object[][] getTestData(String excelFilePath, String sheetName) throws Exception {
137         // 根据参数传入的数据文件路径和文件名称,组合出Excel 数据文件的绝对路径
138         // 声明一个文件;
139         File file = new File(excelFilePath);
140         // 创建FileInputStream 来读取Excel文件内容;
141         FileInputStream inputStream = new FileInputStream(file);
142         // 声明Workbook 对象;
143         Workbook workbook = null;
144         // 获取文件名参数的扩展名,判断是“.xlsx” 还是 “.xls” ;
145         String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf('.'));
146         if (fileExtensionName.equals(".xlsx")) {
147             workbook = new XSSFWorkbook(inputStream);
148 
149         } else if (fileExtensionName.equals(".xls")) {
150             workbook = new HSSFWorkbook(inputStream);
151 
152         }
153         Sheet sheet = workbook.getSheet(sheetName);
154         // 获取Excel 数据文件Sheet1 中数据的行数,getLastRowNum 方法获取数据的最后一行的行号,
155         // getFistRowNum 获取第一行 最后一行减去第一行就是总行数了
156         // 注意excle 的行和列都是从0开始的;
157         int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
158         // 创建名为records 的List对象来存储从Excel文件中读取的数据;
159         List<Object[]> records = new ArrayList<Object[]>();
160         // 使用for循环遍历Excel 数据文件的所有数据(除了第一行,第一行为标题行),所以i从1开始而不是从0开始;
161 
162         for (int i = 1; i < rowCount + 1; i++) {
163             // 使用getRow来获取行对象;
164             Row row = sheet.getRow(i);
165             /*
166              * 声明一个数据,用来存储Excel数据文件每行中的测试用例和数据,数据的大小用getLastCellNum-2
167              * 来进行动态声明,实现测试数据个数和数组大小一致,
168              * 因为Excel数据文件中的测试数据行的最后一个单元格是测试执行结果,倒数第二个单元格为此测试数据行是否运行的状态位,
169              * 所以最后俩列的单元格数据并
170              * 不需要传入测试方法中,所以是用getLastCellNum-2的方式去掉每行中的最后俩个单元格数据,计算出需要存储的测试数据个数,
171              * 并作为测试数据数组的初始化大小
172              * 
173              */
174             String fields[] = new String[row.getLastCellNum() - 2];
175 
176             /*
177              * 判断数据行是否要参与测试的执行,Excel 文件的倒数第二列为数据行的状态位, 标记为“y”
178              * 表示此数据行要被测试脚本执行,标记为非“y”的数据行均被认为不会参数测试脚本执行,会被跳过;
179              */
180 
181             if (row.getCell(row.getLastCellNum() - 2).getStringCellValue().equals("y")) {
182                 for (int j = 0; j < row.getLastCellNum() - 2; j++) {
183                     /*
184                      * 判断Excel 单元格的内容是数字还是字符, 字符格式调用:
185                      * row.getCell(j).getStringCellValue();
186                      * 数字格式调用:row.getCell(j).getNumericCellValue();
187                      */
188                     fields[j] = (String) (row.getCell(j).getCellType() == XSSFCell.CELL_TYPE_STRING
189                             ? row.getCell(j).getStringCellValue() : "" + row.getCell(j).getNumericCellValue());
190 
191                 }
192                 // fields 存储到数组当中;
193                 records.add(fields);
194 
195             }
196         }
197 
198         /*
199          * 定义函数的返回值,即Object[] [] 将存储测试数据的list 转换为一个Object 的二维数组;
200          */
201         Object[][] results = new Object[records.size()][];
202         for (int i = 0; i < records.size(); i++) {
203             results[i] = records.get(i);
204         }
205 
206         return results;
207 
208     }
209 
210     public static int getLastColumnNum() {
211 
212         return ExcelWSheet.getRow(0).getLastCellNum() - 1;
213     }
214 
215 }
原文地址:https://www.cnblogs.com/linbo3168/p/6170086.html