Error while loading excel file with Openpyxl - python

I am trying yo load an excel file using Openpyxl in Python.
from openpyxl import load_workbook
wb2 = load_workbook('Book1.xlsx')
print wb2.get_sheet_names()
It just these three lines. and it throws the following error:
Traceback (most recent call last):
File "C:/Python27/excel1.py", line 5, in <module>
wb2 = load_workbook('Book1.xlsx')
File "C:\Python27\Lib\site-packages\openpyxl\reader\excel.py", line 141, in load_workbook
archive = ZipFile(f, 'r', ZIP_DEFLATED)
File "C:\Python27\Lib\zipfile.py", line 793, in __init__
self._RealGetContents()
File "C:\Python27\Lib\zipfile.py", line 835, in _RealGetContents
raise BadZipfile, "File is not a zip file"
BadZipfile: File is not a zip file
This is exactly like their Documentation. https://openpyxl.readthedocs.org/en/latest/tutorial.html
Is their any better package to do this.

If this file does not exist at the desired location, try:
from openpyxl import load_workbook
from openpyxl import Workbook
# 1) create a workbook
wb = Workbook()
wb.save('my.xlsx')
del wb
# 2) build connection with the just created excel
book = load_workbook('my.xlsx')

It is an issue with the file. When we saved the file externally it was prompting this error. easy fix is to make a try catch and if the it gives the error create a new file in the same name and save on the same place. But for appending with old data wont work in this case.
try:
# this statement shall raise error for Badzip file
wb_obj = openpyxl.load_workbook(filename=path)
except:
# try to create a new file and save at same path
wb_obj = openpyxl.Workbook()
wb_obj.save(path)
wb_obj = openpyxl.load_workbook(filename=path)

xlsx files are zip archives. It looks like the file you're trying to open isn't. If you think this isn't the case please submit a but with a sample file.

Related

I'm trying to follow a beginners tutorial but i'm getting this exit code 1?

Here is my code to import an excel sheet and edit it:
import openpyxl as xl
wb = xl.load_workbook('transactions.xlxs')
sheet = wb['Sheet1']
cell = sheet['a1']
cell = sheet.cell(1, 1)
print(cell.value)
However I get the following error message:
C:\Users\mirco\PycharmProjects\pythonProject14\venv\Scripts\python.exe C:/Users/mirco/PycharmProjects/pythonProject14/main.py
Traceback (most recent call last):
File "C:\Users\mirco\PycharmProjects\pythonProject14\main.py", line 2, in <module>
wb = xl.load_workbook('transactions.xlxs')
File "C:\Users\mirco\PycharmProjects\pythonProject14\venv\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\mirco\PycharmProjects\pythonProject14\venv\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\mirco\PycharmProjects\pythonProject14\venv\lib\site-packages\openpyxl\reader\excel.py", line 94, in _validate_archive
raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support .xlxs file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm
Process finished with exit code 1
How can I fix this?
wb = xl.load_workbook('transactions.xlxs')
was supposed to be
wb = xl.load_workbook('transactions.xlsx')
a little dyslexic mistake
also had to move excel file to the right location

Openpyxl : the load_workbook function was automatically called when the open function run

the code as below
from openpyxl import *
wb = load_workbook(r'./test.xlsx')
ws = wb.active
ws1 = wb.create_sheet("Mysheet")
ws.delete_cols(2)
wb.save('./test.xlsx')
tagui_output = open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w')
tagui_output.write(temp_result)
tagui_output.close()
the output of code as below
C:\Downloads\TagUI_Windows\tagui\flows\samples> python .\excel2.py
fn of load_workbook = ./test.xlsx
fn of load_workbook = C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt
Traceback (most recent call last):
File "C:\Downloads\TagUI_Windows\tagui\flows\samples\excel2.py", line 7, in <module>
tagui_output = open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w')
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 316, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 94, in _validate_archive
raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: filename=C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt openpyxl does not support .txt file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm
It seems the load_workbook function was automatically called when the open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w') function run,why this happened ?
You've conflict for python io function open() with openpyxl.open.
from openpyxl import * is importing all functions which shadows built-in open(). Restrict from openpyxl imports to limited function calls which you use.
Also, use with open("path/tagui_py.txt", "w") as tagui_output: for better file-handling.

how to open a text file after opening workbook in openpyxl Python

i have been trying to append some data on my excel sheet using openpyxl and after that append some data in my text file...for some reason it gives me error whenever i try to open my text file
import openpyxl
from openpyxl import*
path = "students.xlsx"
To open the workbook
wb = openpyxl.load_workbook(path)
Get workbook active sheet object
sheet = wb.active
data to later append
data = (
(1, "john", 1/5/2022)
)
appending data
sheet.append(data)
saving and closing xlsx file
wb.save("students.xlsx")
wb.close()
problem lies here
with open("students.txt", "a") as f:
f.write(data[0]+data[1] + data[2])
here's my error
Traceback (most recent call last):
File "D:\taha\tools\attendance\quiz.py", line 32, in <module>
with open("students.txt", "a") as f:
File "C:\Users\FLH\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\FLH\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\FLH\AppData\Local\Programs\Python\Python310\lib\site-packages\openpyxl\reader\excel.py", line 94, in _validate_archive
raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: openpyxl does not support .txt file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm
In a quick view, you defined data as a tuple that contains a tuple with three elements.
As a first step to solve should use a list instead a tuple of tuples:
data = [1, "john", 1/5/2022]
Could you try this and let me know if it solves or you need more help.
Saying “thanks” is appreciated, but it doesn’t answer the question. Instead, vote up the answers that helped you the most! If these answers were helpful to you, please consider saying thank you in a more constructive way – by contributing your own answers to questions your peers have asked here.

Python openpyxl telling me " No such file or directory:" even though python file is in same directory as the excel file, among others

Beginner here.
I've tried making new excel files, running the python code while the excel file is open, tried renaming the excel file, but nothing works. I was just following this youtube tutorial: https://www.youtube.com/watch?v=7YS6YDQKFh0&t=14s
from openpyxl import Workbook, load_workbook
workbook = load_workbook("Test2.xlsx")
The error:
Traceback (most recent call last):
File "c:\Users\Name\Desktop\Python Projects\Excel Manipulation\Excel_Test.py", line 3, in <module>
workbook = load_workbook("Test2.xlsx")
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 315, in load_workbook
reader = ExcelReader(filename, read_only, keep_vba,
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
self.archive = _validate_archive(fn)
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 96, in _validate_archive
archive = ZipFile(filename, 'r')
File "C:\Users\Name\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1239, in __init__
self.fp = io.open(file, filemode)
**FileNotFoundError: [Errno 2] No such file or directory: 'Test2.xlsx'
PS C:\Users\Name>**
I found a solution. Turns out you just need to copy the file location, convert it to raw string, and add \ExcelFile to the end:
from openpyxl import Workbook, load_workbook
location = r'C:\Users\Name\Desktop\Python Projects\Excel Manipulation\Test2.xlsx'
workbook = load_workbook(location)
Derp.

File is not a zip file

I try to open a file with openpyxl but only get the error:
raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file
A simple code example:
from openpyxl import load_workbook
wb = load_workbook('path.xlsx')
Context: I am trying to open an existing excel file, edit the file and then save it. Until now I am able to only read the file with pandas.read_excel(path.xlsx).
The excel files were in read-only mode. I saved the file as a new file and load_workbook worked.

Categories