How to write to same excel file after the operation with sheet name - pandas

I have excel file name 'excel.xlsx'. it is having 10 sheets with different name. I am able to save but all other sheets are missing
After the Operation I need to save the sheet on the same excel starting from 5th row and 5th column
The new sheet name is 'Final'
My dataframe name is df
writer = pd.ExcelWriter('excel.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Final', startrow=5,startcol=5,index=False)
writer.save()

Did you tried to add a writer.save() before your df.to_excel(...)?

Will be easier - Try using openpyxl engine.
Prerequisite: openpyxl - Install it with command -
pip install openpyxl
Variables used:
sh_nm= Sheet Name you want to append in the workbook.
filename= Workbook name.
df=Dataframe for your new sheet.
Note: Exceptions not handled .
Code:
import pandas as pd
from openpyxl import load_workbook
# !pip install openpyxl
def sheet_collate(filename,_df,sh_nm):
with pd.ExcelWriter(filename, engine='openpyxl') as writer:
writer.book = load_workbook(filename)
_df.to_excel(writer,sh_nm, startrow=5,startcol=5,index=False)
writer.save()
return "Workbook Edited.."
filename='excel.xlsx'
sh_nm='Final'
sheet_collate(filename,df,sh_nm)

Related

Openpyxl not removing sheets completely from Excel Sheet

I was wondering if someone can explain why openpyxl is not removing sheet completely. I am using default openpyxl function. Thought this is deleting the sheet but the traces are still there in the developer tab. If you can help to fix this, I would be very grateful.
`remove_sheet(worksheet)`
While I am now using this alternative approach, but I beleive this is not efficient, since I first delete the sheet, then again use openpyxl to write it
xl = win32com.client.Dispatch('Excel.Application')
book = xl.Workbooks.Open(Filename = file, ReadOnly=False)
xl.Application.Run("delSheets.delSheets")
book.Save()
book.Close()
xl.Application.Quit()
del xl

Python Openpyxl return a sheet name which doesn't exist

In my excel file, I have only three worksheet: "Slot 14", "Data Display", and "Ctrl Value".
When I use openpyxl to load excel file, it returns other worksheet which doesn't exist: ['Slot 14', 'DETAILNO-14', 'DETAIL-14', 'PNO-14', 'DATA-14', 'Data Display', 'Ctrl Value']
Following is my code
filepath=r'D:\Users\chshiu\Desktop\filename.xlsx'
wb = openpyxl.load_workbook(filepath)
wb.get_sheet_names()
I don't think there is something wrong in my code. I am wondering maybe the problem is from excel file itself? I have VBA code inside the excel file.
More information:
I use Python3 in windows.
Because openpyxl cannot load xls file now so I save my original xls file into xlsx file.
It's possible that your file contains hidden sheets. Older versions of Excel use things called Macrosheets for some of the GUI controls. openpyxl just reports what it finds.

how to extract all the data in a single column in excel sheet using sikuli python

This selecting a single data from excel sheet. Now i want to fetch all the data from the excel sheet. Can somebody help me to solve this problem
I have tried this code:
import xlrd
import datetime
EXCELFILE = "D:\\Muthu\\Datamanipulation\\book1.xlsx"
book = xlrd.open_workbook(EXCELFILE)
sheet = book.sheet_by_index(0)
celltype = sheet.cell_type(40,33)
value = sheet.cell_value(40,33)

OpenPyXL always return None for a cell with hyperlink

(My ultimate purpose is to append clickable cells to existing XLSX.)
I use the code below to extract the cell's display value and the hyperlink.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A1')
print cell1.value
print cell1.hyperlink
print wsheet1['A1'].value
print wsheet1['A1'].hyperlink
But it returns the following things:
URL1
None
URL1
None
Why the hyperlink always None? I did add hyperlink manually for cell A1 and the hyperlink works in Excel 2013.
Unfortunately, it's a bug.
It's a bug in 2012...
Some related thread:
Extracting Hyperlinks From Excel (.xlsx) with Python
Some details of my experiment with hyperlink. I am using OpenPyXL 2.3.3.
I can add hyperlink to cells.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A1')
cell1.hyperlink = r'http://www.example.com'
cell1.value=r'XXX'
wbook.save(xlsFile)
But I cannot load the XLSX file and read the hyperlink just as my question said.
And If I just load and re-save the XLSX file, ALL existing hyperlinks will be lost. Yeah!
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wbook.save(xlsFile)
A workaround!
Use the formula with OpenPyXL.
My purpose is to append clickable cells to existing XLSX file. Since hyperlink doesn't work. I use the formula =HYPERLINK(url, displayText) instead. And luckily, the formula is not lost like previous experiment 3.
from openpyxl import load_workbook
xlsFile='hello.xlsx'
wbook = load_workbook(xlsFile)
wsheet1= wbook.get_sheet_by_name('mysheet')
cell1 = wsheet1.cell('A2')
cell1.value=r'=HYPERLINK("http://www.example.com","XXX")'
wbook.save(xlsFile)
Other (failed) options I tried:
I looked into the XlsxWriter. But it explicitly says it cannot modify existing XLSX file. So it cannot be used for appending.
I also looked into the xlrd/xlwt/xlutils, unfortunately, if you want to edit an existing excel, you have to use xlrd to load it as a read-only workbook, and then use xlutils to convert(copy) it into a writable workbook. And BANG! during the copy, something will be lost which includes the HYPERLINK formula. According to its doc string, this is a known limitation:
# Copyright (c) 2009-2012 Simplistix Ltd
#
# This Software is released under the MIT License:
# http://www.opensource.org/licenses/mit-license.html
# See license.txt for more details.
from xlutils.filter import process,XLRDReader,XLWTWriter
def copy(wb):
"""
Copy an :class:`xlrd.Book` into an :class:`xlwt.Workbook` preserving as much
information from the source object as possible.
See the :doc:`copy` documentation for an example.
"""
w = XLWTWriter()
process(
XLRDReader(wb,'unknown.xls'),
w
)
return w.output[0][1]
And also, xlwt doesn't support XLSX, only supports XLS. That's another reason I decided not to use it.

Is it possible to insert a worksheet into an existing workbook using Python?

The Problem
Creation of fancy reports using Pandas and Python.
Proposed Solution
Using a template xlsx file containing a template sheet nicely formatted with references to another pre-populated worksheet, delete the pre-populated sheet and insert the new worksheet from pandas. The template sheet will lose the links reverting to #REF so these will need to be renamed.
I tried:
import os
import xlrd, xlwt
import envconfig
swb1 = xlrd.open_workbook(os.path.join(envconfig.REPORT_WRITER_PATH,'TEMPLATE.xls'), on_demand=True, formatting_info=True)
swb2 = xlrd.open_workbook(os.path.join(envconfig.REPORT_WRITER_PATH,'REPORT.xls'), on_demand=True, formatting_info=True)
swb1s1 = swb1.sheet_by_name('Template')
swb2s1 = swb2.sheet_by_name('Report')
twb = xlwt.Workbook()
sheet1 = twb.add_sheet(swb1s1)
sheet2 = twb.add_sheet(swb2s1)
twb.save("python_spreadsheet.xls")
The above errors with:
sheet1 = twb.add_sheet(swb1s1)
File "C:\Users\pa003202\AppData\Local\Continuum\Anaconda3\lib\site-packages\xlwt\Workbook.py", line 366, in add_sheet
sheetname = sheetname.decode(self.encoding)
AttributeError: 'Sheet' object has no attribute 'decode'
sheetname = sheetname.decode(self.encoding)
AttributeError: 'Sheet' object has no attribute 'decode'
Is there a way to inject data from pandas into a workbook or to open a workbook and insert a sheet?
I solved this by creating a template as described and used the solution here:
Proposed Solution Using a template xlsx file containing a template sheet nicely formatted with references to another pre-populated worksheet, insert the new worksheet from pandas. The template sheet does not lose the links providing the inserted sheet has same name.
Solution:
Look at How to write to an existing excel file without overwriting data? and this works for the scenario.