使用Python自动执行在Excel中加载.csv文件的步骤

时间:2019-02-11 07:07:16

标签: python excel automation

我必须定期将许多.csv文件加载到Excel中,如图所示here (till step 9)-

Excel -> 数据-> 来自文本-> “通过导航到文件位置然后单击导入来选择文件。 '-> 文本导入向导的第1步,共3步

我通过编写一个小的python脚本使所有这些步骤自动化,在该脚本中,我使Python按下快捷键(想象不用鼠标工作,并通过按下快捷键在Excel中导航)。

import pyautogui
from pywinauto.application import Application
app = Application().start('C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.exe')
pyautogui.press('alt')
pyautogui.press('a')
pyautogui.press('f')
pyautogui.press('t')
pyautogui.typewrite(r'C:\Users\Jo\Revenue.txt')
pyautogui.press('enter')

运行上述python脚本后,向我显示导入向导窗口-

Import Wizard

现在,如何使python从下拉列表中选择65001 : Unicode (UTF-8)?如何在python代码中指定选择此编码?任何输入将不胜感激。

1 个答案:

答案 0 :(得分:0)

这就是我要做的。将UTF-8 with BOM添加到文件开头将自动指示excel在file origin下拉列表中选择UTF:

import codecs
import pyautogui

from pywinauto.application import Application
from pywinauto.keyboard import SendKeys

from time import sleep

filename = r'C:\path\excel_automation\data1.txt'
global content

def add_utf8_bom(filename):
    with codecs.open(filename, 'r', 'utf-8') as f:
        content = f.read()
    with codecs.open(filename, 'w', 'utf-8') as f2:
        f2.write('\ufeff')
        f2.write(content)

add_utf8_bom(filename)
app = Application().start(r'C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE')
sleep(1)
#SendKeys('^n') #uncomment for excel 2016 or higher
sleep(1)
pyautogui.press('alt')
pyautogui.press('a')
pyautogui.press('f')
pyautogui.press('t')
pyautogui.typewrite(filename)
pyautogui.press('enter')

信用:https://stackoverflow.com/a/29900075/4551984