AttributeError: 'workbook' object has no attribute 'max_row' - python

I already referred this post here but it has no response.
Am using a public github package here to copy all the formatting from one excel file to another excel file.
By formatting, I mean the color, font, freeze panes etc.
style_sheet = load_workbook(filename = 'sty1.xlsx')
data_sheet = load_workbook(filename = 'dat1.xlsx')
copy_styles(style_sheet, data_sheet) # the error happens in this line
The error producing line within copy_styles function is given below
def copy_styles(style_sheet, data_sheet):
max_matched_row = min(style_sheet.max_row, data_sheet.max_row)
max_matched_col = min(style_sheet.max_column, data_sheet.max_column)
The full copy_styles function can be found in this github link here
The error that I encounter is given below
AttributeError: 'workbook' object has no attribute 'max_row'
If you want a sample file to test, it can be found in this github issue here

Assuming you want to copy the style of the first sheet in the workbook, you should do:
copy_styles(style_sheet.sheet_by_index(0), data_sheet.sheet_by_index(0))
If you want to copy the style of all worksheets (assuming that they match), just loop over them:
style_wb = open_workbook(filename = 'sty1.xlsx')
data_wb = open_workbook(filename = 'dat1.xlsx')
for sheet_from, sheet_to in zip(style_wb.sheets(), data_wb.sheets()):
copy_styles(sheet_from, sheet_to)
I changed the variable names on the second example to make it clear that they are workbooks, not sheets.

Related

Create Function to write dataframe to google sheets with df.to_numpy()

I have a piece of python code in which I create multiple data frames, which I want to write to my google drive.
I have defined the following functions
def write_to_google(FileName,dFrame):
worksheet = gc.open(FileName).sheet1
wb = gc.open(FileName)
wsResults = wb.worksheet('Sheet1')
print("untill here the function seems to operate")
data = dFrame.to_numpy().tolist() #here I get an error
headers = dFrame.columns.tolist()
Data2Write = [headers] + data
wsResults.update("A1",Data2Write)
dFrame is the name of the dataframe I want to write to the FileName (which is an existing file)
I get the following error on the `data = dFrame.to_numpy().tolist()
AttributeError: 'str' object has no attribute 'to_numpy'
How do I get the .to_numpy part to work with the dFrame argument?`
tried google but can find anything on the .to_numpy in the context of an argument

how to fix TypeError: 'NoneType' object does not support item assignment

Error
File "", line 22, in sheet['D3'] = '= SUM(G3:AZ3)'
TypeError: 'NoneType' object does not support item assignment
I tried several methods but none worked
my code
import openpyxl module
import openpyxl
sb="lists.xls"
wb = openpyxl.Workbook(sb)
sheet = wb.active
sheet['D3'] = '= SUM(G3:AZ3)'
wb.save(sb)
I expect the code to run without error.
Your sheet seems to be None. Are you looking to open a file and not write one? Perhaps this might help you:
import openpyxl
from openpyxl import load_workbook
sb="lists.xls"
wb = load_workbook(sb)
sheet = wb.active
sheet['D3'] = '= SUM(G3:AZ3)'
wb.save(sb)
Also: Note that openpyxl does not support the .xls format. It will not be able to process your file unless you convert it to a format that openpyxl can support.
TypeError is mostly because of mixing different types of data! For example, trying to do addition on integers with strings! According to code, the sheet may be a list and you are trying to add key and value to a dictionary! Try to check if you are accessing a dictionary rather than a list!
This might help you:
# Declare a dictionary
sheet = {}
# now you can add data to that dictionary
sheet['D3'] = '= SUM(G3:AZ3)'

getting the error; attributeerror: 'Worksheet' object has no attribute 'delete_rows' openpyxl

i'm writing code for a too to perform GIS functions to an input of an excel sheet. sometimes the excel sheet will come in and have 2 separate rows across the top for its attributes fields, and when there is 2, I need to delete the top row. the value of cell A1 will be naming if I need to do this
I tried writing code to check this and delete it as below;
openpyxl
import arcpy, os, sys, csv, openpyxl
from arcpy import env
env.workspace = r"C:\Users\myname\Desktop\Yanko's tool"
arcpy.env.overwriteOutput = True
excel = r"C:\Users\myname\Desktop\Yanko's tool\Yanko's Duplicate tool\Construction_table_Example.xlsx"
layer = r"C:\Users\myname\Desktop\Yanko's tool\Yanko's Duplicate tool\Example_Polygons.shp"
output = r"C:\Users\myname\Desktop\Yanko's tool\\Yanko's Duplicate tool"
book = openpyxl.load_workbook(excel)
book.get_sheet_by_name("Construction Table format")
if ws.cell(row=1, column=1).value == "Naming":
ws.delete_rows(1, 1)
book.save
book.close
it should just delete the first row if the if function passes true, but I get the error;
Warning
(from warnings module):
File "C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\openpyxl\reader\worksheet.py", line 310
warn(msg)
UserWarning: Data Validation extension is not supported and will be removed
Traceback (most recent call last):
File "C:\Users\ronan.corrigan\Desktop\Yanko's tool\Yanko's Duplicate tool\Yanko's Tool.py", line 31, in <module>
ws.delete_rows(1, 1)
AttributeError: 'Worksheet' object has no attribute 'delete_rows'
any help in figuring out what I've done wrong would be greatly appreciated
thanks
First of all, according to the docs, the get_sheet_by_name function is deprecated, and you should just be using the sheet name to get the function:
book["Construction Table format"]
Another thing to note, in your code I don't see you setting that ws value, which should be set to whatever sheet object is returned. If you're setting it somewhere else, so it may be possible that you are using a different sheet object which doesn't have that function
ws=book["Construction Table format"]
Other than that you'd have to share the stack trace to give a better understanding of what's breaking

How to split Excel screen with Openpyxl?

I've been trying to use Openpyxl to split the Excel screen vertically (in Excel the Split button in the View tab on the ribbon). I haven't found any guide, how to do this. But I have found this web page (https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.views.html) and I think the "ySplit" property may be the solution. Unfortunately I haven't been able to figure out how to use it properly. I've tried the following code:
wb = openpyxl.load_workbook('file.xlsx')
sh = wb.active
sh.sheet_view.pane.ySplit = 20
EDIT: But this code does not work: AttributeError: 'NoneType' object has no
attribute 'ySplit'.
I've also tried some variations of the code above (with ySplit). But without success. If anybody could help me to find a way, how to split the screen, it would be much appreciated.
Thanks in advance.
EDIT2: The solution was provided by stovfl in comments. The code
should be:
sh.sheet_view.pane = openpyxl.worksheet.views.Pane(xSplit=20.0, ySplit=None, topLeftCell='C1', activePane='topLeft', state='split')
Question How to split Excel screen with Openpyxl?
To define, to show a Worksheet splitted, you have to create a openpyxl.worksheet.views.Pane object and assign it to myWorksheet.sheet_view.pane.
from openpyxl.worksheet.views import Pane
wb = openpyxl.load_workbook('file.xlsx')
ws = wb.active
ws.sheet_view.pane = Pane(xSplit=20.0, ySplit=None,
topLeftCell='C1', activePane='topLeft', state='split')
wb.save('file.xlsx')
openPyXL - worksheet.views.Pane
class openpyxl.worksheet.views.Pane(xSplit=None, ySplit=None,
topLeftCell=None,
activePane='topLeft', state='split')[source]
activePane
Value must be one of {‘topLeft’, ‘bottomRight’, ‘topRight’, ‘bottomLeft’}
state
Value must be one of {‘split’, ‘frozen’, ‘frozenSplit’}
topLeftCell
Values must be of type <class ‘str’>
xSplit
Values must be of type <class ‘float’>
ySplit
Values must be of type <class ‘float’>

How can I Bold only part of a string in an Excel cell with Python?

I'm using win32com to fill out an Excel spreadsheet with some analytic information. I have a cell that I want to be in this form:
This is the problem description: this is the command you run to fix it
I can't seem to figure out how to get the text into the cell with Python with mixed formatting.
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Add()
ws = wb.Worksheets("Sheet1")
excel.Visible=True
sel = excel.Selection
sel.Value = "this is the command you run to fix it"
sel.Font.Bold = True
ws.Cells(1,1).Value = 'This is the problem description' + sel.Value #makes the whole cell bold
ws.Cells(1,1).Value = "{} {}".format("this is the problem desc",sel) #makes the whole cell bold
The selection object has a Characters attribute, but I can't find any documentation on what it does.
Per #ron-rosenfield, the VBA code to pull this off looks like:
Range("A1").Characters(2,5).Font.Bold = true
And similarly, there is a Characters object attribute of the excel WorkSheet's Range
>>> ws.Range("A1").Characters
<win32com.gen_py.Microsoft Excel 14.0 Object Library.Characters 967192>
HOWEVER, the method you need to access a range with that object is GetCharacters(start, length) (index starts at 1 as per usual with the excel com methods)
ws.Range("A1").GetCharacters(2,4).Font.Bold = True
You can use this command to update the boldness of characters in a cell after the fact.
Although you are looking for a win32com solution in the body of your question I'll point out for anyone who gets here via the title that this is also possible in Python with XlsxWriter.
Example:

Categories