python多条件筛选 xlrd xlwt_pythonxlrd/xlwt:比较2.xls文件和多个迭代中的值聚合

任务:

我有两个电子表格(A和B),有关代码中的引用,请参见#。在

首先,我从A中的第一行开始。

我在第7列(#1#)中得到了一个特定的值V。我还看了第15列,它决定了下一步(#2#)我想在电子表格的哪一行添加B。在

其次,我切换到B,并查找我在上一步使用电子表格A(#3)定义的正确行。然后我将V添加到第5列的这一行(#4#)。之后,我从A第二行的下一个迭代开始,依此类推(#m=m+1#)。在

我对电子表格中的每一行都这样做。这意味着,A中每一行的值V都被添加到电子表格B的某个单元格中,但并非B中的每一行都必须在其第5列中具有来自A的值。在

解决方案/问题:

我用python3.x使用xlrd/xlwt解决了这个问题。但是,我面临一个问题,我的脚本只适用于一次迭代(即a中的一行)。如果我自动运行脚本多次迭代(Python自动为A中的每一行执行脚本),则先前的值将被较新的值覆盖,从而导致未完成的电子表格B。在

但是,如果我手动运行它(通过手动更改A的行),它可以工作。我认为这是因为,脚本是手动执行的,并且以某种方式保存了值,这样它们就不会被覆盖。因为对于我的案例来说,这不是一个选项(在A…)中超过1k行,我正在寻找一个自动化的解决方案。在

有没有办法克服这个问题?在import xlwt

import xlrd

from xlutils.copy import copy

grid_file = 'grid_aut_100km.xls' #spreadsheet B#

wind_file = 'wind_aut_sample.xls' #spreadsheet A#

gridbook = xlrd.open_workbook(grid_file)

gridsheet = gridbook.sheet_by_index(0)

windbook_rd = xlrd.open_workbook(wind_file)

windsheet_rd = windbook_rd.sheet_by_index(0)

gridbook_wt = copy(gridbook)

gridsheet_wt=gridbook_wt.get_sheet(0)

m=1

def setup():

gridsheet_wt.write(0,5,"sum_capacity")

gridbook_wt.save(grid_file)

def setsumszero():

n=1

sum_capacity = int(0)

while n <= gridsheet.nrows-1:

gridsheet_wt.write(n,5,sum_capacity)

n=n+1

gridbook_wt.save(grid_file)

def gridmatch(m,n):

id_in_windsheet = windsheet_rd.cell_value(m,15) #2#

n=1

id_in_gridsheet = gridsheet.cell_value(n,0)

while True:

if id_in_windsheet == id_in_gridsheet: #3#

print(str(id_in_windsheet) + " = " + str(id_in_gridsheet))

print("It's a Match in row " + str(n))

break

else:

n=n+1

id_in_gridsheet = gridsheet.cell_value(n,0)

sum_capacity_old = gridsheet.cell_value(n,5)

print("Old capacity is " + str(sum_capacity_old))

additional_capacity = windsheet_rd.cell_value(m,7) #1#

print("Additional capacity is " + str(additional_capacity))

sum_capacity_new = sum_capacity_old + additional_capacity #4#

print("Sum of new capacity is " + str(sum_capacity_new))

gridsheet_wt.write(n,5,sum_capacity_new)

print("New capacity is " + str(sum_capacity_new))

gridbook_wt.save(grid_file)

print("")

print("")

setup()

setsumszero()

m=1 #row in windbook

n=1 #row in gridbook

while m <= windsheet_rd.nrows-1:

gridmatch(m,n)

gridbook_wt.save(grid_file)

m=m+1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值