I am very new to Python world. Pardon for any inane mistake(s).
What program is trying to do?
I just wrote a piece of code which reads the data from an existing excel and printing a selected cell value.
Problem?
Problem is IDE is not showing all the suggestion like when control loaded the sheet (of type Worksheet) the object name "sheet" does not show methods available in sheet object.
Code
import pandas as pd
from openpyxl import load_workbook
test_f_path = '/Users/new_python_user/_Codes/_Personal/test_resources/Test_Update.xlsx'
sheet_name = 'Eight'
workbook = load_workbook(test_f_path)
sheet = workbook[sheet_name]
print(sheet.cell(1, 1).value) # <--- Here is problem: typing "sheet." does not provide suggestions
Pycharm Version
Pycharm Community 2019.3.3 for MAC
EDIT-1
Modified the program to cast the object then it worked. But this is not the way i thought about Python. May be i am missing something. Pls advice.
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet # <--Imported here
test_f_path = '/Users/i852841/_Codes/_Personal/PyStockCrawler/test_resources/Test_Update.xlsx'
sheet_name = 'Eight'
workbook = load_workbook(test_f_path)
sheet = workbook[sheet_name]
sheet_casted = Worksheet(sheet) #<-- Cast here
Related
I have used openpyxl for outputting values in Excel in my Python code. However, now I find myself in a situation where the cell locations in excel file may change based on the user. To avoid any problems with the program, I want to name the cells where the code can save the output to. Is there any way to have Python interact with named ranges in Excel?
For a workbook level defined name
import openpyxl
wb = openpyxl.load_workbook("c:/tmp/SO/namerange.xlsx")
ws = wb["Sheet1"]
mycell = wb.defined_names['mycell']
for title, coord in mycell.destinations:
ws = wb[title]
ws[coord] = "Update"
wb.save('updated.xlsx')
print("{} {} updated".format(ws,coord))
I was able to find the parameters of the named range using defined_names. After that I just worked like it was a normal Excel cell.
from openpyxl import load_workbook
openWB=load_workbook('test.xlsx')
rangeDestination = openWB.defined_names['testCell']
print(rangeDestination)
sheetName=str(rangeDestination.attr_text).split('!')[0]
cellName = str(rangeDestination.attr_text).split('!')[1]
sheetToWrite=openWB[sheetName]
cellToWrite=sheetToWrite[cellName]
sheetToWrite[cellName]='TEST-A3'
print(sheetName)
print(cellName)
openWB.save('test.xlsx')
openWB.close()
I am fairly new to python and working my way through the openpyxl package within python and I am unable to get the delete_rows function to work? It is saying that the function "delete rows" isnt within workbook?
My code is below:
from openpyxl import Workbook
from openpyxl import load_workbook
data = 'DATA PATH'
wb = load_workbook(filename=data)
sheet1 = wb['Sheet1']
sheet1.delete_rows(idx=3, amount = 5)
wb.save(filename="TEST.xlsx")
Any advice would be great and if anymore info behind the question is required just let me know.
Thanks!
(Code has been updated)
I have to write some data into existing xls file.(i should say that im working on unix and couldnt use windows)
I prefer work with python and have tried some libraries like xlwt, openpyxl, xlutils.
Its not working, cause there is some filter in my xls file. After rewriting this file filter is dissapearing. But i still need this filter.
Could some one tell me about options that i have.
help, please!
Example:
from xlutils.copy import copy
from xlrd import open_workbook
from xlwt import easyxf
start_row=0
rb=open_workbook('file.xls')
r_sheet=rb.sheet_by_index(1)
wb=copy(rb)
w_sheet=wb.get_sheet(1)
for row_index in range(start_row, r_sheet.nrows):
row=r_sheet.row_values(row_index)
call_index=0
for c_el in row:
value=r_sheet.cell(row_index, call_index).value
w_sheet.write(row_index, call_index, value)
call_index+=1
wb.save('file.out.xls');
I also tried:
import xlrd
from openpyxl import Workbook
import unicodedata
rb=xlrd.open_workbook('file.xls')
sheet=rb.sheet_by_index(0)
wb=Workbook()
ws1=wb.create_sheet("Results", 0)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws1.append(arr)
ws2=wb.create_sheet("Common", 1)
sheet=rb.sheet_by_index(1)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws2.append(arr)
ws2.auto_filter.ref=["A1:A15", "B1:B15"]
#ws['A1']=42
#ws.append([1,2,3])
wb.save('sample.xls')
The problem is still exist. Ok, ill try to find machine running on windows, but i have to admit something else:
There is some rows like this:
enter image description here
Ive understood what i was doing wrong, but i still need help.
First of all, i have one sheet that contains some values
Second sheet contains summary table!!!
If i try to copy this worksheet it did wrong.
So, the question is : how could i make summary table from first sheet?
Suppose your existing excel file has two columns (date and number).
This is how you will append additional rows using openpyxl.
import openpyxl
import datetime
wb = openpyxl.load_workbook('existing_data_file.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
a = sheet.get_highest_row()
sheet.cell(row=a,column=0).value=datetime.date.today()
sheet.cell(row=a,column=1).value=30378
wb.save('existing_data_file.xlsx')
If you are on Windows, I would suggest you take a look at using the win32com.client approach. This allows you to interact with your spreadsheet using Excel itself. This will ensure that any existing filters, images, tables, macros etc should be preserved.
The following example opens an XLS file adds one entry and saves the whole workbook as a different XLS formatted file:
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'input.xls')
ws = wb.Worksheets(1)
# Write a value at A1
ws.Range("A1").Value = "Hello World"
excel.DisplayAlerts = False # Allow file overwrite
wb.SaveAs(r'sample.xls', FileFormat=56)
excel.Application.Quit()
Note, make sure you add full paths to your input and output files.
I want to get a Excel's sheet with Python. I can do this with the sheet's name but I want get it with its Code Name property. The following is a code using the sheet's name:
from openpyxl import load_workbook
wb_donnees = load_workbook("Données.xlsm", read_only = True)
name_ws_1 = wb_donnees.get_sheet_name()[0]
ws_1 = wb_donnees[name_ws_1]
But I want get the sheet with its Code Name property. Is it possible ?
Charlie Clark's answer works for me in read mode.
I'm not sure whether OP needed this, but when writing a new workbook, you cannot get the codename this way. Instead, you will need to specify it yourself, otherwise the function returns None, and sheets will only be codenamed 'Sheet1' etc at workbook creation.
wb = load_workbook('input.xlsm')
wsx = wb.create_sheet('New Worksheet')
wsx.sheet_properties.codeName = 'wsx'
wb.save('output.xlsm')
The following should will only work if the file is not opened in read-only mode:
from openpyxl import load_workbook
wb = load_workbook("Données.xlsm")
for n in wb.sheetnames:
ws = wb[n]
print(n, ws.sheet_properties.codeName)
Let me preface this by saying I have tried looking for, and cannot seem to find a similar situation so please don't be too upset if this seems familiar to you. I am using Python 2.7 and openpyxl version 2.2.5 (I need to use 2.7, and used an older module for other reasons.)
I am new to Python and read/write code in general, so I'm testing this on the command line before I implement it:
I created a file, foo.xlsx in the Python27 file directory with some values that I manually entered via Excel.
I then used this simple code on the Python command line to test my code
from openpyxl import load_workbook
wb = load_workbook('foo.xlsx')
sheet_ranges = wb['range names']
It then resulted in the following error:
File "C:\Python27\lib\openpyxl\workbook.workbook.py", line 233 in getitem
raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: 'Worksheet sheet range names does not exist'
So I thought it had something to do with not importing the entire openpyxl module. I proceeded to do that and run the whole process but it resulted in the same error.
Can someone please let me know what I am doing wrong/how to solve this?
Additional information:
I had successfully written to an empty file before, and then read the values. This gave me the right values for everything EXCEPT what I had written in manually via Excel- the cells that had manual input returned None or Nonetype. The issue seems to be with cells with manual input.
I did hit save on the file before accessing it don't worry
This was in the same directory so I know that it wasn't a matter of location.
The following command does not make sense:
sheet_ranges = wb['range names']
Normally you open a workbook and then access one of the worksheets, the following gives you some examples on how this can be done:
import openpyxl
wb = openpyxl.Workbook()
wb = openpyxl.load_workbook(filename = 'input.xlsx')
# To display all of the available worksheet names
sheets = wb.sheetnames
print sheets
# To work with the first sheet (by name)
ws = wb[sheets[0]]
print ws['A1'].value
# To work with the active sheet
ws = wb.active
print ws['A1'].value
# To work with the active sheet (alternative method)
ws = wb.get_active_sheet()
print ws['A1'].value
If you want to display any named range in the workbook, you can do the following:
print wb.get_named_ranges()
I'm not exactly sure what it is you need to do, but to read Excel spreadsheets into python, I usually use xlrd (which to me was easier to get use to). See example:
import xlrd
workbook = xlrd.open_workbook(in_fname)
worksheet = workbook.sheet_by_index(0)
To write to Excel spreadsheets, I use xlsxwriter:
import xlsxwriter
workbook = xlsxwriter.Workbook(out_fname)
worksheet = workbook.add_worksheet('spreadsheet_name')
Hope this helps.