首页 > 解决方案 > 在只读模式下使用 OpenPyXL 获取 Excel 工作表的列名

问题描述

我怎么能找回

  1. openpyxl只读 工作表中的列名(第一行中单元格的值)?
    • City, Population,Country在下面的示例工作表中
  2. openpyxl 只读工作簿中的所有列名?
    • City, Population, Country, 工作表 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)

笔记:

标签: pythonexcelopenpyxl

解决方案


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

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

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

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

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

推荐阅读