Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import openpyxl
- import pandas as pd
- def write_all_data_to_excel(dataFrame):
- dataFrame.to_excel('studentsData.xlsx', index=False, header=False)
- newFile = "studentsData.xlsx"
- wb = openpyxl.load_workbook(filename=newFile)
- worksheet = wb.active
- for col in worksheet.columns:
- max_length = 0
- column = col[0].column_letter # Get the column name
- for cell in col:
- try: # Necessary to avoid error on empty cells
- if len(str(cell.value)) > max_length:
- max_length = len(str(cell.value))
- except:
- pass
- adjusted_width = (max_length + 2) * 1.2
- worksheet.column_dimensions[column].width = adjusted_width
- wb.save(newFile)
- names = ['john','jane','joe']
- ages = [20,30,40]
- heights = [170,180,190]
- # example of how to use it
- df = pd.DataFrame()
- df['name'] = ['name','age','height']
- # add more data to the dataframe randomly
- df['name'] = [names[0],ages[0],heights[0]]
- df['age'] = [names[1],ages[1],heights[1]]
- df['height'] = [names[2],ages[2],heights[2]]
- write_all_data_to_excel(df)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement