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



如何检索

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

示例 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)

笔记:

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

这将打印第 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')

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

查理克拉克斯的答案压缩成一行列表理解

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中的不同函数和模式使用数字或字母,因此引用两者是非常宝贵的

最新更新