如何不断更新和显示Excel信息?

时间:2018-04-23 19:09:39

标签: python excel

每次修改原始文件时,我都需要更新工作表的副本。需要随时打开副本,以便每个人都可以看到它何时更新。到目前为止,还没有处理代码来检测文件修改,我只是在努力能够更新工作表。我找到了两种方法,它们如下:

1)第一种方法是使用openpyxl。这样做我认为我必须先将数据写入Todolist2,然后在excel应用程序中打开该文件。然后,当原始文件被修改时,它必须在重新写入更新的数据之前关闭excel。然后重新打开它。以下是我到目前为止的情况。使用sleep(10)让我有机会更新example.xlsx,以便模拟将新数据写入Todolist2。只要我将Todolist2写入更新数据后关闭Todolist2就可以了,它不会被拒绝。 (A)但是在第一次通过后它不会更新新数据。 (B)无论如何都要在excel中打开文件,这样我就可以继续向它写入更新的数据,而不是先将它关闭(文件不需要保存)? (下面第二种方式允许我这样做)。

import openpyxl as xl
from copy import copy
import time, os

path1 = 'C:\\example.xlsx'
path2 = 'C:\\Todolist2.xlsx'

wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]

wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.worksheets[0]

while True:
    for row in ws1:
        for cell in row:
            ws2[cell.coordinate].value = cell.value
            if cell.has_style:
                ws2[cell.coordinate].font = copy(cell.font)
                ws2[cell.coordinate].border = copy(cell.border)
                ws2[cell.coordinate].fill = copy(cell.fill)
                ws2[cell.coordinate].number_format = 
                copy(cell.number_format)
                ws2[cell.coordinate].protection = copy(cell.protection)
                ws2[cell.coordinate].alignment = copy(cell.alignment)
    wb2.save(path2)
    os.startfile('C:\\Todolist2.xlsx')
    #I will need something here to close out excel to allow python to 
    #write to it again, otherwise it will throw permission denied.
    time.sleep(10)     #during this time I will modify example.xlsx and 
                       #save, so on the next go around it rewrites the 
                       #new data to Todolist1.xlsx.  However, it does not 
                       #update to Todolist2.  

(2)我试图解决的第二种方法是使用win32com。这允许我在窗口中保持Todolist2在excel中打开,同时从示例,example1,然后是example2写入它。但问题是,它不会写在活动表上,它会不断添加其他工作表。所以在这个问题上,如果我能找到一种方法来重写Todolist2中的活动工作表,或者在添加了附加工作表之后,我可以删除一个也可以工作的旧工作表。 (A)有什么功能可以继续删除旧纸张?

import time, os.path, os
from win32com.client import Dispatch

path1 = 'C:\\example.xlsx'
path2 = 'C:\\Todolist2.xlsx'
path3 = 'C:\\example2.xlsx'
path4 = 'C:\\example3.xlsx'


xl = Dispatch("Excel.Application")
xl.Visible = True

wb1= xl.Workbooks.Open(Filename=path1)
wb2= xl.Workbooks.Open(Filename=path2)

ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))

time.sleep(5)

wb3= xl.Workbooks.Open(Filename=path3)
ws3 = wb3.Worksheets(1)

ws2 = wb2.Worksheets(3)      #it seems by using (3) is the only way it 
                             #allows me to delete one sheet before it 
                             #adds another.
ws2.Delete()
ws3.Copy(Before=wb2.Worksheets(1))

time.sleep(5)

wb4= xl.Workbooks.Open(Filename=path4)
ws4 = wb4.Worksheets(1)

ws2.Delete()            #I got into trouble here, and throws error even 
                        #though it does the delete and copy
ws4.Copy(Before=wb2.Worksheets(1))

0 个答案:

没有答案