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

标签 python excel openpyxl

我怎么找回

  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)

注意事项:

  • 我必须使用只读,因为 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/

相关文章:

python - Django 允许具有端口号的主机

python - 多条水平线和垂直线未显示

python - 是否可以监控 Windows 驱动器上的每个文件创建?

python - openpyxl max_row 和 max_column 错误地报告了一个更大的数字

python - 需要通过迭代excel文件来创建许多python对象

python - rpy2 和 R 调试

javascript - 如何在没有按钮的情况下停止javascript中的setinterval函数

python - python包pyExcelerator/xlwt将特殊字符写入excel表格

arrays - 将两个不相邻的列分组为 Excel VBA 脚本的二维数组

python - 在 Python 2 或 Python 3 上导入 Openpyxl