python - 使用 openpyxl 的数据修改 API
问题描述
假设我们有这个 Excel 表:
以下代码用于遍历所有行,并获取某些列的特定值,但它绝对不是很“pythonic”:
from openpyxl import load_workbook
wb = load_workbook('test.xlsx')
ws = wb.active
header = {col[0].value: i+1 for i, col in enumerate(ws.iter_cols())} # mapping between column
# names (from header row)
# and their index
for i in range(2, ws.max_row+1): # it would be interesting to not have to think about 2, max_row+1, etc.
print(ws.cell(row=i, column=header['abc']).value)
print(ws.cell(row=i, column=header['def']).value)
# for example, print(ws[i, 'abc']) would be nicer (pandas-style)
问题:执行此操作的openpyxl
内置方法是什么?
注意:我不想使用pandas
它,因为我需要修改现有的 Excel 文件并保持布局/格式;另请参阅使用 Pandas 修改 Excel 文件,对布局进行最小的更改。
第二个例子:假设我们想在column128
中为columnabc
中的行523
def
设置一个值。我能找到的最好的是:
def find_row(ws, column, query):
for i in range(2, ws.max_row+1):
if ws.cell(row=i, column=column).value == query:
return i
return None
ws.cell(row=find_row(ws, header['def'], 523), column=header['abc'], value=128)
这可能不是最优的。
TL;DR:如何使用内置openpyxl
API 执行此“查找行 + 替换值”?
解决方案
推荐阅读
- java - 如何检查 c3p0 的连接池是否在我的项目中工作?
- node.js - 为 vue-cli 运行“npm run dev”时如何解决跨环境问题
- android - Android 6 上未显示生物识别提示
- mysql - 如何仅在字段计数等于 1 的情况下从 sql 联接中回填数据,同时维护先前联接的记录?
- kotlin - 将 print() 输出重定向到字符串而不是标准输出
- python - 有没有办法从数据框中的一列中获取值并将它们附加到熊猫 python 中不同的数据框列
- javascript - parcel 可以编译成 ES5,包括所有依赖项吗?
- ssh - 如何通过 ssh 进入在 OpenShift/Kubernetes 集群中运行的容器?
- hyperledger-fabric - Hyperledger Fabric 中的中间 CA 的用途是什么
- sql-server - Labview - SSMS 数据库通信... 如何在不同设备上的 Labview 和 Microsoft SQL Server 之间进行通信?