向现有的Excel电子表格追加数据

4
我编写了以下函数来完成此任务。
def write_file(url,count):

    book = xlwt.Workbook(encoding="utf-8")
    sheet1 = book.add_sheet("Python Sheet 1")
    colx = 1
    for rowx in range(1):

        # Write the data to rox, column
        sheet1.write(rowx,colx, url)
        sheet1.write(rowx,colx+1, count)


    book.save("D:\Komal\MyPrograms\python_spreadsheet.xls")

对于从给定的 .txt 文件中获取的每个 URL,我希望能够计算标签的数量,并将其打印到每个 Excel 文件中。我希望为每个 URL 覆盖文件,然后将其附加到 Excel 文件中。

1个回答

6
你应该使用xlrd.open_workbook()来加载现有的Excel文件,使用xlutils.copy创建一个可写副本,然后进行所有更改并将其保存。类似这样:
from xlutils.copy import copy    
from xlrd import open_workbook

book_ro = open_workbook("D:\Komal\MyPrograms\python_spreadsheet.xls")
book = copy(book_ro)  # creates a writeable copy
sheet1 = book.get_sheet(0)  # get a first sheet

colx = 1
for rowx in range(1):
    # Write the data to rox, column
    sheet1.write(rowx,colx, url)
    sheet1.write(rowx,colx+1, count)

book.save("D:\Komal\MyPrograms\python_spreadsheet.xls")

@komalbhardwaj 抱歉,我修复了。是 book 对象的问题。 - Igor Hatarist
NameError: 全局名称 'wb' 未定义。 - komal bhardwaj
@komalbhardwaj 请检查上面的修正代码:sheet1 = book.get_sheet(0) - Igor Hatarist
1
请注意,在复制过程中可能会丢失一些数据,例如某些公式。这意味着在某些情况下,您无法使用xlrd/xlwt/xlutils将数据附加到现有的Excel文件中。 - smwikipedia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接