AttributeError: 'Worksheet' object has no attribute 'set_column' - python

I am getting an error that seems... wrong. Because of course worksheet object has set_column() as a function, it's in the docs. I've probably done something dumb like drop a parenthesis.
Here's the error:
Traceback (most recent call last):
File "scrubaddresses.py", line 137, in <module>
run()
File "scrubaddresses.py", line 118, in run
format_col_width(worksheet)
File "scrubaddresses.py", line 24, in auto_format_cell_width
ws.set_column('B:C', 20)
AttributeError: 'Worksheet' object has no attribute 'set_column'
Here's my ridiculous import. Config is some constants, controller has some helper functions.
from smartystreets_python_sdk import StaticCredentials, exceptions, Batch, ClientBuilder
from smartystreets_python_sdk.us_street import Lookup as StreetLookup
from pathlib import Path
import pandas as pd
import numpy as np
import config
from controller import getExcel, clean
The func in question:
def format_col_width(ws):
ws.set_column('B:C', 20)
ws.set_column('D', 1)
ws.set_column('E', 20)
Where the ws being passed comes from:
df1 = df.replace(np.nan, '', regex=True)
print(df1)
df1.to_excel(writer, sheet, index = False, engine='xlsxwriter')
worksheet = writer.sheets[sheet]
format_col_width(worksheet)
Did I forget to import something? Xlsxwriter is installed.

The reason it gives: AttributeError: 'Worksheet' object has no attribute 'write'
This is because you have not installed xlsxwriter on your PC.
you can use:
pip install xlsxwriter
and it will work isa.

I had the same problem, the following worked for me:
def format_col_width(ws):
ws.column_dimensions['B'].width = 20
ws.column_dimensions['C'].width = 20
ws.column_dimensions['D'].width = 1
ws.column_dimensions['E'].width = 20

There is an error in the single column ranges. They should be D:D instead of D since the method needs a start and end column even if they are the same.
With that modification the code should work:
import pandas as pd
def format_col_width(ws):
ws.set_column('B:C', 20)
ws.set_column('D:D', 1)
ws.set_column('E:E', 20)
df = pd.DataFrame({'Data1': [10, 20, 30, 20, 15, 30, 45]})
writer = pd.ExcelWriter('pandas_test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
workbook = writer.book
worksheet = writer.sheets['Sheet1']
format_col_width(worksheet)
writer.save()
Output:
Try the above code and see if it works. If it doesn't then XlsxWriter may not be installed and Pandas is defaulting to OpenPyXL.

Related

'Worksheet' object has no attribute 'cell'

I need to open an xlsx document and color it. But I don't understand why it shows cell error it. My algorithm works like this:
Open xlsx, writer = pd.ExcelWriter(path, engine='xlsxwriter')
worksheet = writer.sheets['Sheet1']
col_style = Font(name = "Reem Kufi", size = 12, color = "DB3B22", italic =True)
for i in range(2,40):
worksheet.cell(row = i, column = 3).font = col_style
Error:- 'Worksheet' object has no attribute 'cell'
you will need to use Openpyxl's loadworkbook instead of ExcelWriter to achieve what you are looking for. Updated code here. Note that I have only changed the initial open file and sheet using the new code and required libraries and not changed rest of your code.
from openpyxl.styles import Font
from openpyxl import load_workbook
writer = load_workbook(filename='YourFile.xlsx')
worksheet = writer['Sheet1']
col_style = Font(name = "Reem Kufi", size = 12, color = "DB3B22", italic =True)
for i in range(2,40):
worksheet.cell(row = i, column = 3).font = col_style
writer.save('YourFile.xlsx')

Python Error: AttributeError: 'NoneType' object has no attribute 'to_excel'

I am trying to combine all files in a directory and the save the combined file into another directory.
I am using Python 3.8.
When I run the code I get the following with a AttributeError:
c:\test\Upload test\Book1.xlsx
c:\test\Upload test\Book2.xlsx
c:\test\Upload test\Book3.xlsx
Traceback (most recent call last):
File "C:/Python/PythonDev/combine.py", line 104, in <module>
newdf.to_excel(writer,"All")
AttributeError: 'NoneType' object has no attribute 'to_excel'
the code:
import pandas as pd
import globe
filelist = glob.glob(r'c:\test\Upload test\*.xlsx')
file1 = "*.*"
for i in filelist:
file2 = pd.read_excel(i)
file2['FileName'] = i
file1 = ['newdf']
newdf = file1.append(file2)
print (i)
writer = pd.ExcelWriter(r'c:\test\Uploaded\uploadfile.xlsx', engine= 'xlsxwriter')
newdf.to_excel(writer,"All")
writer.save()
Append doesn't return anything...
Try something like this:
import pandas as pd
import glob
raw_files = glob.glob(r'c:\test\Upload test\*.xlsx')
pd_files = pd.DataFrame()
for file in raw_files:
pd_files.append(pd.read_excel(file))
pd_files.to_excel("c:\test\Uploaded\uploadfile.xlsx")

How to convert txt to excel file

I have a txt file looks like this:
Cellname;Ncellname;Technology
52822;13621;GSM;
52822;13622;GSM;
52822;13623;GSM;
52822;16322;UMTS;
52822;16323;UMTS;
52822;16324;UMTS;
52822;16361;UMTS;
52822;16362;UMTS;
52822;16363;UMTS;
I tried to convert it using the below code:
import pandas as pd
import os
excel = 'gsmrelation_mnm.txt'
df = pd.read_csv(os.path.join(os.path.dirname(__file__), excel))
df.to_excel('gsmrelation_mnm.xlsx', 'Sheet1')
but I found this error:
Traceback (most recent call last):
File "C:/Users/haroo501/PycharmProjects/MyLiveRobo/convert_txt_csv.py", line 8, in <module>
df.to_excel('gsmrelation_mnm.xlsx', 'Sheet1')
File "C:\Users\haroo501\PycharmProjects\MyLiveRobo\venv\lib\site-packages\pandas\core\generic.py", line 2250, in to_excel
formatter.write(
File "C:\Users\haroo501\PycharmProjects\MyLiveRobo\venv\lib\site-packages\pandas\io\formats\excel.py", line 730, in write
writer = ExcelWriter(_stringify_path(writer), engine=engine)
File "C:\Users\haroo501\PycharmProjects\MyLiveRobo\venv\lib\site-packages\pandas\io\excel\_openpyxl.py", line 19, in __init__
from openpyxl.workbook import Workbook
ModuleNotFoundError: No module named 'openpyxl'
enter image description here
How to solve this problem
Try this:
import pandas as pd
excel = 'test.txt'
df = pd.read_csv(excel,sep=';')
column_indexes = list(df.columns)
df.reset_index(inplace=True)
df.drop(columns=df.columns[-1], inplace=True)
column_indexes = dict(zip(list(df.columns),column_indexes))
df.rename(columns=column_indexes, inplace=True)
df
and then
df.to_excel('output.xlsx', 'Sheet1')
and in case you don't want the indexes in the output sheet, use this
df.to_excel('output.xlsx', 'Sheet1', index=False)
import pandas as pd
file = pd.read_csv('input.txt', sep=';', index=False)
file.to_excel('output.xlsx', 'Sheet1')
I tried following,
finally what you expected
import pandas as pd
df = pd.read_csv('gsmrelation_mnm.txt', sep = ';', header=None, names=['Cellname', 'Ncellname', 'Technology'])
df.to_excel('gsmrelation_mnm.xlsx', 'Sheet1', index=False, header=None)

insert text file into existing xlsx using Python

I have a .xlsx file with 11 worksheets and I need to insert the contents of a text file (tab delim, roughly 30 columns with 100 rows) from Row 3 onwards. I tried the code below but I end up with errors. (using bash/Linux)
#!/usr/bin/env python
import csv
from openpyxl.reader.excel import load_workbook
from xlrd import open_workbook
from xlutils import copy as xl_copy
with open('S12_final.txt') as tab_file: #open tab text file
tab_reader = csv.reader(tab_file, delimiter='\t')
xls_readable_book = load_workbook('S12.xlsx') #load workbook
xls_writeable_book = xl_copy.copy(xls_readable_book)
xls_writeable_sheet = xls_writeable_book.get_sheet_by_name('Filtered') #write data on this sheet
for row_index, row in enumerate(tab_reader):
xls_writeable_sheet.write(row_index, 0, row[0])
xls_writeable_sheet.write(row_index, 1, row[1])
xls_writeable_book.save('S12.xlsx') #save excel file
Errors:
> Traceback (most recent call last): File "./tab2excel_a.py", line 23,
> in <module>
> xls_writeable_book = xl_copy.copy(xls_readable_book) File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/copy.py",
> line 19, in copy
> w File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 937, in process
> reader(chain[0]) File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 61, in __call__
> filter.workbook(workbook,filename) File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py",
> line 287, in workbook
> self.wtbook.dates_1904 = rdbook.datemode AttributeError: 'Workbook' object has no attribute 'datemode'
Any suggestions ?
It seems (and by no means I'm knowledgeable about those particular libraries) that you are attempting to input an openpyxl object into an xlutils method in these lines:
xls_readable_book = load_workbook('S12.xlsx') #load workbook
xls_writeable_book = xl_copy.copy(xls_readable_book)
So the interpreter complains that this "unknown" object has no attribute datemode. As so try using xlrd open_workbook method since it seems to return a Book object which, according to the documentation, is fully compatible with xlrd.copy methods:
xls_readable_book = open_workbook('S12.xlsx') #load workbook
xls_writeable_book = xl_copy.copy(xls_readable_book)
Consider this openpyxl example:
from openpyxl.workbook.workbook import Workbook # as _Workbook
import csv
wb = Workbook()
wb.create_sheet('Filtered')
ws = wb['Filtered']
with open('test/S12_final.csv') as tab_file:
tab_reader = csv.reader(tab_file, delimiter='\t')
# Skipt first 2 Lines
[next(tab_reader) for skip in range(2)]
# Append list(rowData) after Sheets last accessed Row
for rowData in tab_reader:
ws.append(rowData)
wb.save('test/S12.xlsx')
Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2

Pandas `to_excel` set font name

Is it possible to set the font name with pandas' excel writer?
Here is my attempt:
import pandas as pd
from pandas.io.excel import ExcelWriter
df = pd.DataFrame([[1,2,3],[4,5,6]])
writer = ExcelWriter("test.xlsx")
writer.set_font_name("Arial") # this would be ideal, but no such method exists
format = writer.book.add_format({"font_name": "Arial"})
df.to_excel(writer) # format is not applied. Need to pass `format` object somewhere
writer.close()
Where can I pass the xlsxwriter.format.Format object once it has been created?
UPDATE: using a solution similar to #miradulo's solution we can make it working for different versions of Pandas:
try:
import pandas.io.formats.excel as fmt_xl # version >= 0.20
except ImportError:
try:
import pandas.formats.format as fmt_xl # 0.18 <= version < 0.20
except ImportError:
import pandas.core.format as fmt_xl # version < 0.18
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=list('abc'))
fmt_xl.header_style = None
writer = pd.ExcelWriter("d:/temp/test.xlsx")
df.to_excel(writer, index= False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']
fmt = writer.book.add_format({"font_name": "Arial"})
worksheet.set_column('A:Z', None, fmt)
worksheet.set_row(0, None, fmt)
writer.save()
XlsxWriter Docs: Working with Python Pandas and XlsxWriter

Categories

Resources