RobotFramework环境配置二十三:创建报告(Excel文件)

创建报告(Excel文件)

项目结束:Suite Teardown
主要目的:创建一份清晰的Excel报告
源代码:report.py

一、项目结束:Suite Teardown

在项目结束时,创建报告。

RobotFramework环境配置二十三:创建报告(Excel文件)_第1张图片

二、CSV vs. Excel报告

CSV文档无法调整格式,是以纯数据方式存储(参考个人博客CSV报告生成)。

RobotFramework环境配置二十三:创建报告(Excel文件)_第2张图片

Excel文档比较灵活,可以自定义格式。

RobotFramework环境配置二十三:创建报告(Excel文件)_第3张图片

二、数据源(测试结果)

Create Excel Report | %{G_TOTAL_RESULT}

数据源:%{G_TOTAL_RESULT} 在 Common_Test_Teardwon 中记录。

RobotFramework环境配置二十三:创建报告(Excel文件)_第4张图片
${TEST_NAME}:RIDE 自带变量,用例名
${TEST_STATUS}:RIDE 自带变量,用例状态(PASS 或者 FAIL)
${TEST MESSAGE}:RIDE 自带变量,用例报错信息

RobotFramework环境配置二十三:创建报告(Excel文件)_第5张图片

三、report.py 源代码

# -*- encoding = cp936 -*-
# Author: Allan
# Version: 2.0
# Data: 2017-5-9
import os, sys
import csv
import xlwt
import datetime

class report():
    def __init__(self):
        #Current Log Path:
        self.curr_dir = 'f:\\robotframework\\logs\\current'

    def Read_From_File(self, filename):
        # Read data from the given file
        file = os.path.join(self.curr_dir, filename) # Default File Path
        try:
            f = open(file)
            data = f.read()
        except Exception, e:
            print str(e)
        finally:
            f.close()

        return data

    def Write_To_CSV_File(self, filename, *data):
        """
        Write the values to the CSV file.

        """
        reload(sys)
        sys.setdefaultencoding('cp936') 

        with open(filename, 'wb') as csvfile:
            spamwriter = csv.writer(csvfile, dialect='excel')
            spamwriter.writerow(['Test Result'])
            spamwriter.writerow(['Case', 'Status', 'Error Message'])
            for row in data:
                for col in row:
                    print col
                    spamwriter.writerow(col)

    def Reorganize_Data(self, data):
        # Reorganize data for writing them to CSV file
        allList = []
        reorganized = data.split('|')
        for row in reorganized:
            allList.append(row.split(':'))
        return allList

    def Set_Style(self, name, height, colour=1, bold=False, pattern_colour=None):
        # default font style

        # Cell set alignment
        alignment = xlwt.Alignment()
        alignment.HORZ = xlwt.Alignment.HORZ_CENTER
        alignment.vert = xlwt.Alignment.VERT_CENTER

        # Cell add borders
        borders = xlwt.Borders()
        borders.left = xlwt.Borders.THIN
        borders.right = xlwt.Borders.THIN
        borders.top = xlwt.Borders.THIN
        borders.bottom = xlwt.Borders.THIN
        borders.left_colour = 0x40
        borders.right_colour = 0x40
        borders.top_colour = 0x40
        borders.bottom_colour = 0x40

        # Cell set font style
        font = xlwt.Font()
        font.name = name
        font.height = height
        font.colour_index = colour
        font.bold = bold

        if pattern_colour != None:
            # Cell set background colour
            pattern = xlwt.Pattern()
            pattern.pattern = xlwt.Pattern.SOLID_PATTERN
            pattern.pattern_fore_colour = pattern_colour

        style = xlwt.XFStyle()
        style.alignment = alignment
        if pattern_colour != None:
            # Cell set background colour
            style.pattern = pattern
        style.borders = borders
        style.font = font
        return style

    def Write_To_Excel_File(self, filename, *data):
        """
        Write the values to the Excel file.

        """
        reload(sys)
        sys.setdefaultencoding('cp936')

        try:
            xls_file = xlwt.Workbook()
            sheet1 = xls_file.add_sheet('Test Report', cell_overwrite_ok=True)

            # Cell set width of column
            col_wid = sheet1.col(0)
            col_wid.width = 256*60
            col_wid = sheet1.col(1)
            col_wid.width = 256*10
            col_wid = sheet1.col(2)
            col_wid.width = 256*60

            # Write report name & subtitle
            started_time = os.getenv('U_CUSTOM_TEST_TASK_START_TIME')
            generated_time = datetime.datetime.now()
            report_status = ['Start Time', '%s' % started_time, 'End Time', '%s' % str(generated_time)]
            row_status = ['Case', 'Status', 'Error Message']
            sheet1.write_merge(0, 3, 0, 0, 'Test Result', self.Set_Style('Arial', 210, 17, True))
            sheet1.write_merge(0, 3, 1, 1, '', self.Set_Style('Arial', 210, 1, True))
            for i in xrange(0, len(report_status)):
                sheet1.write(i, 2, report_status[i], self.Set_Style('Arial', 200, 63))

            for i in xrange(0, len(row_status)):
                sheet1.write(4, i, row_status[i], self.Set_Style('Arial', 200, 64, True, pattern_colour=22))

            # Write test result
            for value in data:
                for row in xrange(0, len(value)):
                    print value[row]
                    for col in xrange(len(value[row])):
                        sheet1.write(row+5, col, value[row][col], self.Set_Style('Arial', 200, 64))
        except IOError, e:
            print str(e)
        finally:
            xls_file.save(filename)

    def Create_CSV_Report(self, filename):
        # Create CSV Report | ${filename}
        file = os.path.join(self.curr_dir, 'report.csv') # Default File Path
        lines = self.Read_From_File(filename)
        data = self.Reorganize_Data(lines)
        self.Write_To_CSV_File(file, data)

    def Create_Excel_Report(self, filename):
        # Create Excel Report | ${filename}
        file = os.path.join(self.curr_dir, 'report.xls') # Default File Path
        lines = self.Read_From_File(filename)
        data = self.Reorganize_Data(lines)
        self.Write_To_Excel_File(file, data)

if __name__ == '__main__':
    report = report()
    report.Create_Excel_Report('Total_Result.log')

四、更多参考资料:
Examples Generating Excel Documents Using Python’s xlwt

Here are some simple examples using Python’s xlwt library to dynamically generate Excel documents.

Please note a useful alternative may be ezodf, which allows you to generate ODS (Open Document Spreadsheet) files for LibreOffice / OpenOffice. You can check them out at:http://packages.python.org/ezodf/index.html

The Simplest Example
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
worksheet.write(0, 0, label = 'Row 0, Column 0 Value')
workbook.save('Excel_Workbook.xls')

Formatting the Contents of a Cell
import xlwt
workbook = xlwt.Workbook(encoding = 'ascii')
worksheet = workbook.add_sheet('My Worksheet')
font = xlwt.Font() # Create the Font
font.name = 'Times New Roman'
font.bold = True
font.underline = True
font.italic = True
style = xlwt.XFStyle() # Create the Style
style.font = font # Apply the Font to the Style
worksheet.write(0, 0, label = 'Unformatted value')
worksheet.write(1, 0, label = 'Formatted value', style) # Apply the Style to the Cell
workbook.save('Excel_Workbook.xls')

Attributes of the Font Object
font.bold = True # May be: True, False
font.italic = True # May be: True, False
font.struck_out = True # May be: True, False
font.underline = xlwt.Font.UNDERLINE_SINGLE # May be: UNDERLINE_NONE, UNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC
font.escapement = xlwt.Font.ESCAPEMENT_SUPERSCRIPT # May be: ESCAPEMENT_NONE, ESCAPEMENT_SUPERSCRIPT, ESCAPEMENT_SUBSCRIPT
font.family = xlwt.Font.FAMILY_ROMAN # May be: FAMILY_NONE, FAMILY_ROMAN, FAMILY_SWISS, FAMILY_MODERN, FAMILY_SCRIPT, FAMILY_DECORATIVE
font.charset = xlwt.Font.CHARSET_ANSI_LATIN # May be: CHARSET_ANSI_LATIN, CHARSET_SYS_DEFAULT, CHARSET_SYMBOL, CHARSET_APPLE_ROMAN, CHARSET_ANSI_JAP_SHIFT_JIS, CHARSET_ANSI_KOR_HANGUL, CHARSET_ANSI_KOR_JOHAB, CHARSET_ANSI_CHINESE_GBK, CHARSET_ANSI_CHINESE_BIG5, CHARSET_ANSI_GREEK, CHARSET_ANSI_TURKISH, CHARSET_ANSI_VIETNAMESE, CHARSET_ANSI_HEBREW, CHARSET_ANSI_ARABIC, CHARSET_ANSI_BALTIC, CHARSET_ANSI_CYRILLIC, CHARSET_ANSI_THAI, CHARSET_ANSI_LATIN_II, CHARSET_OEM_LATIN_I
font.colour_index = ?
font.get_biff_record = ?
font.height = 0x00C8 # C8 in Hex (in decimal) = 10 points in height.
font.name = ?
font.outline = ?
font.shadow = ?

Setting the Width of a Cell
import xltw
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 'My Cell Contents')
worksheet.col(0).width = 3333 # 3333 = 1" (one inch).
workbook.save('Excel_Workbook.xls')

Entering a Date into a Cell
import xlwt
import datetime
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
style = xlwt.XFStyle()
style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0
worksheet.write(0, 0, datetime.datetime.now(), style)
workbook.save('Excel_Workbook.xls')

Adding a Formula to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, 5) # Outputs 5
worksheet.write(0, 1, 2) # Outputs 2
worksheet.write(1, 0, xlwt.Formula('A1*B1')) # Should output "10" (A1[5] * A2[2])
worksheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # Should output "7" (A1[5] + A2[2])
workbook.save('Excel_Workbook.xls')

Adding a Hyperlink to a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")')) # Outputs the text "Google" linking to http://www.google.com
workbook.save('Excel_Workbook.xls')

Merging Columns and Rows
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
worksheet.write_merge(0, 0, 0, 3, 'First Merge') # Merges row 0's columns 0 through 3.
font = xlwt.Font() # Create Font
font.bold = True # Set font to Bold
style = xlwt.XFStyle() # Create Style
style.font = font # Add Bold Font to Style
worksheet.write_merge(1, 2, 0, 3, 'Second Merge', style) # Merges row 1 through 2's columns 0 through 3.
workbook.save('Excel_Workbook.xls')

Setting the Alignment for the Contents of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
alignment = xlwt.Alignment() # Create Alignment
alignment.horz = xlwt.Alignment.HORZ_CENTER # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
alignment.vert = xlwt.Alignment.VERT_CENTER # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
style = xlwt.XFStyle() # Create Style
style.alignment = alignment # Add Alignment to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')

Adding Borders to a Cell
# Please note: While I was able to find these constants within the source code, on my system (using LibreOffice,) I was only presented with a solid line, varying from thin to thick; no dotted or dashed lines.
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
borders = xlwt.Borders() # Create Borders
borders.left = xlwt.Borders.DASHED # May be: NO_LINE, THIN, MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHED, THIN_DASH_DOTTED, MEDIUM_DASH_DOTTED, THIN_DASH_DOT_DOTTED, MEDIUM_DASH_DOT_DOTTED, SLANTED_MEDIUM_DASH_DOTTED, or 0x00 through 0x0D.
borders.right = xlwt.Borders.DASHED
borders.top = xlwt.Borders.DASHED
borders.bottom = xlwt.Borders.DASHED
borders.left_colour = 0x40
borders.right_colour = 0x40
borders.top_colour = 0x40
borders.bottom_colour = 0x40
style = xlwt.XFStyle() # Create Style
style.borders = borders # Add Borders to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')

Setting the Background Color of a Cell
import xlwt
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('My Sheet')
pattern = xlwt.Pattern() # Create the Pattern
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
pattern.pattern_fore_colour = 5 # May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, 17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
style = xlwt.XFStyle() # Create the Pattern
style.pattern = pattern # Add Pattern to Style
worksheet.write(0, 0, 'Cell Contents', style)
workbook.save('Excel_Workbook.xls')

TODO: Things Left to Document
- Panes -- separate views which are always in view
- Border Colors (documented above, but not taking effect as it should)
- Border Widths (document above, but not working as expected)
- Protection
- Row Styles
- Zoom / Manification
- WS Props?
Source Code for reference available at: https://secure.simplistix.co.uk/svn/xlwt/trunk/xlwt/

你可能感兴趣的:(Robotframework)