[英]Python xlrd and xlwt does not append to existing xls
我想為每次運行將列附加到相同的xls。 它沒有使用我現有的代碼附加。
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()
它正確獲取工作表名稱。 但不附加。
.txt是:
Selissues 11
Genissues 68
Noissues 7
Otherissues 13
Total 99999
Pruning/OtherEfficiency .58064516129032258064
CSEfficiency .38888888888888888888
希望Excel看起來像:
您的代碼有兩個問題。 第一,您沒有將wb_in
的現有內容復制到wb_out
。 您正在導入xlutils.copy
,但未使用它。
其次,您要寫出總是從第0
行開始的數據。 這意味着您將始終覆蓋已有的內容。
以下應解決這兩個問題。 需要注意的是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.