Python 将数据附加到现有的 Excel 电子表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28363562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Append data to an existing excel spreadsheet
提问by komal bhardwaj
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.
对于从给定的 .txt 文件中获取的每个 url,我希望能够计算标签的数量并将其打印到每个 excel 文件中。我想为每个 url 覆盖文件,然后附加到 excel 文件。
回答by Igor Hatarist
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.
您应该使用xlrd.open_workbook()
来加载现有的 Excel 文件,使用 创建一个可写副本xlutils.copy
,然后进行所有更改并将其另存为。
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")