【问题标题】:How to iterate over a particular column in excel using pyxl(python)如何使用pyxl(python)遍历excel中的特定列
【发布时间】:2018-10-18 09:52:04
【问题描述】:

我是 python 新手,需要你的帮助。我正在尝试使用 pyxl 编写遍历 excel 中特定列的代码

from io import StringIO
import pandas as pd
import pyodbc 
from openpyxl import load_workbook


d=pd.read_excel('workbook.xlsx',header=None)
wb = load_workbook('workbook.xlsx')

所以在上面的示例中,我必须转到 J 列并显示该列中的所有值。

请帮我解决这个问题。

另外,我的 excel 表中重复了相同的列名。例如,“示例”列名在 B2 和 J2 中都可用。但我想获取 J2 的所有列信息。

请告诉我如何解决这个问题...

谢谢..请回复

【问题讨论】:

  • 请提供您的数据示例,几行供我们查看。
  • 表 1 列名 表 2 列名 x_Table 1 名称 A_Table 2 名称 y_Table 1 id B_Table 2 id Hi yolo..请查找示例

标签: python excel python-2.7 pandas dataframe


【解决方案1】:

既然你是 python 新手,你应该learn to read the documentation。有大量可用的模块,如果您先努力,它对您来说会更快,对我们其他人来说会更容易。

import openpyxl
from openpyxl.utils import cell as cellutils

## My example book simply has "=Address(Row(),Column())" in A1:J20

## Because my example uses formulae, I am loading my workbook with
## "data_only = True" in order to get the values; if your cells do not
## contain formulae, you can omit data_only
workbook = openpyxl.load_workbook("workbook.xlsx", data_only = True)
worksheet = workbook.active
## Alterntively: worksheet = workbook["sheetname"]


## A container for gathering the cell values
output = []

## Current Row = 2 assumes that Cell 1 (in this case, J1) contains your column header
## Adjust as necessary
column = cellutils.column_index_from_string("J")
currentrow = 2

## Get the first cell
cell = worksheet.cell(column = column, row = currentrow)

## The purpose of "While cell.value" is that I'm assuming the column
## is complete when the cell does not contain a value

## If you know the exact range you need, you can either use a for-loop,
## or look at openpyxl.utils.cell.rows_from_range
while cell.value:
    ## Add Cell value to our list of values for this column
    output.append(cell.value)

    ##  Move to the next row
    currentrow += 1

    ## Get that cell
    cell = worksheet.cell(column = column, row = currentrow)


print(output)
""" output: ['$J$2', '$J$3', '$J$4', '$J$5', '$J$6', '$J$7',
            '$J$8', '$J$9', '$J$10', '$J$11', '$J$12', '$J$13', '$J$14',
            '$J$15', '$J$16', '$J$17', '$J$18', '$J$19', '$J$20']

【讨论】:

  • 你太棒了..非常感谢..我可以从中学到一些东西
  • 嗨 Reid..还有一个问题..在我正在做的 excel 文件中有一些被删除的字段..如何在某些字段中省略被删除的文本
  • 我很高兴这有帮助,但是 - 再次 - 请 check the docs so you don't have to wait for an answer。根据该页面,您可以使用cell.font 检查字体样式,并通过cell.font.strike. 使用删除线并记住将答案标记为已接受(复选标记),以便需要它的人可以找到它,而其他正在回答问题的人不要不需要检查。
猜你喜欢
  • 2019-03-28
  • 2021-02-25
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2015-12-31
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多