在只读模式下使用OpenPyXL获取Excel工作表的列名称

Ty *_*man 2 python excel openpyxl

我该如何找回

  1. openpyxl 只读 工作表中的列名(第一行中单元格的值)?
    • CityPopulationCountry在下面的示例表
  2. openpyxl只读工作簿中的所有列名称?
    • CityPopulationCountry,从表1帧和其他列名从所有其他工作表

Excel工作表示例:

| City       | Population  |    Country   |
| -----------|------------ | ------------ |
| Madison    |   252,551   |     USA      |
| Bengaluru  | 10,178,000  |    India     |
| ...        |       ...   |     ...      |
Run Code Online (Sandbox Code Playgroud)

示例代码:

from openpyxl import load_workbook

wb = load_workbook(filename=large_file.xlsx, read_only=True)
sheet = wb.worksheets[0]

... (not sure where to go from here)
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 我必须使用只读,因为Excel文件有超过一百万行(不要问)
  • 我想要列名称,以便最终推断出列类型并将excel数据导入PostgreSQL数据库

Cha*_*ark 6

只读模式提供对工作表中任何行或行集的快速访问。使用方法iter_rows()来限制选择。因此,要获取工作表的第一行:

rows = ws.iter_rows(min_row=1, max_row=1) # returns a generator of rows
first_row = next(rows) # get the first row
headings = [c.value for c in first_row] # extract the values from the cells
Run Code Online (Sandbox Code Playgroud)


HaR*_*HaR 5

这将打印第1行中的所有内容;

list_with_values=[]
for cell in ws[1]:
    list_with_values.append(cell.value)
Run Code Online (Sandbox Code Playgroud)

如果出于某种原因要获取已填写的列字母的列表,则可以:

column_list = [cell.column for cell in ws[1]]
Run Code Online (Sandbox Code Playgroud)

关于第二个问题;假设您已将标头值存储在名为“ list_with_values”的列表中

from openpyxl import Workbook
wb = Workbook()
ws = wb['Sheet']
#Sheet is the default sheet name, you can rename it or create additional ones with wb.create_sheet()
ws.append(list_with_values)
wb.save('OutPut.xlsx')
Run Code Online (Sandbox Code Playgroud)


小智 5

查理·克拉克(Charlie Clarks)的答案通过列表理解压缩为一行

    headers = [c.value for c in next(wb['sheet_name'].iter_rows(min_row=1, max_row=1))]
Run Code Online (Sandbox Code Playgroud)