当前位置:   article > 正文

python 快速操作excel_python操作excel

python操作excel
pip install openpyxl
  1. if __name__ == '__main__':
  2. work_book = openpyxl.Workbook()
  3. sheet = work_book.create_sheet('username_password')
  4. sheet.append(['id', 'loginName', 'userName', 'password'])
  5. users = list()
  6. for index, user in enumerate(users):
  7. password = getPassword(user['id'])
  8. data = [user['id'], user['loginName'], user['userName'], password]
  9. sheet.append(data)
  10. work_book.save("教师用户.xlsx")
  1. import openpyxl
  2. from openpyxl.worksheet.worksheet import Worksheet
  3. if __name__ == '__main__':
  4. # 读取excel
  5. workbook = openpyxl.load_workbook(
  6. r"E:\weixin\WeChat Files\wxid_lkkvjah3yew822\FileStorage\File\2022-10\学校清单.xlsx")
  7. # 获取工作簿
  8. sheet: Worksheet = workbook['Sheet1']
  9. # 获取A列
  10. aList = sheet['A']
  11. # 遍历数据
  12. for a in aList:
  13. # 值
  14. value = a.value
  15. # 行索引
  16. row = a.row
  17. # 列索引
  18. column = a.column
  19. # 处理数据
  20. if '初级中学' in value:
  21. # 设置值
  22. sheet.cell(row, column + 1).value = '初中'
  23. elif '小学' in value:
  24. # 设置值
  25. sheet.cell(row, column + 1).value = '小学'
  26. elif '幼儿园' in value:
  27. # 设置值
  28. sheet.cell(row, column + 1).value = '幼儿园'
  29. elif '幼教点' in value:
  30. # 设置值
  31. sheet.cell(row, column + 1).value = '幼儿园'
  32. elif '教学点' in value:
  33. # 设置值
  34. sheet.cell(row, column + 1).value = '幼儿园'
  35. workbook.save("学校清单-.xlsx")

设置单元格格式:

  1. # 设置标题格式
  2. for t in sheet[1]:
  3. t.style = "Title"
  4. # 设置C列格式
  5. for i, c in enumerate(sheet['C']):
  6. # 标题跳过
  7. if i == 0:
  8. continue
  9. # 格式
  10. c.number_format = 'yyyy-mm-dd hh:mm:ss'
  11. # 字体
  12. c.font = Font(name="Arial", size=14, color="00000000")
  13. # 对齐
  14. c.alignment = Alignment(horizontal='center', vertical='center')
  15. # 边框
  16. c.border = Border(top=Side(border_style="thin", color='00000000'),
  17. left=Side(border_style="thin", color='00000000'),
  18. right=Side(border_style="thin", color='00000000'),
  19. bottom=Side(border_style="thin", color='00000000'))
  20. # 背景色
  21. c.fill = PatternFill(start_color='FFFFFFFF', end_color='FFFFFFFF', fill_type="solid")

设置列宽和行高

  1. sheet.column_dimensions['K'].width = 35
  2. sheet.row_dimensions[1].height = 40

合并单元:需要先合并,后填写
 

  1. ws.merge_cells(range_string='A1:B3')
  2. ws.merge_cells(start_row=5, start_column=4, end_row=8, end_column=8)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/936290
推荐阅读
相关标签
  

闽ICP备14008679号