Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column names of Excel worksheet with OpenPyXL in readonly mode

How could I retrieve

  1. the column names (values of the cells in the first row) in an openpyxl Read-only worksheet?
    • City, Population, Country in the below example worksheet
  2. all column names in an openpyxl Read-only workbook?
    • City, Population, Country, frames from worksheet 1 and the other column names from all other worksheets

Example Excel worksheet:

| City       | Population  |    Country   |
| -----------|------------ | ------------ |
| Madison    |   252,551   |     USA      |
| Bengaluru  | 10,178,000  |    India     |
| ...        |       ...   |     ...      |

Example code:

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)

Notes:

  • I have to use readonly because the Excel file has over 1 million rows (don't ask)
  • I'd like the column names so I can eventually infer the column types and import the excel data into a PostgreSQL database
like image 427
Ty Hitzeman Avatar asked Aug 22 '18 22:08

Ty Hitzeman


1 Answers

This will print every thing from row 1;

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

If for some reason you want to get a list of the column letters that are filled in you can just:

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

For your 2nd question; Assuming you have stored the header values in a list called : "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')
like image 70
HaR Avatar answered Sep 24 '22 02:09

HaR