Openpyxl: 'Worksheet' object has no attribute 'values' - python

My goal is to read in an excel file and view the codes in a pandas dataframe (i.e. '= A3') rather than the resulting values from excel executing the codes, which is the pandas default if read in using pandas.
My goal was described here: How can I see the formulas of an excel spreadsheet in pandas / python?
Openpyxl is supposed to support this, but I can't get the import to function correctly. Anyone spot the error?
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
df = pd.DataFrame()
wb = load_workbook(filename = 'name.xlsx')
sheet_names = wb.get_sheet_names()
name = sheet_names[0]
sheet_ranges = wb[name]
df = pd.DataFrame(sheet_ranges.values)
> AttributeError: 'Worksheet' object has no attribute 'values'
(Note: the exact implementation of the answer at the linked question yields KeyError: 'Worksheet range names does not exist.' My code above resolved this, but then gets stuck as described.)

Check your version of openpyxl, It seems you have an older version.
openpyxl 2.4.2
import openpyxl
print(openpyxl.__version__)
Values property for worksheets were added only from 2.4.0-a1 (2016-04-11)

Related

OPENPYXL get_column_letter not working with exported PANDAS dataframe - any help? :)

I am taking data from a workbook using PANDAS and then exporting it into a new workbook. This is working as expected. When I create a table using OPENPYXL I usually use the following code:
table = Table(displayName="Table2", ref="B1:"+ get_column_letter(data_sheet.max_column) + str(data_sheet.max_row))
However this isn't working as my get_column_letter & row is returning 0. Here’s how I'm writing to excel:
pd.to_excel(destination_file_name,sheet_name="Sheet3")
Am I doing something wrong while writing to excel??

Can't export dataframes and other objects to Excel using pandas?

I am trying to export multiple dataframes to a single spreadsheet in excel from Pandas.
I keep getting the error:
'numpy.int64' object has no attribute 'to_excel'
despite never importing numpy. Here is my code:
import datetime
import pandas as pd
import warnings
import xlwings as xw
... dataframe calculations ...
# Export to Excel
writer = pd.ExcelWriter('C:/users/test.xlsx', engine='xlsxwriter')
workbook = writer.book
worksheet = workbook.add_worksheet('PythonCalculations')
writer.sheets['PythonCalculations'] = worksheet
myNumber.to_excel(writer,sheet_name='PythonCalculations',startrow = 0 , startcol=0)
df1.to_excel(writer,sheet_name='PythonCalculations',startrow = 2, startcol = 0)
Where, for example, myNumber = 100. Type is numpy.int64. whenever I try to execute that line with myNumber in it, it keeps returning the error 'numpy.int64' object has no attribute 'to_excel'.
When I try to execute the line with df1, it manages to execute, however no excel file is created. Even when I created the excel file and ran the lines, it didn't populate. How do I fix this?
I also wonder why you don't just use xlwings. First make sure to take a look at the xlwings docs, https://docs.xlwings.org/en/stable/quickstart.html . Once you are able to connect you should be able to do something as simple as the below code. I'm not adding a worksheet, I'm using an existing worksheet.
wb = xw.Book('my_workbook.xlsm')
sht = wb.sheets['a_sheet_that_already_exists']
rng1 = sht.range('A1') # Ambiguous cell.
rng2 = sht.range('J2') # Ambiguous cell with enough room for df1.
# Your dataframe collections are df1 and df2.
# Showing .options in case you care.
rng1.options(index=True, header=True).value = df1
rng2.options(index=True, header=True).value = df2

python openpyxl get sheet names

I am starting on a code that loads and edits excel (the version I am using is office 2017) sheet using openpyxl. Right now I am still trying to wrap my head around how this module works, here's the code
import openpyxl
from openpyxl import load_workbook
from openpyxl import workbook
from openpyxl.compat import range
from openpyxl.utils import get_column_letter
import os
os.chdir("D:\Scripts\Python\Testing Scripts\My Excel Folder")
wb = load_workbook("MyExcel.xlsx")
names = wb.sheetnames()
print(names)
print(type(wb))
and the error I receive is,
TypeError: 'list' object is not callable
For the string of code
names = wb.sheetnames()
wb.get_sheet_names() returns the list of all the sheets in that excel workbook.
print (wb.get_sheet_names())
for the latest openpyxl to avoid warning:
print (wb.sheetnames)
if you want to access a particular sheet
ws = wb.get_sheet_by_name(name = 'Sheet 1')
Use: wb.sheetnames
Example -
names = wb.sheetnames
print(names)
Do not use: get_sheet_names()
If you will use this, you will get this Warning.
DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).

What does this mean? DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname])

I've import a xlsx sheet into Python 3.6 by using import openpyxl and now am trying to access the Cell Object by doing the following (see below), but I immediately get an error message which I don't know what it means?:
Warning (from warnings module):
File "__main__", line 1
DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
Here is my code:
import openpyxl
wb = openpyxl.load_workbook('c:\\users\\user1\\AppData\\Local\\Programs\\Python\\Python36-32\\example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
Rather than what you're doing, it's telling you to use a different format
wb['Sheet1']
If you plan on using your script in the future, when that library is upgraded, it may break because you're using deprecated functions
the right code :
import openpyxl
wb = openpyxl.load_workbook('c:\users\user1\AppData\Local\Programs\Python\Python36-32\example.xlsx')
sheet = wb['Sheet1']
If you don't anticipate to know beforehand what the sheetname is, then your code should be:
sheet = wb[wb.sheetnames[0]]
...which will automatically choose the left most sheet in the workbook
Furthermore, it is important to note that wb[0] produces a string object...
>>> wb.sheetnames[0]
'Sheet1'
and wb[wb.sheetnames[0]] produces a 'openpyxl.worksheet.worksheet.Worksheet' object...
>>> wb[wb.sheetnames[0]]
<Worksheet "Sheet1">
>>> type(wb[wb.sheetnames[0]])
<class 'openpyxl.worksheet.worksheet.Worksheet'>
This is important on how you plan to work with this object (e.g. iterating over your worksheet).
Please try below code, hope it will help:
import openpyxl
wb = openpyxl.load_workbook('c:\\users\\user1\\AppData\\Local\\Programs\\Python\\Python36-32\\example.xlsx')
sheet = wb['Sheet1']

xlwings writing to range on specific sheet

I have been trying to write some lists to a certain sheet on a workbook but am having no luck. My code is:
import xlwings as xw
from xlwings import Range
from xlwings import Book
wkb = xw.Book('Master_v3.xlsm')
sht = wkb.sheets['Control']
sht.Range('A1').value = some_list
This gives me the error:
*** AttributeError: 'Sheet' object has no attribute 'Range'
When I use "0" instead of specifying the sheet name (i.e. "Control") this seems to work. Where am I going wrong here?
Thanks
xw.Range is a shortcut for the Range on the active sheet of the active book of the active app.
When you fully qualify like you do, then range is an attribute of the sheet object, which follows the Python naming conventions of lower case for attributes:
sht.range('A1').value = some_list
I.e. mind xlwings.Range vs. mysheet.range.
Try this solution:
import xlwings
wb = xlwings.Book(r"filename")
wb.sheets['Sheet1'].range((5,1),(195,13)).value = ...

Categories

Resources