cfabio

Excel.py

Jan 18th, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.17 KB | None | 0 0
  1.  
  2. #########################
  3. # Excel
  4. #########################
  5.  
  6. #allows copying data from one sheet to an other one
  7. #find and elaborate some rows in a sheet
  8. #xlsx file is a workbook
  9. import openpyxl
  10. import os
  11.  
  12. # read excel sheet
  13. os.chdir(sDirectory)
  14. workbook = openpyxl.load_workbook(sFileName)
  15. type(workbook)
  16.  
  17. sheet = workbook.get_sheet_by_name(sSheetName)
  18. sheetList = workbook.get_sheet_names()
  19.  
  20. cell = sheet['A1']   #get the cell object A1
  21. cell.value           #depending on how the excel is formatted it can return a type
  22. str(cell.value)
  23.  
  24. sheet.cell(row=1, colmn=2)  #alternative to the cell coordinations
  25.  
  26. for i in range(1, 8) :
  27.     print(i, sheet.cell(row=i, column=2).value)  
  28.  
  29.  
  30. # write excel sheet
  31.  
  32. wb = openpyxl.Workbook()   #create a new excel sheet
  33. wb.get_sheet_names() #contains the default Sheet
  34. wb.get_sheet_by_name('Sheet')
  35. sheet['A1'].value == None //True
  36. sheet['A1'] = 42
  37. sheet['A2'] = 'Hello'
  38. wb.save('example.xlsx')   #create on disk the new excel sheet
  39.  
  40. sheet2 = wb.create_sheet() #default to Sheet1
  41. sheet2.title = 'new name'
  42. wb.save(sFileName)
  43.  
  44. wb.create_sheet(index=0, title='my other sheet') #createa at index 0 with proper title
Add Comment
Please, Sign In to add comment