[Groovy] 创建Excel,追加Excel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
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;
    }
}

  

posted on   张缤分  阅读(1188)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2017-10-17 [SoapUI] Groovy获取HTTP Status

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示