如何更新Excel数据?(刷新所有查询)
我有一个Excel的xlsm文件,里面有一些查询。
现在我每天都要打开这个文件,然后在“数据”选项卡里点击“全部刷新”这个命令。我想让这个过程自动化。我写了一个Python脚本(我还是Python的新手)。
问题是,数据刷新后,虽然我保存了Excel文件,但刷新后的数据却看不见(我知道刷新是有效的,因为如果我不保存就关闭Excel文件,刷新后的数据是能在文件里看到的)。
奇怪的是,保存功能也正常,因为当我尝试修改'config'里的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的其他库?
2 个回答
1
要刷新你的查询和数据透视表,在Excel中,先点击“数据”> “查询和连接”,然后右键点击你想要的查询,选择“查询属性”。接着,取消勾选“启用后台刷新”这个选项。
4
因为你请求另一个脚本来执行这个操作,我推荐使用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()