How could I retrieve
City
, Population
, Country
in the below example worksheetCity
, Population
, Country
, frames from worksheet 1 and the other column names from all other worksheetsExample 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:
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With