Cannon
Cannon

Reputation: 319

Unhiding and Hiding columns within my workbook

Is their anyway to hide data in an excel workbook if the data is not their? For instance say I use

df = pd.read_excel('Test.xlsx)

The Dataframe that it produces has a table in it which has columns that are already made for January through December Since I only have data so far for January and February I only want those columns to show. The reason for this is because March to December there is no data yet so the columns come up blank. I want to basically hide columns unless their is data in them and when data does become present in those columns I want it to unhide and show the data for that month.

Upvotes: 2

Views: 5556

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169434

Write to Excel file:

df.to_excel('yourfile.xlsx',index=False)

Open using openpyxl:

import openpyxl

wb = openpyxl.load_workbook('yourfile.xlsx')
ws = wb.get_sheet_by_name('YourSheetName')

For each column check if cell in second row has a value and set column as hidden if not:

for col in ws.columns:
  if not col[2].value:
    ws.column_dimensions[col[2].column].hidden = True

Save to Excel file:

wb.save('yourfile_modified.xlsx')

Upvotes: 3

Related Questions