2015-02-06 61 views
1

我編寫了以下函數來完成此任務。將數據附加到現有的Excel電子表格

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文件。

回答

3

您應該使用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") 
+0

@komalbhardwaj對不起,我固定它。這是「書」的對象。 – 2015-02-06 10:50:33

+0

NameError:未定義全局名稱'wb' – 2015-02-06 10:54:30

+0

@komalbhardwaj'sheet1 = book.get_sheet(0)',檢查上面的固定代碼 – 2015-02-06 11:01:28

相關問題