我怎么找回
- openpyxl 中的列名称(第一行中单元格的值)Read-only 工作表?
City
、Population
、Country
在下面的示例工作表中
- 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)
注意事项:
- 我必须使用只读,因为 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]]
对于你的第二个问题; 假设您已将 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')
关于python - 在只读模式下使用 OpenPyXL 获取 Excel 工作表的列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51975912/