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

Get column names of Excel worksheet with OpenPyXL in readonly mode

如何检索

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

示例 Excel 工作表:

| City       | Population  |    Country   |
| -----------|------------ | ------------ |
| Madison    |   252,551   |     USA      |
| Bengaluru  | 10,178,000  |    India     |
| ...        |       ...   |     ...      |

示例代码:

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)

备注:

只读模式提供对工作表中任何行或行集的快速访问。使用方法 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

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

list_with_values=[]
for cell in ws[1]:
    list_with_values.append(cell.value)

如果出于某种原因您想获得已填写的列字母列表,您可以:

column_list = [cell.column for cell in ws[1]]

对于你的第二个问题; 假设您已将 header 值存储在名为的列表中:"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')

Charlie Clarks 的回答通过列表理解压缩为一行

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

我就是这样处理的

from openpyxl.utils import get_column_letter

def get_columns_from_worksheet(ws):
  return {
      cell.value: {
          'letter': get_column_letter(cell.column),
          'number': cell.column - 1
      } for cell in ws[1] if cell.value
  }

一个这样使用的例子是

from openpyxl import load_workbook

wb = load_workbook(filename='my_file.xlsx')
ws = wb['MySheet']

COLUMNS = get_columns_from_worksheet(ws)

for cell in ws[COLUMNS['MY Named Column']['letter']]:
    print(cell.value)

捕获字母和数字代码的主要原因是因为 openpyxl 中的不同函数和模式使用数字或字母,因此参考两者是非常宝贵的