读sheet

  1. from openpyxl import load_workbook
  2. wb = load_workbook("files/p1.xlsx")
  3. # sheet相关操作
  4. # 1.获取excel文件中的所有sheet名称
  5. """
  6. print(wb.sheetnames) # ['数据导出', '用户列表', 'Sheet1', 'Sheet2']
  7. """
  8. # 2.选择sheet,基于sheet名称
  9. """
  10. sheet = wb["数据导出"]
  11. cell = sheet.cell(1, 2)
  12. print(cell.value)
  13. """
  14. # 3.选择sheet,基于索引位置
  15. """
  16. sheet = wb.worksheets[0]
  17. cell = sheet.cell(1,2)
  18. print(cell.value)
  19. """
  20. # 4.循环所有的sheet
  21. """
  22. for name in wb.sheetnames:
  23. sheet = wb[name]
  24. cell = sheet.cell(1, 1)
  25. print(cell.value)
  26. """
  27. """
  28. for sheet in wb.worksheets:
  29. cell = sheet.cell(1, 1)
  30. print(cell.value)
  31. """
  32. """
  33. for sheet in wb:
  34. cell = sheet.cell(1, 1)
  35. print(cell.value)
  36. """

读sheet中单元格的数据

  1. from openpyxl import load_workbook
  2. wb = load_workbook("files/p1.xlsx")
  3. sheet = wb.worksheets[0]
  4. # 1.获取第N行第N列的单元格(位置是从1开始)
  5. """
  6. cell = sheet.cell(1, 1)
  7. print(cell.value)
  8. print(cell.style)
  9. print(cell.font)
  10. print(cell.alignment)
  11. """
  12. # 2.获取某个单元格
  13. """
  14. c1 = sheet["A2"]
  15. print(c1.value)
  16. c2 = sheet['D4']
  17. print(c2.value)
  18. """
  19. # 3.第N行所有的单元格
  20. """
  21. for cell in sheet[1]:
  22. print(cell.value)
  23. """
  24. # 4.所有行的数据(获取某一列数据)
  25. """
  26. for row in sheet.rows:
  27. print(row[0].value, row[1].value)
  28. """
  29. # 5.获取所有列的数据
  30. """
  31. for col in sheet.columns:
  32. print(col[1].value)
  33. """

读合并的单元格

  1. from openpyxl import load_workbook
  2. wb = load_workbook("files/p1.xlsx")
  3. sheet = wb.worksheets[2]
  4. # 获取第N行第N列的单元格(位置是从1开始)
  5. c1 = sheet.cell(1, 1)
  6. print(c1) # <Cell 'Sheet1'.A1>
  7. print(c1.value) # 用户信息
  8. c2 = sheet.cell(1, 2)
  9. print(c2) # <MergedCell 'Sheet1'.B1>
  10. print(c2.value) # None
  1. from openpyxl import load_workbook
  2. wb = load_workbook('files/p1.xlsx')
  3. sheet = wb.worksheets[2]
  4. for row in sheet.rows:
  5. print(row)
  1. >>> 输出结果
  2. (<Cell 'Sheet1'.A1>, <MergedCell 'Sheet1'.B1>, <Cell 'Sheet1'.C1>)
  3. (<Cell 'Sheet1'.A2>, <Cell 'Sheet1'.B2>, <Cell 'Sheet1'.C2>)
  4. (<Cell 'Sheet1'.A3>, <Cell 'Sheet1'.B3>, <Cell 'Sheet1'.C3>)
  5. (<MergedCell 'Sheet1'.A4>, <Cell 'Sheet1'.B4>, <Cell 'Sheet1'.C4>)
  6. (<Cell 'Sheet1'.A5>, <Cell 'Sheet1'.B5>, <Cell 'Sheet1'.C5>)