Guest User

Untitled

a guest
Jun 22nd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. from openpyxl import load_workbook
  2.  
  3. wb = load_workbook('c:/temp/a.xlsx')
  4. sh = wb['Sheet1']
  5.  
  6.  
  7. print('background colors for ALL cells:n')
  8. for row in sh.iter_rows():
  9. for cell in row:
  10. print(f'[{cell.coordinate}]: {cell.fill.fgColor.value}', end=' ')
  11. print()
  12.  
  13. def find_cells_by_color(sh, color='00000000'):
  14. ret = {}
  15. for row in sh.iter_rows():
  16. for cell in row:
  17. if cell.fill.fgColor.value == color:
  18. ret[cell.coordinate] = cell.value
  19.  
  20. return ret
  21.  
  22. res = find_cells_by_color(sh, color='FFFFFF00')
  23. print(f'given color has been found in the following cells: {res}')
  24.  
  25. background colors for ALL cells:
  26.  
  27. [A1]: 00000000 [B1]: 00000000 [C1]: 00000000
  28. [A2]: FFFFFF00 [B2]: 00000000 [C2]: FFFF0000
  29. [A3]: 00000000 [B3]: FFFFFF00 [C3]: FFFFFF00
  30. [A4]: 00000000 [B4]: 00000000 [C4]: FF00B050
  31.  
  32. given color has been found in the following cells: {'A2': 1, 'B3': 5, 'C3': 6}
  33.  
  34. import xlrd
  35. book = xlrd.open_workbook("sample.xls", formatting_info=True)
  36. sheets = book.sheet_names()
  37. for index, sh in enumerate(sheets):
  38. sheet = book.sheet_by_index(index)
  39. rows, cols = sheet.nrows, sheet.ncols
  40. for row in range(rows):
  41. for col in range(cols):
  42. xfx = sheet.cell_xf_index(row, col)
  43. xf = book.xf_list[xfx]
  44. bgx = xf.background.pattern_colour_index #Цвет фона
  45. rgb = book.colour_map[bgx] #Цвет в RGB формате
  46. thecell = sheet.cell(row, col)
  47. print thecell.value #Значение данной ячейки
  48.  
  49. # -*- coding: utf-8 -*-
  50. import win32com.client
  51. Excel = win32com.client.Dispatch("Excel.Application")
  52. wb = Excel.Workbooks.Open(u'D:\xl.xlsx')
  53. sheet = wb.ActiveSheet
  54.  
  55. var = 0
  56. for row in range(1, 5):
  57. for column in range(1, 5):
  58. # Поиск по индексу цвета ColorIndex. Если по цвету, то Color
  59. if sheet.Cells(row, column).Interior.ColorIndex == 6:
  60. var += sheet.Cells(i, j).Value
  61. print(var)
  62.  
  63. wb.Save()
  64. wb.Close()
  65. Excel.Quit()
Add Comment
Please, Sign In to add comment