Append data to an existing excel spreadsheet

隐身守侯 提交于 2021-02-07 08:47:51

问题


I wrote the following function to accomplish this task.

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

For every url taken from a given .txt file, I want to be able to count the number of tags and print that to each excel file. I want to overwrite the file for each url, and then append to the excel file.


回答1:


You should use xlrd.open_workbook() for loading the existing Excel file, create a writeable copy using xlutils.copy, then do all the changes and save it as.

Something like that:

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


来源:https://stackoverflow.com/questions/28363562/append-data-to-an-existing-excel-spreadsheet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!