简体   繁体   English

如何根据 python 中的字典更新 excel 列值

[英]How to update excel column values based on dictionary in python

I have an excel spreadsheet that looks like:我有一个 excel 电子表格,如下所示:

expense.xlsx费用.xlsx

|Amount|CategoryId|Date|
|:----|:------:|-----:|
| 123 | 1 | 2020-07-07|
| 321| 2 | 2020-07-07|

I have a dictionary for the categories:我有一本分类字典:

catDict = {1:'a', 2:'b'}

How would I go about changing the excel column "CategoryId" to match the dictionary values:我将如何 go 关于更改 excel 列“CategoryId”以匹配字典值:

Amount数量 CategoryId类别 ID Date日期
123 123 a一个 2020-07-07 2020-07-07
321 321 b b 2020-07-07 2020-07-07

Using openpyxl you can try with the following:使用 openpyxl 您可以尝试以下操作:

import openpyxl as opxl
wb = opxl.load_workbook('expense.xlsx')
ws = wb.active
for i in range(1,ws.max_row+1):
    ws['B'+str(i)] = str(ws['B'+str(i)].value).replace('1','a').replace('2','b')
wb.save('expense.xlsx')

If you have a lot more values to replace, then I suggest also checking this question to improve on that part of the code.如果您有更多值要替换,那么我建议您也检查这个问题以改进该部分代码。

Old answer: Can you use pandas?旧答案:您可以使用 pandas 吗? If so, you can use .replace() :如果是这样,您可以使用.replace()

df = pd.read_csv('expense.xlsx') #Read excel
catDict = {1:'a',2:'b'}

df['CategoryId'] = df['CategoryId'].replace(catDict)
#Alternatively one can use `.map()`

df.to_excel('expense.xlsx') #Save back to excel

Using openpyxl, hope this helps!使用 openpyxl,希望这会有所帮助!

import openpyxl

workbook = openpyxl.Workbook()
sheet = workbook.active
dict = {1:'a', 2:'b'}

sheet.cell(row=1, column=1, value='Amount')
sheet.cell(row=1, column=2, value='CategoryId')
sheet.cell(row=1, column=3, value='Date')
row, column = 2,1
for key, values in dict.items():
    sheet.cell(row=row, column=column, value=key)
    sheet.cell(row=row, column=column+1, value=values)
    sheet.cell(row=row, column=column+2, value='2020-07-07')
    row += 1
file_name = 'sample.xlsx'
workbook.save(filename=file_name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM