У меня есть следующий код для пользователя, чтобы выбрать электронную таблицу Excel (.xlsx), а затем остальная часть этой программы обработает ее и выдаст определенный вывод:
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
import tkinter
from tkinter.filedialog import askopenfilename
global filePath
filePath = ''
filePath = askopenfilename() # show an "Open" dialog box and return the path to the selected file
wb = load_workbook(filePath)
Это дает мнеследующее исключение в строке load_workbook ():
openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm
Я думаю, что проблема в том, что строку filePath необходимо преобразовать в необработанную строку.Я пробовал это, кодируя строку filePath в unicode_encode, регулярное выражение заменяя \ to \, но безуспешно.Это всегда дает мне одну и ту же ошибку.
Тем не менее, если я пытаюсь статически поместить путь, как показано в следующем коде, он работает безупречно:
wb = load_workbook(r'C:\MyPath\To\Wherever\Excel.xlsx')
Моя версия Python: Python 3.7.3
Есть идеи, как я могу решить эту проблему?
Спасибо
РЕДАКТИРОВАТЬ: так как приведенный выше фрагмент из моего кода работает нормально, здесь я вставляю свой полный кодвсего этого (есть также некоторые функции pyautogui, но все работает нормально, у меня проблема только с openpyxl):
#!/usr/bin/env python
# coding: utf-8
import pyautogui
import time
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
import clipboard
import tkinter
from tkinter.filedialog import askopenfilename
import re
import string
#FailSafe
pyautogui.FAILSAFE = True
global filePath
filePath = ''
#Define choose excel
def chooseExcel():
filePath = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filePath)
print('end of chooseExcel function')
#Define main function
def mainFunction():
#Handling saving of the Excel sheet when CTRL+C is pressed
import signal
import sys
def signal_handler(sig, frame):
print('Saving the excel sheet before exiting the program...')
wb.save(r'C:\Users\aiannacc\Desktop\ExampleNew.xlsx')
print('Saved! Exiting...')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('start of main')
#WORKING WITH EXCEL
#Get the number of rows and columns in the Excel sheet
wb = load_workbook(filePath)
#wb = load_workbook(r'C:\Users\aiannacc\Desktop\Example.xlsx')
sheet = wb.worksheets[0]
row_count = sheet.max_row
column_count = sheet.max_column
print(row_count)
print(column_count)
cellNumber = 2
firstRowIdentificator = 1
#Get all the values from Excel with Incident IDs
for cell in sheet['B']:
print(cell)
if firstRowIdentificator is 1:
firstRowIdentificator = 2
continue
print (cell.value)
incidentManagement = pyautogui.locateCenterOnScreen(r'C:\Users\aiannacc\Documents\ScreenshotsForAutomatingSecurityReport\1.png',confidence=.70)
print(incidentManagement)
pyautogui.moveTo(incidentManagement)
pyautogui.move(70, 0)
pyautogui.click()
time.sleep(0.1)
print(cell.value)
incidentID = cell.value
pyautogui.typewrite(incidentID)
time.sleep(0.3)
pyautogui.hotkey('enter')
time.sleep(6)
#Scroll down to the Updates section in the ticket
clickForGoingDownOnPage = pyautogui.locateCenterOnScreen(r'C:\Users\aiannacc\Documents\ScreenshotsForAutomatingSecurityReport\2.png',confidence=.70)
print(clickForGoingDownOnPage)
pyautogui.click(clickForGoingDownOnPage)
pyautogui.scroll(-700)
#Click on the text in the Updates section and copy it all
foundSolutionField = 'NoValueYet'
try:
updatesFieldInIM = pyautogui.locateCenterOnScreen(r'C:\Users\aiannacc\Documents\ScreenshotsForAutomatingSecurityReport\3.png',confidence=.70)
foundSolutionField = 'No'
print(updatesFieldInIM)
except TypeError:
solutionFieldInIM = pyautogui.locateCenterOnScreen(r'C:\Users\aiannacc\Documents\ScreenshotsForAutomatingSecurityReport\Solution.png',confidence=.70)
foundSolutionField = 'Yes'
if foundSolutionField is 'No':
pyautogui.moveTo(updatesFieldInIM)
pyautogui.move(200, 30)
pyautogui.click()
pyautogui.hotkey('ctrl', 'a')
time.sleep(0.2)
pyautogui.hotkey('ctrl', 'c')
#change this to a correct cell then later
#sheet['A2'] = 'Test123'
incidentID = clipboard.paste()
sheet['I' + str(cellNumber)] = incidentID
if foundSolutionField is 'Yes':
#pyautogui.alert(title='Errorik')
#change this to a correct cell then later
#sheet['A2'] = 'Test123'
print('incident id:')
print(incidentID)
sheet['I' + str(cellNumber)] = 'INCIDENT IS RESOLVED'
incidentID = 'INCIDENT IS RESOLVED'
cellNumber += 1
print('cellNumber is: ' + str(cellNumber))
closeTicketButton = pyautogui.locateCenterOnScreen(r'C:\Users\aiannacc\Documents\ScreenshotsForAutomatingSecurityReport\Xbutton.png',confidence=.70)
pyautogui.click(closeTicketButton)
time.sleep(1.5)
print('Saving the excel sheet before exiting the program...')
wb.save(r'C:\Users\aiannacc\Desktop\ExampleNew.xlsx')
print('Saved! Exiting...')
#### THIS PART NEEDS NOT TO BE INDENTED - IF COPYING AND PASTING IT, PLEASE, PUT THE BELOW CODE OUT OF ANY INDENTATIONS - THERE SHALL NOT BE ANY SPACES BEFORE THE BELOW CODE ####
top = tkinter.Tk()
top.title('My Program')
top.geometry('270x140')
button = tkinter.Button(text = 'Start!', command = mainFunction)
button.pack()
buttonChoose = tkinter.Button(text = 'Choose Excel', command = chooseExcel)
buttonChoose.pack()
label = tkinter.Label(text = 'Created by')
label.pack()
label2 = tkinter.Label(text = 'my name')
label2.pack()
top.mainloop()
Затем, точное сообщение ERROR , которое я получаю(скопировано из IDLE):
>>>
RESTART: C:\Users\aiannacc\AppData\Local\Programs\Python\Python37-32\myProgram.py
C:/Users/aiannacc/Desktop/Example.xlsx
end of chooseExcel function
start of main
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\aiannacc\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:\Users\aiannacc\AppData\Local\Programs\Python\Python37-32\AutomateSecurityReport - pyautogui_in_loop_new.py", line 60, in mainFunction
wb = load_workbook(filePath)
File "C:\Users\aiannacc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\reader\excel.py", line 318, in load_workbook
data_only, keep_links)
File "C:\Users\aiannacc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\reader\excel.py", line 126, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\aiannacc\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm