I want to append columns to the same xls for every run. 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 :
Selissues 11
Genissues 68
Noissues 7
Otherissues 13
Total 99999
Pruning/OtherEfficiency .58064516129032258064
CSEfficiency .38888888888888888888
Want the excel to look like :
Your code has two problems. One, you aren't copying the existing contents of wb_in
to wb_out
. You're importing xlutils.copy
, but not using it.
Second, you're writing out the data always beginning from row 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
:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.