Python openpyxl module says: AttributeError: 'tuple' object has no attribute 'upper' - python

Installed Python 3.4 and modules jdcal and openpyxl:
Trying myself on the openpyxl library to read and write XLSX files from Python. I installed the jdcall module and the openpyxl module. Code lets me create the workbook and work sheet:
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
However, if I try to write to the first cell like this:
ws[ 1, 1] = 'testing 1-2-3'
Python says:
C:\Wolf\Python Studies>database.py
Traceback (most recent call last):
File "C:\Wolf\Python Studies\database.py", line 13, in <module>
ws[ 1, 1] = 'testing 1-2-3'
File "C:\Python34\lib\site-packages\openpyxl-2.2.0b1-py3.4.egg\openpyxl\worksheet\worksheet.py", line 403, in __setitem__
self[key].value = value
File "C:\Python34\lib\site-packages\openpyxl-2.2.0b1-py3.4.egg\openpyxl\worksheet\worksheet.py", line 400, in __getitem__ <BR>
return self._get_cell(key)
File "C:\Python34\lib\site-packages\openpyxl-2.2.0b1-py3.4.egg\openpyxl\worksheet\worksheet.py", line 368, in _get_cell
coordinate = coordinate.upper()
AttributeError: 'tuple' object has no attribute 'upper'
C:\Wolf\Python Studies>
Any idea what I am doing wrong?

Cell coordinates should be provided as a string:
ws['A1'] = 'testing 1-2-3'
Or, if you want to use row and column indexes, use ws.cell().value:
ws.cell(row=1, column=1).value = 'testing 1-2-3'

Related

openpyxl: AttributeError: 'MergedCell' object attribute 'value' is read-only

When i'm trying to fill the cell in existing .xlsx file and then save it to a new one I got message:
import openpyxl
path = "/home/karol/Dokumenty/wzor.xlsx"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
new_protokol = sheet_obj
firma = input("Podaj nazwe: ")
nazwa_pliku = "Protokol odczytu"
filename = nazwa_pliku + firma + ".xlsx"
sheet_obj["C1"] = firma
sheet_obj["D1"] = input()
new_protokol.save(filename=filename)
Traceback (most recent call last):
File "/home/karol/PycharmProjects/Protokolu/Main.py", line 16, in <module>
sheet_obj["C1"] = firma
File "/home/karol/PycharmProjects/Protokolu/venv/lib/python3.7/site-packages/openpyxl/worksheet/worksheet.py", line 309, in __setitem__
self[key].value = value
AttributeError: 'MergedCell' object attribute 'value' is read-only
Process finished with exit code 1
How to fix it?
When you merge cells all cells but the top-left one are removed from the worksheet. To carry the border-information of the merged cell, the boundary cells of the merged cell are created as MergeCells which always have the value 'None'
ws.merge_cells('B2:F4')
top_left_cell = ws['B2']
top_left_cell.value = "My Cell"
Please try this approach, it'll work just fine for you.
To write in a merge cell, you must write in the cell in the upper left corner. And the error will not come out.
ws['I6']="123123123"
wb.save(filename=path....)
I also met this error. I deleted my current Excel file and replaced it with a good Excel file, and then the error disappeared.

Python: got an AttributeError when using the font attribue of the openpyxl module

The code below is from a Python tutoring website. But I get the AttributeError when running it.
import openpyxl
from openpyxl.styles import Font
wb = openpyxl.Workbook()
sheet = wb.get_sheet_by_name('Sheet')
italic24Font = Font(size=24, italic=True)
sheet['A1'].font = italic24Font
sheet['A1'] = 'Hello world!'
wb.save('styled.xlsx')
Error message:
> Traceback (most recent call last):
File "C:\Users\zs\AppData\Local\Programs\Python\Python36\test.py", line 6, in <module>
sheet['A1'].font = italic24Font
AttributeError: can't set attribute
You can try as below,
your_cell.font.size = 24
your_cell.font.italic = True
and also check the doc for clear understanding on how to apply styles.
I hava the same errors too:
c.fill = PatternFill('solid', fgColor=RED, bgColor=RED, fill_type='darkGray')
change it:
c.fill.bgColor = RED
But nothing changed, there is a error too.

Cannot write to an excel AttributeError: 'Worksheet' object has no attribute 'write'

I am trying to write text to an excel I am following this post. This was working earlier but now it is not. I get:
Error:
line 122, in <module>
worksheet.write(0, 11, 'HI')
AttributeError: 'Worksheet' object has no attribute 'write'
df1
A E
c d
c D
Code:
writer = pd.ExcelWriter("C:\\33.xlsx")
df1.to_excel(writer, startrow=0, startcol=0, index = False)
worksheet = writer.sheets['Sheet1']
worksheet.write(0, 11, 'YO')
worksheet.write(1, 11, 'HI')
I have tried also:
import xlrd
import xlwt
from xlutils.copy import copy
import os.path
rb = xlrd.open_workbook('C:\\13.xlsx',formatting_info=True)
r_sheet = rb.sheet_by_index(0)
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(5,2,"string")
wb.save('C:\\13.xlsx')
I get:
with open(filename, "rb") as f:
OSError: [Errno 22] Invalid argument: 'C:\\13.xlsx"'
How do I fix AttributeError: 'Worksheet' object has no attribute 'write'
The reason it gives: AttributeError: 'Worksheet' object has no attribute 'write'
Is because I realised I have not installed xlsxwriter on this pc.
pip install xlsxwriter
Now it works.

Invalid mode or filename when using openpyxl in python 2.7

I am trying to write something in an existing workbook with the openpyxl tools.
But i am getting Err no 22 and dont know why.
My Script looks like this :
#Reading & writing to a workbook
from openpyxl import Workbook
from openpyxl.compat import range
from openpyxl.cell import get_column_letter
wb = Workbook()
dest_filename = 'J:\Python_Script\book2.xls'
ws = wb.active
ws.title = "Tabelle 1"
for col_idx in range(1, 40):
col = get_column_letter(col_idx)
for row in range(1, 600):
ws.cell('%s%s'%(col, row)).value = '%s%s' % (col, row)
ws = wb.create_sheet()
ws.title = 'Pi'
ws['F5'] = 3.14
wb.save(filename = dest_filename)
and this is the Console output with the error message i got :
//------------------
Traceback (most recent call last):
File "J:/Python_Script/xlsx_test.py", line 26, in <module>
wb.save(filename = dest_filename)
File "build\bdist.win32\egg\openpyxl\workbook\workbook.py", line 281, in save
save_workbook(self, filename)
File "build\bdist.win32\egg\openpyxl\writer\excel.py", line 214, in save_workbook
writer.save(filename)
File "build\bdist.win32\egg\openpyxl\writer\excel.py", line 196, in save
archive = ZipFile(filename, 'w', ZIP_DEFLATED)
File "C:\Python27\lib\zipfile.py", line 752, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 22] invalid mode ('wb') or filename: 'J:\\Python_Script\x08ook2.xls'
//----------------------
I am not sure why the file path is different now, also the file name different from the filename in the input section.
thanks
EDIT:
Solved. Just had to change from \ to / in the path.
In Python the \ is used in strings to escape characters. You can avoid this by using "raw strings" by prefixing with "r". So r'J:\Python_Script\book2.xls' should work.
However, when working with paths it's most common to use the os.path module to make sure this are correct.
dest_filename = os.path.join("J:", "Python_Script", "book2.xlsx")
This is invaluable when writing portable code.

Read through an unstructured xls file

I have an .xls file which contains one column with 2,000 rows.
I want to iterate through the file and print out the data points
which start with "cheap". However, the following code doesn't work.
Help!
import xlrd
wb = xlrd.open_workbook("file.xls")
wb.sheet_names()
sh = wb.sheet_by_index(0)
lst = [sh]
for item in lst:
print item.startswith("cheap")
Traceback (most recent call last):
File "C:\Python26\keywords.py", line 14, in <module>
print item.startswith("cheap")
AttributeError: 'Sheet' object has no attribute 'startswith'
it should look like:
import xlrd
wb = xlrd.open_workbook("file.xls")
wb.sheet_names()
sh = wb.sheet_by_index(0)
for item in sh.col(0):
value = unicode(item.value)
if value.startswith("cheap"):
print value

Categories