如何更新Excel数据?(刷新所有查询) [英] How to update Excel data? (Refresh all queries)

查看:62
本文介绍了如何更新Excel数据?(刷新所有查询)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含几个查询的Excel xlsm文件。

目前,我每天都打开它,然后单击"Data"选项卡中的"Refresh All"命令。我希望这是自动完成的。我用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'\serverCC_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文档SheetToRechres.xlsx,它具有到一个简单XML文件的数据连接。但是,下面的脚本将适用于Excel文档连接到的任何数据源。我已经在我自己的计算机上对此进行了测试,数据刷新和保存如预期的那样持续存在。

刷新Excel.ps1

#Set the file path (can be a network location)
$filePath = "C:ScriptsSheetToRefresh.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数据?(刷新所有查询)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆