如何使用Python从Excel文件读取一列?

Sir*_* Li 6 python excel

我想在excel的一栏中读取数据,这是我的代码:

import xlrd

file_location = "location/file_name.xlsx"

workbook = xlrd.open_workbook(file_location)

sheet = workbook.sheet_by_name('sheet')

x = []

for cell in sheet.col[9]:

    if isinstance(cell, float):

        x.append(cell)

print(x)
Run Code Online (Sandbox Code Playgroud)

这是错误的,因为工作表中没有名为col [col.num]的方法,但是我只想从第8列(H列)中提取数据,我该怎么办?

Deu*_*rum 9

如果你没有被 xlrd 锁定,我可能会使用 Pandas,这在处理来自任何地方的数据时非常好:

import pandas as pd

df = pd.ExcelFile('location/test.xlsx').parse('Sheet1') #you could add index_col=0 if there's an index
x=[]
x.append(df['name_of_col'])
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用 Pandas 将新提取的列写入新的 excel 文件 df.to_excel()


Roe*_*oni 5

您可以像这样获取第 8 列的值:

for rownum in range(sheet.nrows):
    x.append(sheet.cell(rownum, 7))
Run Code Online (Sandbox Code Playgroud)