douqin6785 2014-05-10 18:41
浏览 607
已采纳

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

I have a Excel xlsm file with a few queries.

Currently I open it every day and click on the "Refresh All" command in the "Data" tab. I want this to be done automatically. I wrote a script in python (I'm a newbie in Python).

The problem is that after the data is refreshed and the Excel file has been saved, the refreshed data is not visible (I know that refreshing works because if I prevent to save and close the Excel file, the refreshed data is visible in the file )

The weird thing is that saving also works fine because when I try to modify cell B2 from 'config' it is changed...

Where is the problem?

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)

Maybe someone can recommend another script? For example, Powershell? PHP? Or an other library for Python3?

  • 写回答

1条回答 默认 最新

  • dongshushen4392 2014-05-11 19:39
    关注

    Since you requested another script to perform this action, I recommend PowerShell. As a simple test, I created an Excel document, SheetToRefresh.xlsx, which has a data connection to a simple xml file. However, the script below will work for any data source that the Excel document is connected to. I have tested this on my own machine, the data refresh and save persists, as expected.

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题