如何使用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)
这是错误的,因为没有方法在名为col [col.num]的表中,但是我只想提取第8列(H列)中的数据,我该怎么办?
你可以像这样得到第8列的值:
for rownum in range(sheet.nrows): x.append(sheet.cell(rownum, 7))
如果你没有用xlrdlocking,我可能会用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'])
然后你可以用pandas df.to_excel()
把新提取的列写入一个新的excel文件
到目前为止,使用xlrd
获得列中所有值的最简单方法是col_values()
工作表方法:
x = [] for value in sheet.col_values(8): if isinstance(value, float): x.append(value)
(注意,如果你想要列H,你应该使用7,因为索引从0开始)
顺便提一句,你可以使用col()
来获取列中的单元格对象 :
x = [] for cell in sheet.col(8): if isinstance(cell.value, float): x.append(cell.value)
官方教程 (作为xlrd
, xlwt
和xlutils
的体面参考)是find这个东西的最好的地方。 您当然也可以查看文档和源代码。
我会build议做到这一点:
import openpyxl fname = 'file.xlsx' wb = openpyxl.load_workbook(fname) sheet = wb.get_sheet_by_name('sheet-name') for rowOfCellObjects in sheet['C5':'C7']: for cellObj in rowOfCellObjects: print(cellObj.coordinate, cellObj.value)
结果:
C5 70.82
C6 84.82
C7 96.82
注意: fname是指excel文件, get_sheet_by_name('sheet-name')是指所需的工作表,并且在工作表中提到['C5':'C7']范围。
查看链接了解更多详情。 代码段也取自这里。
使用pandas
import pandas as pd filepath = "somepath.xlsx" mycolumns = "A,B,E:F" # choose your columns (comma separated) df = pd.read_excel(filepath , usecols=mycolumns)
更多信息: http : //pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html