xlrd与xlwt对象的方法不通用
对于xlrd读取出的文件对象,需要使用xlutils拷贝,得到xlwt对象才能进行编辑更新等操作。
#将xlrd对象读取为xlwt对象的方法:
startRows = []
oldWorkbook = xlrd.open_workbook(filePath)
sheetNames = ["第一季度", "第二季度", "第三季度", "第四季度"]
for i, sn in enumerate(sheetNames):
sheet = oldWorkbook.sheet_by_name(sn)
#记录一下各个sheet的表长,方便后续更新添加数据
startRows.append(sheet.nrows)
for j in range(1, startRows[i]):
existInfo[i].add((sheet.cell_value(j, 3), sheet.cell_value(j, 6)))
workbook = copy(oldWorkbook)
sheets = [workbook.get_sheet(sn) for sn in sheetNames]
#xlrd对象按照索引读取文件
如上文获取sheet对象
sheet.cell_value(i, j)
#创建与保存xlwt对象
workbook = xlwt.Workbook()
sheets = [workbook.add_sheet("第一季度"), workbook.add_sheet("第二季度"), workbook.add_sheet("第三季度"), workbook.add_sheet("第四季度")]
# 作用同上
startRows = [1, 1, 1, 1]
workbook.save(filePath)
#将数据写入xlwt对象
首先还是获取sheet对象
sheet.write(i, j, data)