python xlwt 搜索特定值

2024-06-16 08:29:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我用xlrd编写了一个脚本,从多个excel文件的多个单元格中提取多个数据,并使用xlwt将这些数据写入一个新的excel文件。在新的excel文件中,我添加了另外两行,其中包含计算平均值和测试时间的公式。 现在,我尝试添加一个脚本,该脚本将搜索ttest行,并将0.05以下的所有值显示为红色。在stackoverflow上我找到了一些帮助,但仍然收到一个错误。(对于颜色,我使用这个源:https://pypi.python.org/pypi/xlwt
你能帮帮我吗?
谢谢!在

    from xlwt import *
    style = xlwt.easyxf('font: colour red, bold on')
    wb=xlwt.Workbook()
    wbs=wb.add_sheet("sheet_to_write")
    w=xlrd.open_workbook("file_to_read.xlsx")
    ws=w.sheet_by_name("sheet_to_read")
    c=ws.cell(2,6).value
    wbs.write(46,1,c)
    ... #same as the last two lines, extracting different cells from the sheet_to_red and writing them in the sheet_to_write
    wbs.write(61,1,Formula("TTEST($B3:$B18, $B19:$B57, 2, 2)"))

旧代码:

^{pr2}$

代码2:

    for row in range(61):
      for col in range(wbs.nrows):
        cell=ws.cell(row,col)
            try:
                if float(cell.value) < 0.05:
                  cell.color =='22'
            except ValueError: pass

AttributeError: 'Cell' object has no attribute 'color'

代码3:

    for row in range(61):
      for col in range(wbs.nrows):
        search=wbs.cell(row,col)
            try:
                if float(search.value) < 0.05:
                  wbs.write(row, col, search.value, style)
            except ValueError: pass
    ERROR:
    AttributeError: 'Worksheet' object has no attribute 'cell',

我的结论是:这个方法行不通,因为xlwt没有属性单元,或者nrows,这些属性是xlrd特有的。因此,唯一可行的方法是创建另一个使用xlrd的文件,搜索特定值,然后将其写入新文件。 感谢Pyrce和tmrlvi的帮助!在


Tags: 文件toin脚本forvaluecellrange
1条回答
网友
1楼 · 发布于 2024-06-16 08:29:16

当您只需要赋值时,您尝试将字符串附加到整数。我猜你是想做这样的事:

# Generate a color style for writing back into xlwt
xlwt.add_palette_colour("my_color", 0x22)
style = xlwt.easyxf('font: colour my_color;')

for row in range(61):
    cell = input_sheet.cell(row, col)
    try:
       if float(cell.value) < 0.05:
          output_sheet.write(row, col, cell.value, style)
    except ValueError: pass

同样,正如您所看到的,xlwt中的颜色分配与您预期的略有不同。您可能还需要遍历所有单元格并将它们复制到输出工作表中,或者共享已读取的同一工作表,以使其完全符合您的需要。在

相关问题 更多 >