发生异常(..)-'Microsoft Excel','SaveAs ...类失败'

时间:2018-11-13 13:19:05

标签: python-3.x

这段代码基本上可以完成所需的工作。但是有时它确实会引发错误,而我希望代码能够正常工作,因为所有必要的数据都存在。

它的作用是:(1)读入用户(2)将信息添加到Excel仪表板,例如标题信息,词云和个人资料图片。

然后保存Excel文件。有时,几乎随机地会产生错误:(pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None))。代码的哪一部分可能导致这种情况?

import os
import xlwings as xw
import pandas as pd
import openpyxl


def get_users(file_name):
    """Read all the users from the csv file."""
    users = []
    f = open(file_name, 'r')
    for line  in f:
        user = line.strip().split(',')
        screen_name = user[0]
        users.append(screen_name)
    f.close()
    return users


def read_csv_file(file_name):
    """Return csv file with accounts."""
    data = []
    f = open(file_name, 'r')
    for line in f:
        temp = tuple(line.strip().split(';'))
        data.append(temp)
    f.close()
    return data


def write_panda_to_excel(df, start_cell, wb):
    """Write Pandas DataFrame to Excel."""
    sht = wb.sheets['Input']
    sht.range(start_cell).value = df


def add_word_cloud(name, cell, wb):
    """Add the WordCloud to Sheet2 """
    sht = wb.sheets['Sheet2']
    name = os.getcwd() + '\\' + name
    rng = sht.range(cell)
    sht.pictures.add(name, top=rng.top, left=rng.left, width=325, height=155)


def add_profile_picture(user, cell, wb):
    #Add charts to dashboard.
    sht = wb.sheets['Sheet1']
    picture = [f for f in os.listdir('.') if f.startswith(user + '.')][0]
    name = os.getcwd() + '\\' + picture
    rng = sht.range(cell)
    sht.pictures.add(name, top=rng.top, left=rng.left, width=70, height=90)


app = xw.App(visible=False)

# Read users
os.chdir('../FolderA/')
file_name = 'accounts_file.csv'
users = get_users(file_name)
os.chdir('../Data')

for i, user in enumerate(users):
    try:
        #count += 1
        print(100 * '-')
        print(len(users), i+1, user)

        # go to directory where the dashboard is stored
        os.chdir('../Folder5/FolderE')
        wb = xw.Book('Twitter - Individuele Rapportage.xlsm')
        os.chdir('../../Data/' + user)

        # Remove file if exists
        xl = [e for e in os.listdir('.') if e.endswith('.xlsm')]
        for e in xl:
            os.remove(e)

        # add user name to title of Dashboard
        sht = wb.sheets['Input_Data']

        # add the csv data and profile pictures the other data to the dashboard
        df = pd.read_csv(user + '_header_info.csv', sep=',')
        write_panda_to_excel(df, 'A1', wb)

        cell = 'L20'
        try:
            add_profile_picture(user, cell, wb)
        except:
            os.chdir('../../Folder6')
            with open('Twitter - Profile picture Error.txt', 'a') as ExceptFile:
                ExceptFile.write(str(user) + '\n')
                os.chdir('../Data/' + user)

        name = user + '_WC.png'
        cell = 'Y46'
        add_word_cloud(name, cell, wb)

        xlname = 'Twitter' + user + '.xlsm'

        try:
            wb.save(xlname)
            wb.close()

        except:
            os.chdir('../../Folder6')
            with open('Twitter - Dashboard Generation Errors.txt', 'a') as myfile:
                myfile.write(str(user + "\n"))
                myfile.close()
            os.chdir('../Data/' + user)
        os.chdir('..')

    except OSError as exception:
        print(exception)
        os.chdir('..')
        with open('dash_errors.txt', 'w') as dashboard_errors:
            dashboard_errors.write(user+"\n")

0 个答案:

没有答案