在excel中用字符串替换字符串

时间:2017-01-13 10:00:02

标签: python python-3.x

我想将文本文件中的字符串与Excel工作表中的第一个列进行比较 如果文件中的字符串与第一列中的任何值匹配,我想用第二列中的值替换此字符串并将更改保存到文本文件

import numpy as np
wb = openpyxl.load_workbook('D:\\example.xlsx')

ws = wb.active

v = "D:\\A2.txt"
v = open(v).read()
row = 1
cell_addr = "A" + str(row)
next_cell = "B" + str(row)
while ws[cell_addr].value is not None:

    # print(cell_addr, ws[cell_addr].value, type(ws[cell_addr].value))
    j=1
    for i in v:
        if i == ws[cell_addr].value:
            v.replace(i, ws[next_cell].value)
        else:
              print (i)
    with open('D:\\A2.txt', 'w') as f:
        f.write(i)          

    row += 1
    cell_addr = "A" + str(row)
    next_cell = "B" + str(row)

1 个答案:

答案 0 :(得分:0)

这样的东西?

import openpyxl

xlsfile = 'example.xlsx'
txtfile = 'A2.txt'

with open(txtfile, 'r') as f:
    v = f.read().split('\n')

new_v = list(v)
wb = openpyxl.load_workbook(xlsfile)
ws = wb.active
for cells in ws.rows:
    val = cells[0].value
    if val in v:
        index = v.index(val)
        new_v[index] = cells[1].value

with open(txtfile, 'w') as f:
    f.write('\n'.join(new_v))