本人在學習使用selenium和UiAutomator的時候,學習了一excel文檔的操做,前兩天寫了一個讀取excel的方案,今天看了一下寫入excel的,暫時用的Map<Integer,List<String[]>>做爲寫入源。如今分享出來,但願能對你有所幫助。git
//寫入xlsx文檔 public static void writeXlsx(String filename, Map<Integer,List<String[]>> map) { String fileType = filename.substring(filename.lastIndexOf(".") + 1, filename.length());//提取文件名後綴 try { if (!fileType.equals("xlsx")) {//判斷文件名是否正確 output("文件名錯誤!"); } XSSFWorkbook wb = new XSSFWorkbook();//新建工做區 for(int sheetnum=0;sheetnum<map.size();sheetnum++){//遍歷表格 XSSFSheet sheet = wb.createSheet("第"+(sheetnum+1)+"個表格"); List<String[]> list = map.get(sheetnum+1);//取出須要寫入的表格內容,這裏須要+1才行 for(int i=0;i<list.size();i++){//遍歷行 XSSFRow row = sheet.createRow(i);//新建行 String[] str = list.get(i);//取出須要寫入的行信息 for(int j=0;j<str.length;j++){//遍歷寫入行單元格 XSSFCell cell = row.createCell(j);//建立單元格 cell.setCellValue(str[j]);//寫入單元格數據 } } } FileOutputStream outputStream = new FileOutputStream(filename);//新建輸出流 wb.write(outputStream);//寫入文件數據 outputStream.close();//關閉輸出流 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
這裏依然借鑑了前人的思路,本身根據需求優化了一些代碼,把方法從新寫了一遍。api
使用Excel主要爲了生成測試報告用的,在實際始終當中,效果通常般,Excel的普通格式比較簡單,好比設置顏色和文字格式等等,可是設計合併單元格和插入信息等格式就複雜多了,後期已經放棄。markdown