1. 程式人生 > >Java + Excel 接口自動化

Java + Excel 接口自動化

cell src tex 表達式 zip flush ren 必須 開心

最近項目比較悠閑,想找點事幹,寫了個 Excel 接口測試的 "框架" 以前用 python 寫過一個,這次用 java, 應該說框架都不算,反正就是寫了,能幫我解決問題就行。

當然咯,也許會問幹嘛那麽麻煩直接用 feed4testng, 或者 testng 就行了,沒事找事幹還專門寫個這玩意... 呵呵,就閑的蛋疼!

文筆有限不知道怎麽寫,直接上代碼:

歡迎各位指定,或提出好的意見,總覺得還有很多不好的地方。

結構就這破樣了, E 文也不好, 隨便搗鼓,開心就好。 哈哈

技術分享圖片

ExcelUtil.java 類:

技術分享圖片 技術分享圖片
  1 package com.hozhu.excel;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.IOException;
  8 import java.util.ArrayList;
  9 import java.util.HashMap;
 10 import java.util.List;
 11 import java.util.Map;
 12 
 13 import org.apache.log4j.Logger;
 14 import org.apache.poi.ss.usermodel.CellStyle;
 15 import org.apache.poi.ss.usermodel.IndexedColors;
 16 import org.apache.poi.xssf.usermodel.XSSFCell;
 17 import org.apache.poi.xssf.usermodel.XSSFCellStyle;
 18 import org.apache.poi.xssf.usermodel.XSSFRow;
 19 import org.apache.poi.xssf.usermodel.XSSFSheet;
 20 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 21 
 22 /**
 23  * 只支持讀取 .xlsx 所有方法讀取數據時, 未對 Excel 格式類型進行判斷處理 如 Excel 中有特殊數據類型, 需在 Excel
 24  * 中標註為文本類型, 程序才能正常處理
 25  * 
 26  * @author Roger
 27  * @version 1.0
 28  */
 29 public class ExcelUtil {
 30     private static Logger logger = Logger.getLogger(ExcelUtil.class);
 31 
 32     private String filePath = null;
 33     private String sheetName = null;
 34 
 35     public String getSheetName() {
 36         return sheetName;
 37     }
 38 
 39     public void setSheetName(String sheetName) {
 40         this.sheetName = sheetName;
 41     }
 42 
 43     public String getFilePath() {
 44         return filePath;
 45     }
 46 
 47     public void setFilePath(String filePath) {
 48         this.filePath = filePath;
 49     }
 50 
 51     /**
 52      * 判斷成員變量 filePath 是否為空
 53      * 
 54      * @return
 55      */
 56     private boolean isFilePathEmpty() {
 57         boolean flag = false;
 58         if ((null != filePath && (!filePath.equals("")))) {
 59             flag = true;
 60         }
 61         return flag;
 62     }
 63 
 64     private boolean isSheetNameEmpty() {
 65         boolean flag = false;
 66         if ((null != sheetName && (!sheetName.equals("")))) {
 67             flag = true;
 68         }
 69         return flag;
 70     }
 71 
 72     // 使用靜態內部類創建外部類對象
 73     private static class Excel {
 74         private static ExcelUtil excelUtil = new ExcelUtil();
 75     }
 76 
 77     private ExcelUtil() {
 78     }
 79 
 80     // 獲取 ExcelUtil 實例
 81     public static ExcelUtil getInstance() {
 82         return Excel.excelUtil;
 83     }
 84 
 85     /**
 86      * 檢查傳入的文件後綴是否為 xlsx
 87      * 
 88      * @param filePacht
 89      * @return
 90      */
 91     public boolean checkXlsx(File file) {
 92         boolean flag = false;
 93 
 94         if (file.exists()) {
 95             String str = file.getName();
 96             if (str.substring(str.lastIndexOf(".") + 1).equals("xlsx"))
 97                 flag = true;
 98         } else {
 99             logger.info(file.getName() + ", 文件不存在...");
100             // System.out.println("文件不存在...");
101         }
102 
103         return flag;
104     }
105 
106     /**
107      * 
108      * @param file
109      * @return true: 文件未被操作; false: 文件正在被操作.
110      */
111     public boolean isFile(File file) {
112         return file.renameTo(file);
113     }
114 
115     public File createFile() {
116         File file = null;
117         if (isFilePathEmpty()) {
118             file = new File(filePath);
119         } else {
120             logger.error("filePath 不能為: "
121                     + filePath
122                     + ", 請先使用 ‘ExcelUtil.getInstance().setFilePath(filePath)‘ 設置!");
123             // System.out.println("filePath 不能為: " + filePath +
124             // ", 請先使用 ‘ExcelUtil.getInstance().setFilePath(filePath)‘ 設置!");
125             System.exit(-1);
126         }
127         return file;
128     }
129 
130     /**
131      * 創建 XSSFWorkbook
132      * 
133      * @param 文件路徑
134      * @return
135      */
136     public XSSFWorkbook createExcelWorkBook() {
137         File file = createFile();
138 
139         BufferedInputStream in = null;
140         XSSFWorkbook book = null;
141 
142         if (checkXlsx(file)) {
143             try {
144                 in = new BufferedInputStream(new FileInputStream(file));
145                 book = new XSSFWorkbook(in);
146             } catch (IOException e) {
147                 e.printStackTrace();
148             }
149         }
150         return book;
151     }
152 
153     /**
154      * 創建 XSSFSheet
155      * 
156      * @param sheetName
157      * @return
158      */
159     public XSSFSheet createExcelSheet(String sheetName) {
160         XSSFSheet sheet = null;
161         if (isSheetNameEmpty()) {
162             XSSFWorkbook book = createExcelWorkBook();
163             if (book != null) {
164                 int sheetCount = book.getNumberOfSheets();
165                 for (int i = 0; i < sheetCount; i++) {
166                     if (sheetName.equals(book.getSheetName(i))) {
167                         sheet = book.getSheet(sheetName);
168                         break;
169                     }
170                 }
171             }
172         } else {
173             logger.error("sheetName 不能為: "
174                     + sheetName
175                     + ", 請先使用 ‘ExcelUtil.getInstance().setSheetName(SheetName)‘ 設置!");
176             // System.out.println("sheetName 不能為: " + sheetName +
177             // ", 請先使用 ‘ExcelUtil.getInstance().setSheetName(SheetName)‘ 設置!");
178             System.exit(-1);
179         }
180 
181         return sheet;
182     }
183 
184     /**
185      * 獲取指定行
186      * 
187      * @param sheetName
188      * @param line
189      *            行索引, 從 0 開始
190      * @return
191      */
192     public XSSFRow getExcelRow(int line) {
193         XSSFRow row = null;
194         if (line <= getSheetMaxRow())
195             row = createExcelSheet(sheetName).getRow(line);
196         return row;
197     }
198 
199     /**
200      * 獲取指定 sheet 中最大行數
201      * 
202      * @param sheetName
203      * @return
204      */
205     public int getSheetMaxRow() {
206         int maxRow = -1;
207         if (createExcelSheet(sheetName) != null)
208             maxRow = createExcelSheet(sheetName).getLastRowNum();
209         return maxRow;
210     }
211 
212     /**
213      * 使用正則表達式去掉多余的.與0
214      * 
215      * @param s
216      * @return
217      */
218     private String subZeroAndDot(String s) {
219         if (s.indexOf(".") > 0) {
220             // 去掉多余的 0
221             s = s.replaceAll("0+?$", "");
222             // 如果最後一位是.則去掉
223             s = s.replaceAll("[.]$", "");
224         }
225         return s;
226     }
227 
228     /**
229      * 獲取 Excel 指定行數據
230      * 
231      * @param sheetName
232      * @param line
233      * @return 返回一個一維數組
234      */
235     public String[] readExcelRows(int line) {
236         String[] result = null;
237         XSSFRow row = getExcelRow(line);
238         int maxRow = getSheetMaxRow();
239         if (row != null && maxRow > -1) {
240             int columnNum = row.getLastCellNum();
241             result = new String[columnNum];
242             for (int i = 0; i < columnNum; i++) {
243                 // 判斷單元格是否為空, 不進行判斷時, 如遇到空白單元格時, 拋出空指針異常
244                 if (null != row.getCell(i))
245                     result[i] = subZeroAndDot(row.getCell(i).toString().trim());
246             }
247         }
248         return result;
249     }
250 
251     /**
252      * 獲取指定單元格中內容
253      * 
254      * @param sheetName
255      * @param line
256      *            行
257      * @param column
258      *            列
259      * @return
260      */
261     public String readExcelCell(int line, int column) {
262         String[] value = null;
263         String result = "";
264         value = readExcelRows(line);
265         if (value != null) {
266             result = value[column];
267         }
268         return result;
269     }
270 
271     /**
272      * 從指定行開始讀取 Excel 中所有數據
273      * 
274      * @param sheetName
275      *            sheet 名稱
276      * @param line
277      *            表標題所在行
278      * @return 返回一個包含 HashMap<String, String> 的 ArrayList; 格式:[{第一行數據},{第二行數據}]
279      *         {列 1 標題 = 列 1 值, 列 2 標題 = 列 2 值}
280      */
281     public List<Map<String, String>> readExcelAllData(int line) {
282         List<Map<String, String>> result = new ArrayList<Map<String, String>>();
283         // 讀取標題行
284         String[] titleRow = readExcelRows(line);
285         int maxRow = getSheetMaxRow();
286         XSSFRow row;
287         if (null != titleRow && maxRow != -1) {
288             // i = line + 1; 標題的下一行開始取數據
289             for (int i = line + 1; i <= maxRow; i++) {
290                 row = getExcelRow(i);
291                 Map<String, String> map = new HashMap<String, String>();
292                 for (int j = 0; j < row.getLastCellNum(); j++) {
293                     if (null != row.getCell(j)) {
294                         String value = subZeroAndDot(row.getCell(j).toString()
295                                 .trim());
296                         map.put(titleRow[j], value);
297                     }
298                 }
299                 result.add(map);
300             }
301         }
302         return result;
303     }
304 
305     /**
306      * 從指定數據行開始讀取 Excel 所有數據
307      * 
308      * @param sheetName
309      *            sheet 名稱
310      * @param line
311      *            數據讀取開始行
312      * @return
313      */
314     public String[][] readDataArrayAll(int line) {
315         ArrayList<Object> list = new ArrayList<Object>();
316         int maxRow = getSheetMaxRow();
317         XSSFRow row = null;
318         int columnNum = 0;
319         if (maxRow != -1) {
320             for (int i = line; i <= maxRow; i++) {
321                 row = getExcelRow(i);
322                 columnNum = row.getLastCellNum();
323                 String[] values = new String[columnNum];
324 
325                 for (int j = 0; j < columnNum; j++) {
326                     if (null != row.getCell(j)) {
327                         String tempStr = subZeroAndDot(row.getCell(j)
328                                 .toString().trim());
329                         values[j] = tempStr;
330                     }
331                 }
332                 list.add(values);
333             }
334         }
335 
336         String[][] result = new String[list.size()][columnNum];
337 
338         for (int i = 0; i < result.length; i++) {
339             result[i] = (String[]) list.get(i);
340         }
341         return result;
342     }
343 
344     /**
345      * 從指定數據行開始讀取 Excel 所有數據
346      * 
347      * @param sheetName
348      *            sheet 名稱
349      * @param line
350      *            數據讀取開始行
351      * @return 返回一個包含 list 的 list; 格式 [[第一行數據],[第二行數據]]
352      */
353     public List<List<String>> readDataListAll(int line) {
354         List<List<String>> result = new ArrayList<List<String>>();
355 
356         int maxRow = getSheetMaxRow();
357         XSSFRow row = null;
358 
359         if (maxRow != -1) {
360             for (int i = line; i <= maxRow; i++) {
361                 row = getExcelRow(i);
362                 List<String> list = new ArrayList<String>();
363                 for (int j = 0; j < row.getLastCellNum(); j++) {
364                     if (null != row.getCell(j)) {
365                         String value = subZeroAndDot(row.getCell(j).toString()
366                                 .trim());
367                         list.add(value);
368                     }
369                 }
370                 result.add(list);
371             }
372         }
373         return result;
374     }
375 
376     /**
377      * 將數據寫入指定單元格
378      * 
379      * @param sheetName
380      *            sheet 名稱
381      * @param line
382      *            需寫入的行
383      * @param column
384      *            需寫入的列
385      * @param content
386      *            需寫入的內容
387      * @throws IOException
388      */
389     public void writeExcelCell(int line, int column, String content)
390             throws IOException {
391         XSSFWorkbook book = createExcelWorkBook();
392         XSSFSheet sheet = book.getSheet(sheetName);
393 
394         if (line <= sheet.getLastRowNum() && line >= 0) {
395             XSSFRow row = sheet.getRow(line);
396 
397             if (column < row.getLastCellNum() && column >= 0) {
398                 if (isFile(createFile())) {
399                     FileOutputStream out = new FileOutputStream(createFile());
400                     XSSFCell cell = row.getCell(column);
401                     if (null == cell) {
402                         cell = row.createCell(column);
403                     }
404                     cell.setCellValue(content);
405                     book.write(out);
406                     out.close();
407                 } else {
408                     logger.error("文件: " + filePath + ", 正被使用, 請關閉! 程序執行終止...");
409                     // System.out.println("文件: " + filePath
410                     // + ", 正被使用, 請關閉! 程序執行終止...");
411                     System.exit(-1);
412                 }
413             } else
414                 logger.error("列索引越界...");
415             // System.out.println("列索引越界...");
416         } else
417             logger.error("行索引越界...");
418         // System.out.println("行索引越界...");
419     }
420     
421     /**
422      * 從指定行的下一行開始讀取某列的所有數據
423      * @param titleLineIndex  指定行讀取
424      * @param columnName         列名
425      * @return
426      */
427     public String[] readExcelColumnData(int titleLineIndex, String columnName) {
428         String[] result = null;
429         int columnIndex = getColumnIndex(titleLineIndex, columnName);
430         int maxRow = getSheetMaxRow();
431 
432         if (columnIndex != -1 && maxRow != -1) {
433             result = new String[maxRow - titleLineIndex];
434             
435             for (int i = 0; i < maxRow - titleLineIndex; i++) {
436                 result[i] = readExcelCell(titleLineIndex + 1 + i, columnIndex);
437             }
438         }
439         return result;
440     }
441     
442 
443     /**
444      * 獲取列的索引
445      * 
446      * @param sheetName
447      *            sheet 名稱
448      * @param line
449      *            需要獲取的行
450      * @param columnName
451      *            列名
452      * @return
453      */
454     public int getColumnIndex(int line, String columnName) {
455         int index = -1;
456         String[] title = readExcelRows(line);
457 
458         if (null != title) {
459             for (int i = 0; i < title.length; i++) {
460                 if (columnName.equals(title[i]))
461                     index = i;
462             }
463         }
464         return index;
465     }
466 
467     /**
468      * 設置單元格背景色
469      * 
470      * @param sheetName
471      *            sheet 名稱
472      * @param titleRow
473      *            列標題所在行號, 索引 0 開始
474      * @param columnName
475      *            需要獲取列索引的列名稱
476      * @param line
477      *            需要設置顏色單元格所在行
478      * @param color
479      *            需設置的顏色; 0: 紅色; 1: 綠色; 2: 灰色; 3: 黃色; 4: 白色.
480      * @throws IOException
481      */
482     public void setCellBackgroundColor(int titleRow, String columnName,
483             int line, int color) throws IOException {
484         XSSFWorkbook book = createExcelWorkBook();
485         XSSFSheet sheet = book.getSheet(sheetName);
486 
487         int columnIndex = getColumnIndex(titleRow, columnName);
488         XSSFRow row = sheet.getRow(line);
489         XSSFCell cell = row.getCell(columnIndex);
490         XSSFCellStyle old = cell.getCellStyle();
491         XSSFCellStyle temp = book.createCellStyle();
492         temp.cloneStyleFrom(old); // 拷貝舊的樣式
493 
494         switch (color) {
495         case 0:
496             // 紅色
497             temp.setFillForegroundColor(IndexedColors.RED.getIndex());
498             break;
499         case 1:
500             // 綠色
501             temp.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
502             break;
503         case 2:
504             // 灰色
505             temp.setFillForegroundColor(IndexedColors.GREY_50_PERCENT
506                     .getIndex());
507             break;
508         case 3:
509             // 黃色
510             temp.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
511             break;
512         case 4:
513             // 白色
514             temp.setFillForegroundColor(IndexedColors.WHITE.getIndex());
515             break;
516         default:
517             System.out.println("設定顏色參數 (color) 錯誤...");
518             break;
519         }
520 
521         temp.setFillPattern(CellStyle.SOLID_FOREGROUND);
522         // XSSFFont font = book.createFont();
523         // font.setFontHeightInPoints((short)9); // 字體大小
524         // font.setFontName("宋體");
525         // temp.setFont(font);
526         cell.setCellStyle(temp);
527         if (isFile(createFile())) {
528             FileOutputStream out = new FileOutputStream(createFile());
529             book.write(out);
530             out.close();
531         } else {
532             logger.error("文件: " + filePath + ", 正被使用, 請關閉! 程序執行終止...");
533             // System.out.println("文件: " + filePath + ", 正被使用, 請關閉! 程序執行終止...");
534             System.exit(-1);
535         }
536     }
537 
538 }
技術分享圖片 技術分享圖片

HttpRequester.java類:

技術分享圖片 技術分享圖片
  1 package com.hozhu.api;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStreamReader;
  6 import java.io.PrintWriter;
  7 import java.net.HttpURLConnection;
  8 import java.net.URL;
  9 import java.util.HashMap;
 10 import java.util.Map;
 11 
 12 public class HttpRequester {
 13     /**
 14      * 向指定 URL 發送POST方法的請求
 15      * 
 16      * @param method
 17      *            指定請求方法:GET, POST 等
 18      * @param url
 19      *            發送請求的 URL
 20      * @param param
 21      *            請求參數,請求參數是 name1=value1&name2=value2 的形式。
 22      * @return result 返回結果
 23      */
 24     public static Map<String, String> sendPost(String method, String url,
 25             String param) {
 26         PrintWriter out = null;
 27         BufferedReader br = null;
 28         String result = "";
 29         int responseCode = 0;
 30         Map<String, String> map = new HashMap<String, String>();
 31         try {
 32             // 打開和URL之間的連接
 33             HttpURLConnection httpConn = (HttpURLConnection) new URL(url)
 34                     .openConnection();
 35 
 36             // 發送POST請求必須設置如下兩行
 37             // 設置可輸入、 可輸出
 38             httpConn.setDoInput(true);
 39             httpConn.setDoOutput(true);
 40 
 41             httpConn.setReadTimeout(150000);
 42             httpConn.setConnectTimeout(15000);
 43 
 44             // 連接後不自動跳轉
 45             httpConn.setInstanceFollowRedirects(false);
 46 
 47             // 設置通用的請求屬性
 48             httpConn.setRequestProperty("Accept-Charset", "utf-8");
 49             httpConn.setRequestProperty("User-Agent", "systempatch");
 50             httpConn.setRequestProperty("Accpet-Encoding", "gzip");
 51 
 52             // 設置提交方式
 53             httpConn.setRequestMethod(method);
 54 
 55             // httpConn.connect();
 56 
 57             // 獲取HttpURLConnection對象對應的輸出流
 58             out = new PrintWriter(httpConn.getOutputStream());
 59 
 60             // 發送請求參數
 61             out.print(param);
 62             out.flush();
 63             responseCode = httpConn.getResponseCode();
 64             map.put("code", String.valueOf(responseCode));
 65             // 打印 http 狀態碼
 66             // System.out.println("responseCode: " + responseCode);
 67 
 68             if (HttpURLConnection.HTTP_OK == responseCode) {
 69                 // 定義BufferedReader輸入流來讀取URL的響應
 70                 br = new BufferedReader(new InputStreamReader(
 71                         httpConn.getInputStream(), "utf-8"));
 72                 String strLine;
 73                 StringBuffer responseBuf = new StringBuffer();
 74 
 75                 while ((strLine = br.readLine()) != null) {
 76                     responseBuf.append(strLine);
 77                 }
 78 
 79                 result = responseBuf.toString();
 80                 map.put("result", result);
 81             }
 82 
 83         } catch (Exception e) {
 84             System.out.println("發送 POST 請求出現異常!" + e);
 85             e.printStackTrace();
 86         }
 87         // 使用finally塊來關閉輸出流、輸入流
 88         finally {
 89             try {
 90                 if (out != null) {
 91                     out.close();
 92                 }
 93                 if (br != null) {
 94                     br.close();
 95                 }
 96             } catch (IOException ex) {
 97                 ex.printStackTrace();
 98             }
 99         }
100         return map;
101     }
102 }
技術分享圖片 技術分享圖片

MobileApiTools.java 類

技術分享圖片 技術分享圖片
  1 package com.hozhu.api;
  2 
  3 import java.io.IOException;
  4 import java.text.SimpleDateFormat;
  5 import java.util.Date;
  6 
  7 import com.hozhu.excel.ExcelUtil;
  8 
  9 public class MobileApiTools {
 10     private MobileApiTools() {
 11     }
 12 
 13     /**
 14      * 獲取當前系統時間
 15      * 
 16      * @return
 17      */
 18     public static String getDate() {
 19         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 20         return df.format(new Date());
 21     }
 22 
 23     /**
 24      * 期望結果與實際結果比較
 25      * 
 26      * @param expectedResult
 27      * @param actualResult
 28      * @return
 29      */
 30     public static String assertResult(String expectedResult, String actualResult) {
 31         String result;
 32         if (expectedResult.equals(actualResult))
 33             result = "OK";
 34         else
 35             result = "NG";
 36         return result;
 37 
 38     }
 39 
 40     /**
 41      * 初始化 Excel 中指定列數據
 42      * 
 43      * @param filePath
 44      *            文件路徑
 45      * @param sheetName
 46      *            sheet 名稱
 47      * @param titleLineIndex
 48      *            表標題所在行索引
 49      * @param columnName
 50      *            列名稱
 51      * @param content
 52      *            需寫入的內容
 53      * @param color
 54      *            需設置的單元格顏色
 55      * @throws IOException
 56      */
 57     public static void initializeData(int titleLineIndex, String columnName,
 58             String content, int color) throws IOException {
 59         int maxRow = ExcelUtil.getInstance().getSheetMaxRow();
 60         int columnIndex = ExcelUtil.getInstance().getColumnIndex(
 61                 titleLineIndex, columnName);
 62         if (maxRow != -1 && columnIndex != -1) {
 63             for (int i = titleLineIndex + 1; i <= maxRow; i++) {
 64                 // 初始化單元格內容
 65                 ExcelUtil.getInstance().writeExcelCell(i, columnIndex, content);
 66                 // 設置單元格顏色
 67                 ExcelUtil.getInstance().setCellBackgroundColor(titleLineIndex,
 68                         columnName, i, color);
 69             }
 70         }
 71     }
 72 
 73     /**
 74      * 將執行結果寫入 Excel 中
 75      * 
 76      * @param filePath
 77      *            文件路徑
 78      * @param sheetName
 79      *            sheet 名稱
 80      * @param titleLineIndex
 81      *            標題所在索引行
 82      * @param writeStartRow
 83      *            寫入起始行
 84      * @param columnName
 85      *            列名稱
 86      * @param content
 87      *            寫入內容
 88      */
 89     public static void writeResult(int titleLineIndex, int writeStartRow,
 90             String columnName, String content) {
 91 
 92         int columnIndex = ExcelUtil.getInstance().getColumnIndex(
 93                 titleLineIndex, columnName);
 94         if (columnIndex != -1) {
 95             try {
 96                 ExcelUtil.getInstance().writeExcelCell(writeStartRow,
 97                         columnIndex, content);
 98             } catch (IOException e) {
 99                 e.printStackTrace();
100             }
101         }
102     }
103 
104     /**
105      * 表標題行是否包含指定參數
106      * @param argLineIndex            參數名稱所在單元格行索引
107      * @param argColumnIndex        參數名稱所在單元格列索引
108      * @param titleLineIndex        表標題所在行索引
109      * @return
110      */
111     public static boolean isArgEquals(int argLineIndex, int argColumnIndex,
112             int titleLineIndex) {
113         String[] argArray = null;
114         boolean flag = false;
115         
116         // 獲取所在單元格的參數列表
117         String args = ExcelUtil.getInstance().readExcelCell(argLineIndex, argColumnIndex);
118         if (!args.equals("")) {
119             argArray = args.split("\\|");
120         } else {
121             System.out.println("文件: " + ExcelUtil.getInstance().getFilePath()
122                     + ", sheetName: " + ExcelUtil.getInstance().getSheetName()
123                     + ", 獲取參數失敗...");
124         }
125         
126         if (argArray != null) {
127             for (int i = 0; i < argArray.length; i++) {
128                 int tempIndex = ExcelUtil.getInstance().getColumnIndex(
129                         titleLineIndex, argArray[i]);
130                 if (tempIndex >= 0)
131                     flag = true;
132                 else
133                     System.out.println("參數: " + argArray[i]
134                             + ", 不存在表標題行中, 請檢查...");
135             }
136         }
137         return flag;
138     }
139 
140     public void info() {
141         
142     }
143 }
技術分享圖片 技術分享圖片

LoginAPI.java 類

技術分享圖片 技術分享圖片
  1 package com.hozhu.cases;
  2 
  3 import java.io.IOException;
  4 import java.util.List;
  5 import java.util.Map;
  6 
  7 import org.apache.log4j.Logger;
  8 import org.json.JSONException;
  9 import org.json.JSONObject;
 10 
 11 import com.hozhu.api.HttpRequester;
 12 import com.hozhu.api.MobileApiTools;
 13 import com.hozhu.excel.ExcelUtil;
 14 
 15 public class LoginAPI {
 16     private static Logger logger = Logger.getLogger(LoginAPI.class);
 17     
 18     private final String FILE_PATH = "mobileApiCase.xlsx";
 19     private final String SHEET_NAME = "Login";
 20     private final int TITLE_LINE_INDEX = 4;
 21 
 22     private final String RESULT_CODE = "ResultCode";
 23     private final String TEST_RESULT = "TestResult";
 24     private final String RUNNING_TIME = "RunningTime";
 25     private final String ACTUAL_RESULT = "ActualResult";
 26     private final String RUN = "Run";
 27 
 28     // 需要的參數常量
 29     private final String MAIL = "mail";
 30     private final String MOBILE = "mobile";
 31     private final String PASS_WORD = "password";
 32     
 33     public LoginAPI() {
 34         try {
 35             logger.info(LoginAPI.class);
 36             
 37             ExcelUtil.getInstance().setFilePath(FILE_PATH);
 38             ExcelUtil.getInstance().setSheetName(SHEET_NAME);
 39             
 40             logger.info("初始化: " + ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName());
 41             
 42             MobileApiTools.initializeData(TITLE_LINE_INDEX, RUN, "N", 4);
 43             MobileApiTools.initializeData(TITLE_LINE_INDEX, ACTUAL_RESULT, "",
 44                     4);
 45             MobileApiTools.initializeData(TITLE_LINE_INDEX, RESULT_CODE, "", 4);
 46             MobileApiTools.initializeData(TITLE_LINE_INDEX, TEST_RESULT, "NT",
 47                     2);
 48             MobileApiTools
 49                     .initializeData(TITLE_LINE_INDEX, RUNNING_TIME, "", 4);
 50             
 51             logger.info(ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName() + "初始化完成");
 52         } catch (IOException e) {
 53             e.printStackTrace();
 54         }
 55     }
 56 
 57     public void login() throws JSONException, IOException {
 58         String url = "";
 59         String act = "";
 60         String method = "";
 61         List<Map<String, String>> data = null;
 62         boolean flag = false;
 63 
 64         url = ExcelUtil.getInstance().readExcelCell(0, 1);
 65         act = ExcelUtil.getInstance().readExcelCell(1, 1);
 66         method = ExcelUtil.getInstance().readExcelCell(2, 1);
 67         flag = MobileApiTools.isArgEquals(3, 1, TITLE_LINE_INDEX);
 68 
 69         if (url.equals("") || act.equals("") || method.equals("") || !flag) {
 70             logger.error("請檢查 Excel 中 Interface、Act、Method、ArgName 是否設置正確...");
 71             //System.out
 72             //        .println("請檢查 Excel 中 Interface、Act、Method、ArgName 是否設置正確...");
 73             System.exit(-1);
 74         }
 75 
 76         data = ExcelUtil.getInstance().readExcelAllData(4);
 77 
 78         if (data != null) {
 79             for (int i = 0; i < data.size(); i++) {
 80                 Map<String, String> map = data.get(i);
 81                 String mail = map.get(MAIL);
 82                 String mobile = map.get(MOBILE);
 83                 String password = map.get(PASS_WORD);
 84                 String state = map.get("State");
 85                 String expectedResult = map.get("ExpectedResult");
 86                 String loginName;
 87 
 88                 // 如果 state == 0 則用 郵箱登錄, 否則使用手機號碼登錄
 89                 if (Integer.parseInt(state) == 0)
 90                     loginName = mail;
 91                 else
 92                     loginName = mobile;
 93 
 94                 String param = "Act=" + act + "&" + "LoginName=" + loginName
 95                         + "&" + "Pwd=" + password;
 96 
 97                 Map<String, String> result = HttpRequester.sendPost(method,
 98                         url, param);
 99                 String code = result.get("code");
100                 String rsTmp = result.get("result");
101 
102                 // 將字符串轉換為 JSON
103                 JSONObject object = new JSONObject(rsTmp);
104                 String actualResult = object.getString("msg");
105 
106                 String testResult = MobileApiTools.assertResult(expectedResult,
107                         actualResult);
108 
109                 // 寫入 Run 列, 執行紀錄
110                 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX
111                         + 1 + i, RUN, "Y");
112 
113                 // 寫入 http code
114                 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX
115                         + 1 + i, RESULT_CODE, code);
116 
117                 // 設置單元格顏色
118                 if (Integer.parseInt(code) == 200)
119                     ExcelUtil.getInstance().setCellBackgroundColor(
120                             TITLE_LINE_INDEX, RESULT_CODE,
121                             TITLE_LINE_INDEX + 1 + i, 1);
122                 else
123                     ExcelUtil.getInstance().setCellBackgroundColor(
124                             TITLE_LINE_INDEX, RESULT_CODE,
125                             TITLE_LINE_INDEX + 1 + i, 1);
126 
127                 // 寫入實際結果
128                 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX
129                         + 1 + i, ACTUAL_RESULT, actualResult);
130 
131                 // 寫入測試通過與否
132                 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX
133                         + 1 + i, TEST_RESULT, testResult);
134 
135                 if (testResult.equals("OK"))
136                     ExcelUtil.getInstance().setCellBackgroundColor(
137                             TITLE_LINE_INDEX, TEST_RESULT,
138                             TITLE_LINE_INDEX + 1 + i, 1);
139                 else
140                     ExcelUtil.getInstance().setCellBackgroundColor(
141                             TITLE_LINE_INDEX, TEST_RESULT,
142                             TITLE_LINE_INDEX + 1 + i, 0);
143 
144                 // 寫入執行時間
145                 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX
146                         + 1 + i, RUNNING_TIME, MobileApiTools.getDate());
147                 
148                 logger.info("CaseID: " + map.get("CaseID") + ", CaseName: " + map.get("CaseName") + ", ExpectedResult: " +
149                 map.get("ExpectedResult") + ", ActualResult: " + actualResult + ", ResultCode: " + code +
150                 ", TestResult: " + testResult);
151             }
152         }
153 
154     }
155     
156     public static void main(String[] args) throws JSONException, IOException {
157         LoginAPI loginAPI = new LoginAPI();
158         loginAPI.login();
159 
160     }
161 
162 }
技術分享圖片 技術分享圖片

RunCase.java : 所有的 case 都放這裏運行

技術分享圖片 技術分享圖片
 1 package com.hozhu.cases;
 2 
 3 import java.io.IOException;
 4 
 5 import org.json.JSONException;
 6 import org.testng.Assert;
 7 import org.testng.annotations.Test;
 8 
 9 import com.hozhu.excel.ExcelUtil;
10 
11 public class RunCase {
12     @Test
13     public void testLogin() throws JSONException, IOException {
14         LoginAPI login = new LoginAPI();
15         login.login();
16         String [] result = ExcelUtil.getInstance().readExcelColumnData(4, "TestResult");
17         for (int i = 0; i < result.length; i++) {
18             Assert.assertEquals(result[i], "OK");
19         }
20     }
21 }
技術分享圖片 技術分享圖片

好了, 上傳完畢,等等, 還有那 excel 也上截圖吧,呵呵

技術分享圖片

原文:https://www.cnblogs.com/peng-lan/p/5335654.html

Java + Excel 接口自動化