从Python连接到Excel 2016(365)并执行任务

2024-10-01 11:31:11 发布

您现在位置:Python中文网/ 问答频道 /正文

在windows 10中连接到Excel API时出现问题。我使用Office365和Excel2016。我的目标是:从客户机FTPS服务器下载CSV文件,将其与现有文件合并,对其执行一些操作(使用pandas),然后将整个数据加载到excel中并使用它进行报告。。。在将它加载到Excel中之前,一切都很好,我设法用Python自动完成所有步骤(如果我的代码看起来有点混乱,很抱歉,我是Python新手)

import subprocess
import os
import ftplib
import fnmatch
import sys
from ftplib import FTP_TLS
from win32com.client import Dispatch
import pandas as pd

filematch = '*.csv'
target_dir = 'cannot tell you the path :-) '

def loginftps(servername,user,passwort):
    ftps = FTP_TLS(servername)
    ftps.login(user=user,passwd=passwort)
    ftps.prot_p()
    ftps.cwd('/changes to some directory')

    for filename in ftps.nlst(filematch):
        target_file_name = os.path.join(target_dir,os.path.basename(filename))
        with open(target_file_name,'wb') as fhandle:
                ftps.retrbinary('RETR %s' %filename, fhandle.write)

def openExcelApplication():
    xl = Dispatch("Excel.Application")
    xl.Visible = True # otherwise excel is hidden

def mergeallFilestoOneFile():
    subprocess.call(['prepareData_executable.bat'])

def deletezerorows():
    rohdaten = pd.read_csv("merged.csv",engine="python",index_col=False,encoding='Latin-1',delimiter=";", quoting = 3)
    rohdaten = rohdaten.convert_objects(convert_numeric=True)
    rohdaten = rohdaten[rohdaten.UN_PY > 0]
    del rohdaten['deletes something']
    del rohdaten['deletes something']
    rohdaten.to_csv('merged_angepasst.csv',index=False,sep=";")

def rohdatenExcelAuswertung():
    csvdaten = pd.csv_read("merged.csv")

servername = input("please enter FTPS serveradress:")
user = input("Loginname:")
passwort = input("Password:")

loginftps(servername,user,passwort)
mergeallFilestoOneFile()
deletezerorows()

我在这里不知怎么地卡住了,。。我做了大量的google研究,但是不知怎么的,从来没有人尝试在Python中执行Excel任务??在

我发现了这个stackoverflow讨论:Opening/running Excel file from python,但不知怎么的,我无法确定我的Excel应用程序存储在哪里来运行这个线程中提到的代码。在

我有一个Excel工作簿,它与我的CSV文件有数据连接。我希望Python打开msexcel,刷新数据连接,刷新数据透视表,然后保存并关闭文件。在

这里有没有人尝试过类似的东西,并能提供一些代码让我开始? 谢谢


Tags: 文件csv数据代码fromimporttargetos
1条回答
网友
1楼 · 发布于 2024-10-01 11:31:11

一小段代码,可用于打开excel文件、更新链接数据、保存并最终关闭它:

from win32com.client import Dispatch

xl = Dispatch("Excel.Application")
xl.Workbooks.Open(Filename='C:\\Users\\Xukrao\\Desktop\\workbook.xlsx', UpdateLinks=3)
xl.ActiveWorkbook.Close(SaveChanges=True)
xl.Quit()

相关问题 更多 >