我想使用openpyxl打印
python中特定列的所有数据(所有行)我正在以这种方式工作;
from openpyxl import load_workbook workbook = load_workbook('----------/dataset.xlsx') sheet = workbook.active for i in sheet: print(sheet.cell(row=i,column=2).value)
但它给出了
if row < 1 or column < 1:
TypeError: unorderable types: tuple() < int()
因为我在row = i中迭代.如果我使用sheet.cell(row = 4,column = 2).value它会打印cell的值.但是,我如何迭代所有文档?
编辑1
在一些研究中,发现可以使用工作表名称获取数据.工作表1存在于.xlsx文件中,但其数据未打印.这段代码有什么问题吗?
workbook = load_workbook('---------------/dataset.xlsx') print(workbook.get_sheet_names()) worksheet =workbook.get_sheet_by_name('Sheet1') c=2 for i in worksheet: d = worksheet.cell(row=c,column=2) if(d.value is None): return else: print(d.value) c=c+1
解决方法
阅读
OpenPyXL Documentation
迭代工作簿中的所有工作表,例如:
for n,sheet in enumerate(wb.worksheets): print('Sheet Index:[{}],Title:{}'.format(n,sheet.title))
Output:
06001
迭代一个工作表中的所有行和列:
worksheet = workbook.get_sheet_by_name('Sheet') for row_cells in worksheet.iter_rows(): for cell in row_cells: print('%s: cell.value=%s' % (cell,cell.value) )
输出:
<Cell Sheet.A1>: cell.value=²234 <Cell Sheet.B1>: cell.value=12.5 <Cell Sheet.C1>: cell.value=C1 <Cell Sheet.D1>: cell.value=D1 <Cell Sheet.A2>: cell.value=1234 <Cell Sheet.B2>: cell.value=8.2 <Cell Sheet.C2>: cell.value=C2 <Cell Sheet.D2>: cell.value=D2
迭代一行的所有列,例如row == 2:
for row_cells in worksheet.iter_rows(min_row=2,max_row=2): for cell in row_cells: print('%s: cell.value=%s' % (cell,cell.value) )
输出:
<Cell Sheet.A2>: cell.value=1234 <Cell Sheet.B2>: cell.value=8.2 <Cell Sheet.C2>: cell.value=C2 <Cell Sheet.D2>: cell.value=D2
迭代所有行,只有第2列:
for col_cells in worksheet.iter_cols(min_col=2,max_col=2): for cell in col_cells: print('%s: cell.value=%s' % (cell,cell.value))
输出:
<Cell Sheet.B1>: cell.value=12.5 <Cell Sheet.B2>: cell.value=8.2 <Cell Sheet.B3>: cell.value=9.8 <Cell Sheet.B4>: cell.value=10.1 <Cell Sheet.B5>: cell.value=7.7
用Python测试:3.4.2 – openpyxl:2.4.1 – LibreOffice:4.3.3.2