package ScriptLibrary

import java.awt.Color
import java.awt.GraphicsConfiguration.DefaultBufferCapabilities;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle
import org.apache.poi.xssf.usermodel.XSSFColor
import org.apache.poi.xssf.usermodel.XSSFDataFormat
import org.apache.poi.xssf.usermodel.XSSFFont
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem class WriteExcel { def testRunner
def context
def log WriteExcel(testRunner,context,log) {
this.testRunner = testRunner
this.context = context
this.log = log
} def parseFailMessage(String failMessage,def extraInfoMap){
//获取Test Suite和Test Case的名字
def currentStepIndex = context.currentStepIndex
def testCaseName = testRunner.testCase.getTestStepAt(currentStepIndex).getParent().getName()
def testSuiteName = testRunner.testCase.getTestStepAt(currentStepIndex).getParent().getParent().getName() //解析extraInfoMap
def valueList = extraInfoMap.values() //根据;分隔每一条错误信息
ArrayList failMessageList = new ArrayList()
String[] failMessageArray = failMessage.split(";") //遍历每一条错误信息,解析出每一列的值,便于写入Excel
for(int i=0;i<failMessageArray.size();i++){
//获取第i条错误信息
String oneFailMessage = failMessageArray[i] //从Expected:处进行分隔
int expectedIndex = oneFailMessage.indexOf("Expected:")
//从got:处进行分隔
int gotIndex = oneFailMessage.indexOf("got:") //解析错误信息中打印的JsonPath
String detailedJsonPath = oneFailMessage.substring(0,expectedIndex)
//解析JsonPath中的叶子节点
String lastLeafNode = detailedJsonPath.reverse().split("\\.")[0].reverse()
//解析Expected的值
String expectedValue = oneFailMessage.substring(expectedIndex,gotIndex).split(":")[1]
//解析Actual的值
String actualValue = oneFailMessage.substring(gotIndex).split(":")[1] //把需要输出的所有数据点拼接成一个list
def errorMessage = [testSuiteName,testCaseName]
errorMessage = errorMessage+valueList
errorMessage = errorMessage+[lastLeafNode,expectedValue,actualValue,detailedJsonPath] //把每条单独的list拼接成一个总的list返回
failMessageList.add(errorMessage)
}
return failMessageList
} def createExcel(File createFile, def topRow) {
String sheetName = "Automation Test";
try { XSSFWorkbook workbook = new XSSFWorkbook();
XSSFCellStyle cellStyleString = setCellStyleString(workbook)
XSSFCellStyle cellStyleTitle = setCellStyleTitle(workbook) int columnsNum = topRow.size();// calculate columns size by topRow
XSSFSheet sheet = workbook.createSheet(sheetName); int rownum = 0;
Row row = sheet.createRow(rownum++); int cellnum = 0;
for (String cellString : topRow) { Cell cell = row.createCell(cellnum++);
cell.setCellStyle(cellStyleString);
if (rownum == 1) {
cell.setCellStyle(cellStyleTitle);
}
// remove DIV style
if (cellString != null)
cellString = cellString.replaceAll('<(\\S*?)[^>]*>',"")
cell.setCellValue(cellString);// insert value
}
sheet = setSheetStyle(sheet, columnsNum -1);// setting sheet style FileOutputStream out = new FileOutputStream(createFile);
workbook.write(out);
out.flush();
out.close(); } catch (Exception e) {
e.printStackTrace();
}
} //向Excel中追加数据
def addExcel(String excelPath, ArrayList<String[]> failMessageList) throws IOException{
int columnsNum = failMessageList[0].size();// calculate columns size first row
FileInputStream fs = new FileInputStream(excelPath);//获取excel
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheetAt(0);//获取工作表
XSSFRow row = sheet.getRow(0);//获取第一行(即:字段列头,便于赋值)
int lastRowNum = sheet.getLastRowNum()
FileOutputStream out = new FileOutputStream(excelPath);//向excel中添加数据
for (int i = 0; i < failMessageList.size(); i++) {
row = sheet.createRow(++lastRowNum);//在现有行号后追加数据
String[] addOneRowData = failMessageList[i];
for(int j=0;j<addOneRowData.size();j++){
String str = addOneRowData[j];
row.createCell(j).setCellValue(str);//设置单元格的数据
}
}
sheet = setSheetStyle(sheet, columnsNum -1);// setting sheet style
wb.write(out);
out.flush();
out.close();
} def getExcelName( ) {
def currentStepIndex = context.currentStepIndex
def testCaseName = testRunner.testCase.getTestStepAt(currentStepIndex).getParent().getName()
def testSuiteName = testRunner.testCase.getTestStepAt(currentStepIndex).getParent().getParent().getName()
def excelName = testSuiteName + " _ " + testCaseName
excelName = excelName.replace(",","").replace(":","=").replace("/","").replace("*","")
return excelName
} def fillInFailMessage(File createFile, ArrayList<String[]> failMessageList, String[] topRow) {
String sheetName = "Automation Test";
try { XSSFWorkbook workbook = new XSSFWorkbook();
XSSFCellStyle cellStyleString = setCellStyleString(workbook)
XSSFCellStyle cellStyleTitle = setCellStyleTitle(workbook)
XSSFCellStyle cellStyleFail = setCellStyleFail(workbook)
XSSFCellStyle cellStyleNull = setCellStyleNull(workbook) failMessageList.add(0, topRow);
int columnsNum = topRow.length;// calculate columns size by topRow
XSSFSheet sheet = workbook.createSheet(sheetName); int rownum = 0;
for (int i = 0; i < failMessageList.size(); i++) { String[] rowStrings = failMessageList.get(i);
Row row = sheet.createRow(rownum++); int cellnum = 0;
for (String cellString : rowStrings) { Cell cell = row.createCell(cellnum++);
cell.setCellStyle(cellStyleString);
if (rownum == 1) {
cell.setCellStyle(cellStyleTitle); } else if (cellString != null && cellString.contains("%") && cellnum == columnsNum) {
Number number = NumberFormat.getInstance().parse(cellString); // If the actual deviation > 10%, change the cell color to red in the excel
if (number.doubleValue() > 10) {
cell.setCellStyle(cellStyleFail);
}
} else if ("null".equals(cellString) || "not null".equals(cellString)) {
// If cell value is "null" or "not null" change color to yellow in the excel
cell.setCellStyle(cellStyleNull);
}
// remove DIV style
if (cellString != null)
cellString = cellString.replaceAll('<(\\S*?)[^>]*>',"")
cell.setCellValue(cellString);// insert value
}
}
sheet = setSheetStyle(sheet, columnsNum -1);// setting sheet style FileOutputStream out = new FileOutputStream(createFile);
workbook.write(out);
out.flush();
out.close(); } catch (Exception e) {
e.printStackTrace();
}
} def XSSFSheet setSheetStyle(XSSFSheet sheet, int columnsNum) { sheet.createFreezePane(0, 1, 0, 1);
String columnRange = "A1:" + (char) (65 + columnsNum) + "1";
sheet.setAutoFilter(CellRangeAddress.valueOf(columnRange)); for (int i = 0; i <= columnsNum; i++)
sheet.autoSizeColumn(i); return sheet;
} def setCellStyleString(XSSFWorkbook workbook) {
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFDataFormat dataFormat = workbook.createDataFormat();
cellStyle.setDataFormat(dataFormat.getFormat("@"));
return cellStyle;
} def setCellStyleTitle(XSSFWorkbook workbook) {
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(new XSSFColor(new Color(131, 191, 90)));
return cellStyle;
} def setCellStyleFail(XSSFWorkbook workbook) {
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
cellStyle.setFillForegroundColor(new XSSFColor(new Color(255, 0, 0)));
return cellStyle;
} def setCellStyleNull(XSSFWorkbook workbook) {
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFFont fontStyle = workbook.createFont();
fontStyle.setColor(new XSSFColor(new Color(255, 0, 0)));
fontStyle.setBold(true);
cellStyle.setFont(fontStyle);
return cellStyle;
}
}

  

[Groovy] 创建Excel,追加Excel的更多相关文章

  1. C# 处理Excel公式(一)——创建、读取Excel公式

    对于数据量较大的表格,需要计算一些特殊数值时,我们通过运用公式能有效提高我们数据处理的速度和效率,对于后期数据的增删改查等的批量操作也很方便.此外,对于某些数值的信息来源,我们也可以通过读取数据中包含 ...

  2. C# -- 使用Aspose.Cells创建和读取Excel文件

    使用Aspose.Cells创建和读取Excel文件 1. 创建Excel Aspose.Cells.License li = new Aspose.Cells.License(); li.SetLi ...

  3. 使用poi读写excel、向excel追加数据等,包括.xls和.xlsx文档

    1.使用maven引入jar包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>p ...

  4. JS+Selenium+excel追加写入,使用python成功爬取京东任何商品~

    之前一直是requests库做爬虫,这次尝试下使用selenium做爬虫,效率不高,但是却没有限制,文章是分别结合大牛的selenium爬虫以及excel追加写入操作而成,还有待优化,打算爬取更多信息 ...

  5. [Asp.net]常见数据导入Excel,Excel数据导入数据库解决方案,总有一款适合你!

    引言 项目中常用到将数据导入Excel,将Excel中的数据导入数据库的功能,曾经也查找过相关的内容,将曾经用过的方案总结一下. 方案一 NPOI NPOI 是 POI 项目的 .NET 版本.POI ...

  6. java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)

    使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...

  7. c#导出Excel 使用EXCEL进程

    private void exportExcel(string filename, string path,string title, List<ArchivedWcsTask> wcst ...

  8. Laravel 5 中使用 Laravel Excel 实现 Excel/CSV 文件导入导出功能

    1.简介 Laravel Excel 在 Laravel 5 中集成 PHPOffice 套件中的 PHPExcel,从而方便我们以优雅的.富有表现力的代码实现Excel/CSV文件的导入和导出. 该 ...

  9. 在 Laravel 5 中使用 Laravel Excel 实现 Excel/CSV 文件导入导出功能

    1.简介 Laravel Excel 在 Laravel 5 中集成 PHPOffice 套件中的 PHPExcel ,从而方便我们以优雅的.富有表现力的代码实现Excel/CSV文件的导入和 导出  ...

随机推荐

  1. JavaScript数组方法大全(推荐)

    原网址:http://www.jb51.net/article/87930.htm 数组在笔试中经常会出现的面试题,javascript中的数组与其他语言中的数组有些不同,为了方便之后数组的方法学习, ...

  2. feign的hystrix不起作用.

    在springCloud中使用feign内嵌的断路器hystrix时.feign中的hystrix不起作用.这可能是由于springCloud的版本原因造成的.需要在application.prope ...

  3. 已知一个函数rand7()能够生成1-7的随机数,请给出一个函数rand10(),该函数能够生成1-10的随机数。

    题目: 已知一个函数rand7()能够生成1-7的随机数,请给出一个函数,该函数能够生成1-10的随机数. 思路: 假如已知一个函数能够生成1-49的随机数,那么如何以此生成1-10的随机数呢? 解法 ...

  4. Docker 网络不通的解决方法

    表现是: docker主机内部网络正常,与其它主机的连接失效,其它主机不能连接docker主机上映射的端口,docker内部也无法连接外部主机. 执行docker info,可以看到一些警告. 可在不 ...

  5. pandas中关于DataFrame 去除省略号

    #显示所有列 pd.set_option('display.max_columns', None) #显示所有行 pd.set_option('display.max_rows', None) #设置 ...

  6. CentOS 下搭建Jenkins

    1.下载安装包 A 可以连接外网: 导入仓库 wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins.io/redhat-stable/jen ...

  7. HDU5532 Almost Sorted Array(最长上升子序列 or 瞎搞个做差的数组)

    题目链接:点我 题意:给定一个序列,询问是否能删除一个数让它成为非递减或者非递增的序列. 比如说 删除后的序列是1 3 3 5 或者5 3 3 1 或者1 3 5 或者5 3 1 都可以.只要满足删掉 ...

  8. TZOJ 2588 Bad Grass(DFS)

    描述 Bessie was munching on tender shoots of grass and, as cows do, contemplating the state of the uni ...

  9. f5 SNAT

    request过程: 1.真实源地址(3.3.3.3)将数据包发给f5虚拟的vs地址(1.1.1.5:80): 2.f5将真实源地址(3.3.3.3)转换成SNAT地址(1.1.1.100),并将vs ...

  10. SpringBoot08 请求方式、参数获取注解、参数验证、前后台属性名不一致问题、自定义参数验证注解、BeanUtils的使用

    1 请求方式 在定义一个Rest接口时通常会利用GET.POST.PUT.DELETE来实现数据的增删改查:这几种方式有的需要传递参数,后台开发人员必须对接收到的参数进行参数验证来确保程序的健壮性 1 ...