Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2224345
  • 博文数量: 287
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 2130
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-31 14:30
个人简介

自己慢慢积累。

文章分类

全部博文(287)

分类: Python/Ruby

2016-05-19 13:48:37

注意: xlrd xlutils 只支持 xls 不支持 xlsx

想要往已经存在的xls文件中,写入新的行,新的数据,对应的逻辑为:

  1. 用xlrd.open_workbook打开已有的xsl文件
    • 注意添加参数formatting_info=True,得以保存之前数据的格式
  2. 然后用,from xlutils.copy import copy;,之后的copy去从打开的xlrd的Book变量中,拷贝出一份,成为新的xlwt的Workbook变量
  3. 然后对于xlwt的Workbook变量,就是正常的:
    1. 通过get_sheet去获得对应的sheet
    2. 拿到sheet变量后,就可以往sheet中,写入新的数据
  4. 写完新数据后,最终save保存

点击(此处)折叠或打开

  1. #coding:utf-8

  2. import xlrd
  3. import xlwt
  4. import requests
  5. import time
  6. from xlutils.copy import copy


  7. data = xlrd.open_workbook("E:/接口测试用例.xls")
  8. sheet = data.sheet_by_name("详细结果")
  9. rows_no = sheet.nrows
  10. print(rows_no)

  11. new_data = copy(data)
  12. new_sheet = new_data.get_sheet(1)
  13. new_sheet.write(1, 1, "test1")
  14. help(new_data.save)
  15. new_data.save("E:/接口测试用例.xls")

原作者代码:

点击(此处)折叠或打开

  1. import xlwt;
  2. import xlrd;
  3. #import xlutils;
  4. from xlutils.copy import copy;
  5.  
  6. styleBoldRed   = xlwt.easyxf('font: color-index red, bold on');
  7. headerStyle = styleBoldRed;
  8. wb = xlwt.Workbook();
  9. ws = wb.add_sheet(gConst['xls']['sheetName']);
  10. ws.write(0, 0, "Header",        headerStyle);
  11. ws.write(0, 1, "CatalogNumber", headerStyle);
  12. ws.write(0, 2, "PartNumber",    headerStyle);
  13. wb.save(gConst['xls']['fileName']);
  14.  
  15. #open existed xls file
  16. #newWb = xlutils.copy(gConst['xls']['fileName']);
  17. #newWb = copy(gConst['xls']['fileName']);
  18. oldWb = xlrd.open_workbook(gConst['xls']['fileName'], formatting_info=True);
  19. print oldWb; #<xlrd.book.Book object at 0x000000000315C940>
  20. newWb = copy(oldWb);
  21. print newWb; #<xlwt.Workbook.Workbook object at 0x000000000315F470>
  22. newWs = newWb.get_sheet(0);
  23. newWs.write(1, 0, "value1");
  24. newWs.write(1, 1, "value2");
  25. newWs.write(1, 2, "value3");
  26. print "write new values ok";
  27. newWb.save(gConst['xls']['fileName']);
  28. print "save with same name ok";



阅读(3638) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~