python - 在只读模式下使用 OpenPyXL 获取 Excel 工作表的列名
问题描述
我怎么能找回
- openpyxl只读 工作表中的列名(第一行中单元格的值)?
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]]
对于你的第二个问题;假设您已将标题值存储在名为:“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')
推荐阅读
- javascript - 如何从javascript中的输入文件生成视频缩略图?
- javascript - 使用多个循环检查javascript中的多个条件
- angular - 刷新令牌和访问令牌更改并在更改后重复 401 未经授权的请求 Angular 8
- java - void 方法的 JUnit 测试(输出-输入依赖)
- sql - SQL 修剪非常慢
- batch-file - 检测变量是否包含字符串,然后批量查找该字符串之后的单词
- angular - oidc登录死循环
- python - Python > Selenium + CSV:如何从网站上抓取并将 2 列写入 CSV?
- macos - macOS 核心数据 – toOne 新记录是否在创建时自动分配给 toMany 对象?
- javascript - 如何根据名称(“编号”.js)在文件夹中执行.js文件