Openpyxl:在行中查找字符串,然后将数据添加到同一行的第 45、46、47 列

Openpyxl: Find string in Row then add data to column 45, 46, 47 of the same row

我的列是固定的,不应该移动。行不断变化。我需要找到一个字符串 'Bond Fund' 并且找到的每一行都需要将数据添加到第 45、46、47 列。

我尝试了以下代码,但没有提供语法错误,但是在打开 excel sheet 时,没有值添加到记录的列中。

import openpyxl
from openpyxl.utils.cell import get_column_letter
from datetime import datetime

fname = input("Name of workbook:")
wb = openpyxl.load_workbook('Import ' + fname + '.xlsx', data_only=True)
ws1 = wb.worksheets\['Import'\]

for row in ws1.iter_rows():
    for cell in row:
        if cell.value == "Bond Fund":
            ws1.cell(row=cell.Row, column=45).value = 'SubClass'
            ws1.cell(row=cell.Row, column=46).value = 'Bond Fund'
            ws1.cell(row=cell.Row, column=47).value = 'Research'

我希望代码能像查找和替换一样工作,我已成功使用它,例如

for col in ws1.iter_cols(min_col=1, min_row=1, max_col=100):
    for cell in col:
        if cell.value == 'Bond':
            cell.value = 'Bond Fund'

解决我上面的问题:

intermuni= 'Muni California Intermediate'
for _idx, _ival in enumerate(ws1.values, start=1):
        if str(intermuni) in str(_ival):
            ws1.cell(row=_idx, column=45).value = 'SubClass'
            ws1.cell(row=_idx, column=46).value = 'Muni Single State Interm'
            ws1.cell(row=_idx, column=47).value = 'Priority Buy'
            ws1.cell(row=_idx, column=48).value = 'Can Sell'
            ws1.cell(row=_idx, column=49).value = 'SubClass'
            ws1.cell(row=_idx, column=50).value = 'Muni National Interm'
            ws1.cell(row=_idx, column=51).value = 'Priority Buy'
            ws1.cell(row=_idx, column=52).value = 'Can Sell'

新问题: #我想在上面的if语句中使用字典来避免出现多个if elif语句。这可能吗?

#首先想到我创建了字典。然后在 if str(assetClass) in str(_ival):

中使用 assetClass
assetClass = {'Large Value':'QVAL', 'Large Blend':'VONE','Large Growth':'SPY','Small Blend':'VB','Foreign Large Blend':'EFA','Diversified Emerging Mkts':'EEM','Health':'XHE','US Tech':'QQQ','Intermediate Core Bond':'BND','Inflation-Protected Bond':'AGG','Multisector Bond':'BND','High Yield Bond':'SJNK','Bank Loan':'AGG','Muni California Intermediate':'MUB','Muni California Long':'MUB','Preferred Stock':'JPS', 'Nontraditional Bond':''BND'} 
for _idx, _ival in enumerate(ws1.values, start=1):
        if str(assetClass) in str(_ival):
            ws1.cell(row=_idx, column=32).value = '' #what goes here?
            ws1.cell(row=_idx, column=33).value = 'ALL'
            ws1.cell(row=_idx, column=34).value = '1'

首先这行得通吗?如果是这样,“ws1.cell(row=_idx, column=32).value = '' #what goes here?”的代码是什么?哪个会在第 32 列中保存与键匹配的字典值?

谢谢。

我相信这对您发布的场景有帮助: 请看一下

######
import os
import openpyxl


# Class definitions should use CamelCase convention based on pep-8 guidelines
class CustomOpenpyxl:
    # Initialize the class with filename as only argument
    def __init__(self, _my_file_name):
        assert _my_file_name.split('.')[-1] in ['xls', 'xlsx'], 'Input file does not have valid excel extension'
        self.my_filename = _my_file_name
        self.my_base_wb = openpyxl.load_workbook(self.my_filename, read_only=False)
        # following line will get the names of worksheets in the workbook
        self.ws_names_in_my_base_wb = self.my_base_wb.sheetnames
        # following line will get the number of worksheets in the workbook
        self.num_ws_in_my_base_wb = len(self.my_base_wb.sheetnames)
        # following line will set the last worksheet in the workbook as active
        self.my_base_active_ws = self.my_base_wb.active

    # Method to save the workbook
    # No arguments to this method
    def save_wb(self):
        return self.my_base_wb.save(self.my_filename)

_my_file_name = 'Financial Sample.xlsx'
os.chdir('/Users/devops/Documents')

_stk_oflw_obj = CustomOpenpyxl(_my_file_name)
_my_search_string = 'Small Business'

# Iterate over the values in the active worksheet
for _idx, _ival in enumerate(_stk_oflw_obj.my_base_active_ws.values, start=1):
    # Search the string in the entire row
    # (_ival is tuple values)
    if str(_my_search_string) in str(_ival):
        # If the string is found in the row
        # add 'Whosebug-Subclass' text on 17th column on the matched row index
        _stk_oflw_obj.my_base_active_ws.cell(row=_idx, column=17).value = 'Whosebug-Subclass'
        # add 'Whosebug-Subclass' text on 18th column on the matched row index
        _stk_oflw_obj.my_base_active_ws.cell(row=_idx, column=18).value = 'Whosebug-Subclass'
        # add 'Whosebug-Subclass' text on 19th column on the matched row index
        _stk_oflw_obj.my_base_active_ws.cell(row=_idx, column=19).value = 'Whosebug-Subclass'

# Save the workbook
_stk_oflw_obj.save_wb()
######