python - 使用 openpyxl 选择多列
问题描述
我是 python 新手,正在尝试使用 openpyxl 读取 excel 文件。
我的 Excel 文件有 20 列,我只需要提取 5 列。
我的 Excel 文件
CustNumber CustName Serial Number CreateDate ModifiedDate Organization CustAddress Phone
1 XYZ 1010 01-01-2021 01-10-2021 test1 101 parklane 234
2 ABC 1012 01-01-2021 01-10-2021 test2 102 texchlane 234
3 CDF 1010 01-01-2021 01-10-2021 test1 101 parklane 234
4 ASC 1012 01-01-2021 01-10-2021 test2 102 texchlane 234
输出
CustNumber CustName CreateDate ModifiedDate Organization CustAddress
1 XYZ 01-01-2021 01-10-2021 test1 101 parklane
3 CDF 01-01-2021 01-10-2021 test1 101 parklane
我需要从 excel 文件中选择一些列,并过滤 excel 文件中 Organization = test1 的记录。
我想在 openpyxl 中而不是在 pandas 中执行此操作。我能够读取一列,但不确定如何读取多列然后过滤文件以仅提取 test1 记录。
我的代码
import openpyxl
book = openpyxl.load_workbook('Book1.xlsx')
sheet = book['SSH_CERT']
column_name = 'Description'
for column_cell in sheet.iter_cols(1, sheet.max_column):
if column_cell[0].value == column_name:
j = 0
for data in column_cell[1:]:
print(data.value)
break
谢谢
解决方案
这将是带有 pandas 的 1 行代码,但由于您需要 openpyxl 解决方案,所以它是:
import openpyxl
book = openpyxl.load_workbook('Book1.xlsx')
sheet = book['SSH_CERT']
# enter column names you want to be removed
column_names = ['CreatedDate']
for cell in sheet[1]:
if cell.value in column_names:
sheet.delete_cols(cell.column, 1)
book.save(filename='book1_res.xlsx')
这将搜索所有列并删除存储在column_names
推荐阅读
- html - 定义列的垂直堆叠顺序
- java - 引用 Listview Null 适配器
- html - 在 inline div 中将材质卡宽度作为父级
- python - Python matplotlib / 用线连接图
- express - 如何在 Pug 中创建选项卡
- vhdl - 在 VHDL 中的 when select 语句中添加清除/重置输入
- android - Android 添加指纹支持排除了 Play 商店中的某些设备
- android - 我可以禁用 android 上的通知徽章和小通知图标吗?
- http - 在 GO 中重新组合大块的 zip 下载
- python - 通过硒从网络抓取中将列表存储到CSV文件中?