【问题标题】:How to write loop in excel (XLS) robot framework?如何在excel(XLS)机器人框架中编写循环?
【发布时间】:2017-01-26 00:46:53
【问题描述】:

我尝试使用下面的脚本将值写入 excel 文件 (XLS)。 有 4 行值,但输出只显示 1 行。

第二个问题:我可以使用现有文件吗?

*** Settings ***
Library           Collections
Library           WriteExcel.Excel

*** Variables ***

*** Test Cases ***
Write Excel Test
    [Tags]
    @{content}    Create List
    Append To List    ${content}    1    1    Test Case 1
    Append To List    ${content}    2    1    Test Case 2
    Append To List    ${content}    3    1    Test Case 3
    Append To List    ${content}    4    1    Test Case 4
    Write To Excel File    test3.xls    ${content}

这是我的 WriteExcel.py

import xlwt

class Excel(object):

    def __init__(self):
        print "write to excel file"

    def group(self,lst, n):

         return zip(*[lst[i:n] for i in range(n)])
    def write_to_excel_file(self,filename,content_list):

            # Create an new Excel file and add a worksheet.
            workbook = xlwt.Workbook()
            worksheet = workbook.add_sheet('wb')

            #content_lists=[1,1,'hello',2,1,'brother',3,1,'how are you',4,1,'are you good today']
            t=self.group(content_list,3)
            #print(t)
            for item in t:
                worksheet.write(int(item[0]), int(item[1]), item[2])


            # close work book
                workbook.save(filename)

This is my result

【问题讨论】:

  • 你的 t 恰好包含一个要迭代/写入文件的元组:>>> mylist = [1, 1, "Test 1", 2, 1, "Test 2", 3, 1, "Test 3", 4, 1, "Test 4"] >>> zip(*[mylist[i:3] for i in range (3)]) [(1, 1, 'Test 1')] 所以你需要在某处通过 n 迭代 group
  • 感谢您的建议

标签: python robotframework


【解决方案1】:

需要对组功能进行小改动

def group(self,lst, size):
    return ([lst[i:i+size] for i  in range(0, len(lst), size)])

是的,可以将数据添加到现有文件。参考下面的例子

https://stackoverflow.com/a/25144775/6626530 - 感谢@Chopra

import xlrd
import xlwt
from xlutils.copy import copy
def saveWorkSpace(fields):
    rb = xlrd.open_workbook('accounts.xls',formatting_info=True)
    r_sheet = rb.sheet_by_index(0) 
    r = r_sheet.nrows
    wb = copy(rb) 
    sheet = wb.get_sheet(0) 
    sheet.write(r,0,fields['name'])
    sheet.write(r,1,fields['phone'])
    sheet.write(r,2,fields['email'])
    wb.save('accounts.xls')
    print 'Wrote accounts.xls'

【讨论】:

  • 感谢您的建议,我将尝试将数据添加到现有文件中
猜你喜欢
  • 2018-08-09
  • 2020-12-29
  • 1970-01-01
  • 2016-03-15
  • 2020-02-19
  • 1970-01-01
  • 2016-11-18
  • 2015-12-08
  • 2017-04-20
相关资源
最近更新 更多