分享

使用python操作Excel——xlrd、xlwt、xlutils库

 Four兄 2019-09-03

一、使用xlrd进行读操作

打开workbook

  1. import xlrd
  2. wb = xlrd.open_workbook('mywokbook.xls')

检查表单名字

wb.sheet_names()

获取sheet表

  1. sh = wb.sheet_by_index(0) # 索引获取
  2. sh = wb.sheet_by_name('Sheet01') # 名字获取

递归打印所有行数据

  1. for n in range(sh.nrows):
  2. print sh.row_values(n)

返回第N列数据

first_column = sh.col_values(N)

通过索引读取某单元格数据

cell_A1 = sh.cell(0, 0).value

二、使用xlwt进行写操作

初始化workbook对象,之后才能进行写入操作

  1. import xlwt
  2. wbk = xlwt.Workbook()
  3. sheet = wbk.add_sheet('sheet2')

写入数据

sheet.write(0, 1, 'new text')

保存文件

wbk.save('new.xls')

注意:修改表单内容,需要使用cell_overwrite_ok=True来创建worksheet

  1. sheet2 = wbk.add_sheet('sheet2', cell_overwrite_ok=True)
  2. sheet2.write(0, 0, 'text')
  3. sheet2.write(0, 0, 'altertext')

三、使用xlutils进行修改操作

Python中一般使用xlrd(excel read)来读取Excel文件,使用xlwt(excel write)来生成Excel文件(可以控制Excel中单元格的格式),需要注意的是,用xlrd读 取excel是不能对其进行操作的:xlrd.open_workbook()方法返回xlrd.Book类型,是只读的,不能对其进行操作。而 xlwt.Workbook()返回的xlwt.Workbook类型的save(filepath)方法可以保存excel文件。因此对于读取和生成Excel文件都非常容易处理,但是对于已经存在的Excel文件进行修改就比较麻烦了。不过,还有一个xlutils(依赖于xlrd和xlwt)提供复制excel文件内容和修改文件的功能。其实际也只是在xlrd.Book和xlwt.Workbook之间建立了一个管道而已,如下图:

xlutils.copy模块的copy()方法实现这个功能

  1. from xlrd import open_workbook
  2. from xlutils.copy import copy
  3. rb = open_workbook('D:\\text.xls')
  4. # 通过get_sheet()获取的sheet才有write()方法
  5. wb = copy(rb)
  6. ws = wb.get_sheet(0)
  7. ws.write(0, 0, 'changed!')
  8. wb.save('D:\\new.xls')

四、实际工作使用

将公司采购单转换成苗木平台生成的Excel模板,采购单总共76条数据,模板14种苗木分类。

采购数据样式:

苗木平台模板数据样式:

生成的Excel表格

偷了个懒,比如时间数据的格式没进行设置,实际代码如下

  1. import re
  2. import xlrd
  3. import xlwt
  4. from xlutils.copy import copy
  5. # 打开sheet表
  6. def open_sheet(xl_name):
  7. xl = xlrd.open_workbook(xl_name)
  8. xl_sheet = xl.sheets()[0]
  9. return xl_sheet
  10. # 将原文件的采购行插入匹配模板的采购行
  11. def insert_mb(L, line_no, ws):
  12. for x in range(len(L)):
  13. one_tree = L[x]
  14. line_no += 1
  15. for i in range(mb_sheet.nrows):
  16. if i == 1:
  17. ws.write(line_no, i, tree_classify(one_tree[2]))
  18. if i == 2:
  19. ws.write(line_no, i, one_tree[2])
  20. if i == 3:
  21. ws.write(line_no, i, one_tree[7])
  22. if i == 4:
  23. ws.write(line_no, i, '43485')
  24. if i == 7:
  25. ws.write(line_no, i, tree_classify(str(one_tree[3])))
  26. if i == 8:
  27. ws.write(line_no, i, one_tree[4])
  28. if i == 9:
  29. ws.write(line_no, i, one_tree[5])
  30. if i == 12:
  31. ws.write(line_no, i, one_tree[-1])
  32. # 处理采购项名称
  33. def tree_classify(tree_name):
  34. s = re.sub('[A-Z]', '', tree_name)
  35. s = s.split('(')[0]
  36. return s
  37. # 查找模板中苗木某种分类的行号
  38. def search_no(sheet, class_no):
  39. for i in range(len(col_data)):
  40. if class_no == 1 and col_data[i] == '一':
  41. line_no = i
  42. elif class_no == 2 and col_data[i] == '二':
  43. line_no = i
  44. elif class_no == 3 and col_data[i] == '三':
  45. line_no = i
  46. elif class_no == 4 and col_data[i] == '四':
  47. line_no = i
  48. elif class_no == 5 and col_data[i] == '五':
  49. line_no = i
  50. elif class_no == 6 and col_data[i] == '六':
  51. line_no = i
  52. return line_no
  53. # 读取所有的采购项并按序号分类
  54. def load_class_no(class_no, sheet):
  55. L = []
  56. for i in range(4, sheet.nrows-6):
  57. one_tree = sheet.row_values(i)[:-8]
  58. if one_tree[0] == class_no:
  59. L.append(one_tree)
  60. return L
  61. # copy模板才可以修改
  62. def copy_alter(sheet):
  63. cp_sheet = copy(sheet)
  64. if __name__ == '__main__':
  65. order_name = '副本径河项目苗木采购审批表.xlsx'
  66. mb_name = 'Copy of importBuyList_ex.xls'
  67. tree_sheet = open_sheet(order_name)
  68. mb_sheet = open_sheet(mb_name)
  69. # 模板中第一列的数据
  70. col_data = mb_sheet.col_values(0)
  71. # copy后模板才可以修改
  72. mb = xlrd.open_workbook(mb_name)
  73. cp_sheet = copy(mb)
  74. wr_sheet = cp_sheet.get_sheet(0)
  75. for no in range(1, 7):
  76. class_trees = load_class_no(no, tree_sheet)
  77. line_no = search_no(wr_sheet, no)
  78. insert_mb(class_trees, line_no, wr_sheet)
  79. cp_sheet.save('new.xls')

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多