Python xlrd和xlwt不会追加到现有的xls

时间:2018-12-18 12:59:36

标签: python xlrd xlwt

我想为每次运行将列附加到相同的xls。不会使用我现有的代码附加它。

DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG: SMTPTransport trying to connect to host "mail.bizsolindia.com", port 465

它正确获取工作表名称。但是没有附加。

count .txt是:

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()

希望Excel看起来像这样:

enter image description here

1 个答案:

答案 0 :(得分:0)

您的代码有两个问题。第一,您没有将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()