如何更新Excel数据?(刷新所有查询)


How to update Excel data? (Refresh all queries)

我有一个Excel xlsm文件与几个查询。

目前我每天打开它,点击"数据"选项卡中的"刷新所有"命令。我希望这是自动完成的。我用python写了一个脚本(我是python的新手)。

问题是,数据刷新后,Excel文件已保存,刷新的数据是不可见的(我知道,刷新工作,因为如果我防止保存和关闭Excel文件,刷新的数据是可见的文件)

奇怪的是,保存也工作得很好,因为当我试图修改单元格B2从'配置'它被改变…

问题在哪里?

import win32com.client
import datetime
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
office = win32com.client.Dispatch("Excel.Application")
wb = office.Workbooks.Open(r'''server'CC_source.xlsm')
office.DisplayAlerts = True
office.Visible = True
wb.RefreshAll()
sh = wb.Worksheets("config")
sh.Cells(2,2).Value = wczoraj
wb.Close(True)

也许有人可以推荐另一个脚本?例如,Powershell?PHP吗?或者是Python3的其他库?

由于您需要另一个脚本来执行此操作,因此我推荐使用PowerShell。作为一个简单的测试,我创建了一个Excel文档SheetToRefresh.xlsx,它具有到一个简单xml文件的数据连接。但是,下面的脚本将适用于Excel文档所连接的任何数据源。我已经在我自己的机器上测试了这个,数据刷新和保存仍然存在,正如预期的那样。

RefreshExcel.ps1

#Set the file path (can be a network location)
$filePath = "C:'Scripts'SheetToRefresh.xlsx"
#Create the Excel Object
$excelObj = New-Object -ComObject Excel.Application
#Make Excel visible. Set to $false if you want this done in the background
$excelObj.Visible = $true
#Open the workbook
$workBook = $excelObj.Workbooks.Open($filePath)
#Focus on the top row of the "Data" worksheet
#Note: This is only for visibility, it does not affect the data refresh
$workSheet = $workBook.Sheets.Item("Data")
$workSheet.Select()
#Refresh all data in this workbook
$workBook.RefreshAll()
#Save any changes done by the refresh
$workBook.Save()
#Uncomment this line if you want Excel to close on its own
#$excelObj.Quit()

要刷新您的查询,然后您的数据透视,在Excel中转到data>查询和连接;右键单击查询查询属性>取消启用背景刷新