【java 菜鳥自動化實踐之二】採用POI將圖片存入指定的excel單元格中(支援excel2003和2007)
阿新 • • 發佈:2019-01-04
實現目的:selenium實時擷取瀏覽器圖,並採用POI將圖片存入指定的excel單元格中(支援excel2003和2007)
package common; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; /** * User: XZee Date: * 2011-10-10 Time: 16:10:29 */ public class write_excel { private static Logger log = Logger.getLogger(write_excel.class); /** 總行數 */ private int totalRows = 0; /** 總列數 */ private int totalCells = 0; /** 錯誤資訊 */ private static String errorInfo; private static XSSFWorkbook workbook; private static HSSFWorkbook workbook2; private static WebDriver driver; /** * 構造方法 * * @return */ public int getTotalRows() { return totalRows; } public int getTotalCells() { return totalCells; } public String getErrorInfo() { return errorInfo; } public static boolean validateExcel(String filePath) { /** 檢查檔名是否為空或者是否是Excel格式的檔案 */ if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) { errorInfo = "檔名不是excel格式"; return false; } /** 檢查檔案是否存在 */ File file = new File(filePath); if (file == null || !file.exists()) { errorInfo = "檔案不存在"; return false; } return true; } public static boolean isExcel2003(String filePath) { return filePath.matches("^.+\\.(?i)(xls)$"); } public static boolean isExcel2007(String filePath) { return filePath.matches("^.+\\.(?i)(xlsx)$"); } public static void update_Excel_Screenshot(String filePath, int sheetIndex, int row, int col, File value) { BufferedImage bufferImage = null; FileOutputStream fileOutputStream = null; try { FileInputStream fis = new FileInputStream(filePath); // 先把讀入的圖片放到第一個 ByteArrayOutputStream 中,用於產生ByteArray ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bufferImage = ImageIO.read(value); ImageIO.write(bufferImage, "JPEG", byteArrayOutputStream); if (!validateExcel(filePath)) { log.error(errorInfo); } if (isExcel2007(filePath)) { workbook = new XSSFWorkbook(fis); XSSFSheet sheet = workbook.getSheetAt(sheetIndex); // 準備插入圖片 XSSFDrawing patriarch = sheet.createDrawingPatriarch(); int cols = col + 1; int rows = row - 1; XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 100, 100, (short) col, rows, (short) cols, row); // anchor.setAnchorType(3); // 準備插入圖片 byte[] pictureData = byteArrayOutputStream.toByteArray(); int pictureFormat = XSSFWorkbook.PICTURE_TYPE_JPEG; int pictureIndex = workbook.addPicture(pictureData,pictureFormat); patriarch.createPicture(anchor, pictureIndex); } else if (isExcel2003(filePath)) { workbook2 = new HSSFWorkbook(fis); HSSFSheet sheet = workbook2.getSheetAt(sheetIndex); HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); int cols = col + 1; int rows = row - 1; // 準備插入圖片 HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 100, 100, (short) col, rows, (short) cols, row); byte[] pictureData = byteArrayOutputStream.toByteArray(); int pictureFormat = HSSFWorkbook.PICTURE_TYPE_JPEG; int pictureIndex = workbook.addPicture(pictureData, pictureFormat); patriarch.createPicture(anchor, pictureIndex); } fileOutputStream = new FileOutputStream(filePath); // 寫入excel workbook.write(fileOutputStream); byteArrayOutputStream.close(); fileOutputStream.close(); fis.close(); } catch (Exception e) { log.info(e.getMessage()); } finally { if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException io) { log.info(io.getMessage()); } } } } // 實時擷取頁面圖,並存入到excel中 public static void write_excel_Screenshot(String filePath, int i) throws Exception { try { // 截圖 File screenShotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); // 將圖片存入第1行的第3列的單元格中 update_Excel_Screenshot(filePath, 0, i, 3, screenShotFile); log.info("用例執行失敗後,成功儲存當前操作失敗的圖片!"); } catch (Exception e) { log.error(e.getMessage()); } } public static void main(String[] args) throws Exception { File file_chrome = new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chromedriver.exe"); System.setProperty("webdriver.chrome.driver", file_chrome.getAbsolutePath()); ChromeOptions options = new ChromeOptions(); options.addArguments("disable-infobars"); // 設定成使用者自己的資料目錄 options.addArguments("user-data-dir=C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\User Data"); // 開啟chrome瀏覽器 WebDriver driver = new ChromeDriver(options); System.out.println("End chrome browser..."); driver.get("http://www.baidu.com"); int row = 1; // 行 String filePath =".\\xxxxx\\xxxx.xlsx"; write_excel_Screenshot(filePath, row); } }