Advertisement
kingbode

Untitled

Oct 8th, 2023
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1.  
  2.  
  3. import openpyxl
  4. import pandas as pd
  5.  
  6.  
  7. def write_all_data_to_excel(dataFrame):
  8.     dataFrame.to_excel('studentsData.xlsx', index=False, header=False)
  9.  
  10.     newFile = "studentsData.xlsx"
  11.  
  12.     wb = openpyxl.load_workbook(filename=newFile)
  13.     worksheet = wb.active
  14.  
  15.     for col in worksheet.columns:
  16.         max_length = 0
  17.         column = col[0].column_letter  # Get the column name
  18.         for cell in col:
  19.  
  20.             try:  # Necessary to avoid error on empty cells
  21.                 if len(str(cell.value)) > max_length:
  22.                     max_length = len(str(cell.value))
  23.             except:
  24.                 pass
  25.         adjusted_width = (max_length + 2) * 1.2
  26.         worksheet.column_dimensions[column].width = adjusted_width
  27.  
  28.     wb.save(newFile)
  29.  
  30.  
  31.  
  32. names = ['john','jane','joe']
  33. ages = [20,30,40]
  34. heights = [170,180,190]
  35.  
  36. # example of how to use it
  37. df = pd.DataFrame()
  38. df['name'] = ['name','age','height']
  39.  
  40. # add more data to the dataframe randomly
  41.  
  42. df['name'] = [names[0],ages[0],heights[0]]
  43. df['age'] = [names[1],ages[1],heights[1]]
  44. df['height'] = [names[2],ages[2],heights[2]]
  45.  
  46.  
  47. write_all_data_to_excel(df)
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement