Openpyxl: Worksheet has no object delete rows error - python

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)

Related

IDE does not suggest methods available on the selected object

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

python - adding rows to an existing worksheet table

I'm working with the .xlsx file and it has a tab with a workhsheet table where lots of conditional formatting are used. From time to time I need to append this table with new rows.
My plan is to use python openpyxl (or other package) to append this table.
so far I could identify this table as
from openpyxl import load_workbook
wb=load_workbood(myfile)
ws=wb['mytab']
tab = wb.ws._tables[0]
Can I use something like .append() method or change data of this table to add more rows to it?
My goal is to keep the formatting.
I've already tried this approach -
Manipulate existing excel table using openpyxl and it doesn't' work for me
I'm using openpyxl 2.6.1
Regards,
Pavel
from openpyxl import load_workbook
filename= r'C:\Users\PC/test.xlsx'
wb = load_workbook(filename)
ws = wb['Hoja1']
ws["A1"] = "AAA"
ws["A2"] = "BBB"
wb.save(filename)
from openpyxl import load_workbook
wb=load_workbood(myfile)
ws=wb['mytab']
tab = ws.tables["Table1"]
tab.ref = f"A1:{ws.max_column}{ws.max_row}"

How to get the value from merged cells in xlsx file using python?

I am trying to get the value from cell with row = 11 and column B and C. See screenshot for more clarification.
I tried following code using xlrd package but it does not print anything.
import xlrd
path = "C:/myfilepath/data.xlsx"
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
sheet.cell_value(10,1)
sheet.cell_value(10,2)
I am not able to output the value from particular merged cells using xlrd package in python.
Above code should print the cell value i.e PCHGFT001KS
I don't know how xlrd works, but I do know how the lovely openpyxl works. You should use openpyxl! it's a robust tool for working with xlsx files. (NOT xls).
import openpyxl
wb = openpyxl.load_workbook(excel)
ws = wb[wb.get_sheet_names()[0]]
print(ws['B11'].value)
Extra:
If you want to unmerge those blocks you can do the following.
for items in ws.merged_cell_ranges:
ws.unmerge_cells(str(items))
wb.save(excel)

openpyxl: remove_sheet causes IndexError: list index out of range error on saving sheet

I am trying to use openpyxl to:
Open an Excel (2016) workbook which contains 3 worksheets (Sheet1,Sheet2,Sheet3)
Remove a worksheet (Sheet2)
Save the workbook to a different workbook minus Sheet2
from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb.save("c:/Users/me/book2.xlsx")
The wb.save will generate an IndexError: list index out of range error and produce a corrupted book2.xlsx file which Excel cannot open.
I run into similar problem, only with xlwt library. Regardless, the cause is the same, You remove the sheet which is set as active sheet. So, to fix this, before saving workbook, set some other sheet as active. In openpyxl, it would be something like this:
from openpyxl import load_workbook
wb = load_workbook("c:/Users/me/book1.xlsx")
ws = wb.get_sheet_by_name('Sheet2')
wb.remove_sheet(ws)
wb._active_sheet_index = 0
wb.save("c:/Users/me/book2.xlsx")
I must mention that this is not very good programming practice, but there is no method to set active sheet, only to get one.
EDIT: Just found out that this repo was moved to bitbucket, and found that it has method for setting active sheet. Just use:
wb.active = 0

"Worksheet range names does not exist" KeyError in openpyxl

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.

Categories