Exception Occurred (..) - 'Microsoft Excel', 'SaveAs … class failed'












1















This code basically does what it needs to do. But it does throw an error sometimes whereas I would expect the code to work as all data necessary is present.



So what it does is: (1) Read in users (2) Add information to the Excel dashboard, such as header information, word clouds and profile picture.



Then it saves the Excel file. It sometimes, randomly almost, gives an error: (pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)). What part of the code could cause this?



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")









share|improve this question




















  • 1





    I edited the question. Maybe it's clearer now

    – mrPy
    Nov 13 '18 at 15:08
















1















This code basically does what it needs to do. But it does throw an error sometimes whereas I would expect the code to work as all data necessary is present.



So what it does is: (1) Read in users (2) Add information to the Excel dashboard, such as header information, word clouds and profile picture.



Then it saves the Excel file. It sometimes, randomly almost, gives an error: (pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)). What part of the code could cause this?



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")









share|improve this question




















  • 1





    I edited the question. Maybe it's clearer now

    – mrPy
    Nov 13 '18 at 15:08














1












1








1








This code basically does what it needs to do. But it does throw an error sometimes whereas I would expect the code to work as all data necessary is present.



So what it does is: (1) Read in users (2) Add information to the Excel dashboard, such as header information, word clouds and profile picture.



Then it saves the Excel file. It sometimes, randomly almost, gives an error: (pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)). What part of the code could cause this?



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")









share|improve this question
















This code basically does what it needs to do. But it does throw an error sometimes whereas I would expect the code to work as all data necessary is present.



So what it does is: (1) Read in users (2) Add information to the Excel dashboard, such as header information, word clouds and profile picture.



Then it saves the Excel file. It sometimes, randomly almost, gives an error: (pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', 'Open method of Workbooks class failed', 'xlmain11.chm', 0, -2146827284), None)). What part of the code could cause this?



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")






python-3.x






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 15:08







mrPy

















asked Nov 13 '18 at 13:19









mrPymrPy

857




857








  • 1





    I edited the question. Maybe it's clearer now

    – mrPy
    Nov 13 '18 at 15:08














  • 1





    I edited the question. Maybe it's clearer now

    – mrPy
    Nov 13 '18 at 15:08








1




1





I edited the question. Maybe it's clearer now

– mrPy
Nov 13 '18 at 15:08





I edited the question. Maybe it's clearer now

– mrPy
Nov 13 '18 at 15:08












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53281903%2fexception-occurred-microsoft-excel-saveas-class-failed%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53281903%2fexception-occurred-microsoft-excel-saveas-class-failed%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Full-time equivalent

Bicuculline

さくらももこ