注意: xlrd xlutils 只支持 xls 不支持 xlsx
想要往已经存在的xls文件中,写入新的行,新的数据,对应的逻辑为:
-
用xlrd.open_workbook打开已有的xsl文件
-
注意添加参数formatting_info=True,得以保存之前数据的格式
-
然后用,from xlutils.copy import copy;,之后的copy去从打开的xlrd的Book变量中,拷贝出一份,成为新的xlwt的Workbook变量
-
然后对于xlwt的Workbook变量,就是正常的:
-
通过get_sheet去获得对应的sheet
-
拿到sheet变量后,就可以往sheet中,写入新的数据
-
写完新数据后,最终save保存
-
#coding:utf-8
-
-
import xlrd
-
import xlwt
-
import requests
-
import time
-
from xlutils.copy import copy
-
-
-
data = xlrd.open_workbook("E:/接口测试用例.xls")
-
sheet = data.sheet_by_name("详细结果")
-
rows_no = sheet.nrows
-
print(rows_no)
-
-
new_data = copy(data)
-
new_sheet = new_data.get_sheet(1)
-
new_sheet.write(1, 1, "test1")
-
help(new_data.save)
-
new_data.save("E:/接口测试用例.xls")
原作者代码:
-
import xlwt;
-
import xlrd;
-
#import xlutils;
-
from xlutils.copy import copy;
-
-
styleBoldRed = xlwt.easyxf('font: color-index red, bold on');
-
headerStyle = styleBoldRed;
-
wb = xlwt.Workbook();
-
ws = wb.add_sheet(gConst['xls']['sheetName']);
-
ws.write(0, 0, "Header", headerStyle);
-
ws.write(0, 1, "CatalogNumber", headerStyle);
-
ws.write(0, 2, "PartNumber", headerStyle);
-
wb.save(gConst['xls']['fileName']);
-
-
#open existed xls file
-
#newWb = xlutils.copy(gConst['xls']['fileName']);
-
#newWb = copy(gConst['xls']['fileName']);
-
oldWb = xlrd.open_workbook(gConst['xls']['fileName'], formatting_info=True);
-
print oldWb; #<xlrd.book.Book object at 0x000000000315C940>
-
newWb = copy(oldWb);
-
print newWb; #<xlwt.Workbook.Workbook object at 0x000000000315F470>
-
newWs = newWb.get_sheet(0);
-
newWs.write(1, 0, "value1");
-
newWs.write(1, 1, "value2");
-
newWs.write(1, 2, "value3");
-
print "write new values ok";
-
newWb.save(gConst['xls']['fileName']);
-
print "save with same name ok";
阅读(3721) | 评论(0) | 转发(0) |