首页 > 解决方案 > 使用 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
     
     

谢谢

标签: pythonopenpyxl

解决方案


这将是带有 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


推荐阅读