小言_互联网的博客

python使用xlwings操作表格

522人阅读  评论(0)

  
  1. # -*- coding: UTF-8 -*-
  2. ##库安装的教程:包含mac和windows
  3. #https://zhuanlan.zhihu.com/p/107086691
  4. import xlwings as xw
  5. #创建excel实例,打开Excel
  6. app = xw.App(visible = True,add_book = False)
  7. #打开工作簿
  8. target = app.books.open( r"/Users/jeremiahyuan/Desktop/11.xls")
  9. source = app.books.open( r"/Users/jeremiahyuan/Desktop/22220191129.xls")
  10. #在工作簿中打开工作表
  11. sht_data = source.sheets[ "sheetname"]
  12. ID_xz = "aaa"
  13. ID_gx = "bbb"
  14. #配合for循环用下标读取工作表设置的变量
  15. n = 1
  16. #循环范围需手动修改
  17. for i in range( 4, 160):
  18. #获取原数据中身份证号,与户主关系,电话,姓名
  19. sfz = sht_data.range( "I"+str(i)).value
  20. gx = sht_data.range( "K"+str(i)).value
  21. tel = sht_data.range( "AA"+str(i)).value
  22. name = sht_data.range( "H"+str(i)).value
  23. print(sfz, gx, tel, name)
  24. if ((sht_data.range( "E"+str(i)).value == ID_xz) and (sht_data.range( "K"+str(i)).value == ID_gx)):
  25. #根据下标获取工作表
  26. sht = target.sheets[ "Sheet" + str(n)]
  27. #下面的数据是只在为户主的时候填写的
  28. print (str(i) + ":enter if")
  29. sht.range( "C3").value = "xxxxx"+ID_xz
  30. #修改工作表名称
  31. sht.name = name
  32. #获取数据复制到新的表的对应位置
  33. sht.range( "C4").value = name
  34. sht.range( "B9").value = name
  35. sht.range( "A9").value = gx
  36. #身份证号码前加"'"可以完美复制
  37. sht.range( "C9").value = "'"+sfz
  38. sht.range( "F4").value = tel
  39. #n递增进入下一户人家
  40. n+= 1
  41. #m重新赋值1
  42. m = 1
  43. else:
  44. print ( "enter else")
  45. #获取数据复制到新的表的对应位置
  46. sht.range( "B"+str(m+ 9)).value = name
  47. sht.range( "A"+str(m+ 9)).value = gx
  48. sht.range( "C"+str(m+ 9)).value = "'"+sfz
  49. m+= 1
  50. target.save()
  51. target.close()
  52. source.close()
  53. app.quit()

 


转载:https://blog.csdn.net/weixin_39540568/article/details/104525863
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场