user14380579
user14380579

Reputation:

Hide columns when using to_excel

I have two DataFrames, each with multiple columns.

I am saving these to Excel in different sheets.

For the dir_tree_df dataframe, I would like the first 3 sheets hidden. For the table_of_contents_df dataframe, I would like the first column hidden.

Is this possible? I've seen a possible solution here, but unsure how to implement it in my code

Is it possible to create an excel file with hidden columns in Python using pandas?

My Code

 with pd.ExcelWriter(target_directory + 'output_test.xlsx') as writer:  
        table_of_contents_df.to_excel(writer, sheet_name='Contents', index = False)
        dir_tree_df.to_excel(writer, sheet_name='Data', index = False)

Upvotes: 3

Views: 3001

Answers (1)

user14380579
user14380579

Reputation:

Think I solved it. The docs helped:
https://xlsxwriter.readthedocs.io/working_with_pandas.html https://xlsxwriter.readthedocs.io/worksheet.html#worksheet

with pd.ExcelWriter(target_directory + 'output_test.xlsx', engine = 'xlsxwriter') as writer:  
            table_of_contents_df.to_excel(writer, sheet_name='Contents', index = False)
            dir_tree_df.to_excel(writer, sheet_name='Data', index = False)
    
            worksheet = writer.sheets['Contents']
            worksheet.set_column('A:A', None, None, {'hidden': 1})
    
            worksheet = writer.sheets['Data']
            worksheet.set_column('A:C', None, None, {'hidden': 1})
            

Upvotes: 6

Related Questions