簡體   English   中英

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

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

我有一個 excel 電子表格,如下所示:

費用.xlsx

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

我有一本分類字典:

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

我將如何 go 關於更改 excel 列“CategoryId”以匹配字典值:

數量 類別 ID 日期
123 一個 2020-07-07
321 b 2020-07-07

使用 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')

如果您有更多值要替換,那么我建議您也檢查這個問題以改進該部分代碼。

舊答案:您可以使用 pandas 嗎? 如果是這樣,您可以使用.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

使用 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