[英]Python xlrd and xlwt does not append to existing xls
I want to append columns to the same xls for every run. 我想为每次运行将列附加到相同的xls。 Its not getting appended using my existing code. 它没有使用我现有的代码附加。
import xlwt
import xlrd
from xlutils.copy import copy
wb_in = xlrd.open_workbook('~/new.xls', 'r+')
sheet_name = wb_in.sheet_names()[0]
ws_in = wb_in.sheet_by_name(sheet_name)
wb_out = xlwt.Workbook()
ws_out = wb_out.add_sheet(sheet_name) # Use the same sheet name
f = open('~/count.txt', 'r+')
data = f.readlines() # read all lines at once
for i in range(len(data)):
row = data[i].split() # This will return a line of string data, you may need to convert to other formats depending on your use case
for j in range(len(row)):
ws_out.write(i, j, row[j]) # Write to cell i, j
wb_out.save('~/new' + '.xls')
f.close()
Its getting the sheet name correctly. 它正确获取工作表名称。 But is not appending. 但不附加。
count .txt is : .txt是:
Selissues 11
Genissues 68
Noissues 7
Otherissues 13
Total 99999
Pruning/OtherEfficiency .58064516129032258064
CSEfficiency .38888888888888888888
Want the excel to look like : 希望Excel看起来像:
Your code has two problems. 您的代码有两个问题。 One, you aren't copying the existing contents of wb_in
to wb_out
. 第一,您没有将wb_in
的现有内容复制到wb_out
。 You're importing xlutils.copy
, but not using it. 您正在导入xlutils.copy
,但未使用它。
Second, you're writing out the data always beginning from row 0
. 其次,您要写出总是从第0
行开始的数据。 This means you'll always be overwriting whatever is already there. 这意味着您将始终覆盖已有的内容。
The following should resolve both of those issues. 以下应解决这两个问题。 Note that wb_out
is being set to a copy of wb_in
, and that when writing to ws_out
, the row number is being offset by ws_in.nrows
, the number of rows that already existed in ws_in
: 需要注意的是wb_out
被设置为副本wb_in
,并写入时ws_out
,行号是由偏移ws_in.nrows
,已经在存在的行数ws_in
:
from xlrd import open_workbook
from xlutils.copy import copy
wb_in = open_workbook('~/new.xls', 'r+')
ws_in = wb_in.sheet_by_index(0)
wb_out = copy(wb_in)
ws_out = wb_out.get_sheet(0)
f = open('~/count.txt', 'r+')
data = f.readlines()
for i in range(len(data)):
row = data[i].split()
for j in range(len(row)):
ws_out.write(ws_in.nrows + i, j, row[j].strip())
wb_out.save('~/new.xls')
f.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.