Skip to content
Advertisement

How put all rows heights to 20, and all columns width to 30

I want to put all row heights to 20 and all column widths to 30. I tried this code: All is just with pandas dataframe.

worksheet2.set_default_row(20) #it works but in Excel is it 19.80
worksheet2.set_default_column(30) #it doesn't work, 

Error: 'Worksheet' object has no attribute 'set_default_column'

Advertisement

Answer

Creating excel file

import pandas as pd
import numpy as np

# creating and saving excel file
df = pd.DataFrame(
    np.random.randint(0, 10, size=(10, 4)),
    columns=['column name 1', 'column name 2',
             'column name 3', 'column name 4']
)
writer = pd.ExcelWriter('test_file.xlsx')
df.to_excel(writer, sheet_name='my_sheet', index=False)
writer.save()

Changing size of columns and rows

import pandas as pd

df = pd.read_excel('test_file.xlsx')
writer = pd.ExcelWriter('test_file.xlsx')
df.to_excel(writer, sheet_name='my_sheet', index=False)

worksheet = writer.sheets['my_sheet']

# change column width of all columns
worksheet.set_column(0, len(df),  30)

# change row height
for row in range(0, len(df.index)+1):
    worksheet.set_row(row, 20)

writer.save()

Before

enter image description here

After

enter image description here

Reference

https://xlsxwriter.readthedocs.io/worksheet.html

You might also want to take a look at this to dynamically change the row height and column width

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement