I want to add some object to my excel sheet,
I'm using openpyxl,
In excel you do it by:
Insert->Object
Is there a way to do it thru openpyxl or any other excel tool that working with python?
While this is not currently possible with openpyxl I suspect it would be fairly straightforward to add the relevant functionality using the add_image() method as a starting place.
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
picture = openpyxl.drawing.Image('/path/to/picture')
picture.anchor(ws.cell('cell to put the image'))
ws.add_image(picture)
wb.save('whatever you want to save the workbook as')
This code of course refers to creating a new workbook and adding the image into it. To add the image to your preexisting workbook you would obviously just load that workbook using load_workbook.
Related
I have done a lot of research and failed to solve this problem, so I am coming here to ask for help. I read the worksheet object from a file below,
sheet_2_workbook = openpyxl. load_workbook(sheet_2_path)
sheet_2 = sheet_2_workbook.worksheets\[0\]
As described in the title, I want to add it to the new sheet of the existing .xlsx document, how should I do it?
I tried to realize this as below, but the new document obtained by this method will lose some of the original formatting, including the cell background color and merged cells
old_wb = openpyxl. load_workbook(file_list[i])
old_sheet_name = old_wb. get_sheet_names()[0]
old_ws = old_wb[old_sheet_name]
ws2 = combined_wb.create_sheet(sheet_name)
for row in old_ws.values:
ws2.append(row)
I am sure that the worksheet object read in the file contains these formats, because the .xlsx document I dumped with the following code has the format mentioned above
sheet_2_workbook. save(filename = temp_save_path)
How I would go about your task of adding a worksheet object to a new sheet in an existing Excel document using openpyxl:
Import the openpyxl module
Load the existing Excel document using the load_workbook() function
Create a new sheet using the create_sheet() method of the Workbook object
Alternatively, you can specify the name of the new sheet as a string when calling the create_sheet() method
Save changes using the save() method
(To preserve the formatting you can use the copy_worksheet() to create a copy of the original worksheet and add it to the workbook)
import openpyxl
workbook = openpyxl.load_workbook('existing_document.xlsx')
sheet_2_workbook = openpyxl.load_workbook(sheet_2_path)
sheet_2 = sheet_2_workbook.worksheets[0]
new_sheet = workbook.copy_worksheet(sheet_2)
// Alternatively, you can specify the name of the new sheet as a string
// new_sheet = workbook.copy_worksheet(sheet_2, 'Sheet2')
workbook.save('existing_document.xlsx')
I get a huge Excel-Sheet (normal table with header and data) on a regular basis and I need to filter and delete some data and split the table up into seperate sheets based on some rules. I think I can save me some time if I use Python for that tedious task because the filtering, deleting and splitting up into several sheets is based on always the same rules that can logically be defined.
Unfortunately the sheet and the data is partially color-coded (cells and font) and I need to maintain this formating for the resulting sheets. Is there a way of doing that with python? I think I need a pointer in the right direction. I only found workarounds with pandas but that does not allow me to keep the formatting.
You can take a look at an excellent Python library for Excel called openpyxl.
Here's how you can use it.
First, install it through your command prompt using:
pip install openpyxl
Open an existing file:
import openpyxl
wb_obj = openpyxl.load_workbook(path) # Open notebook
Deleting rows:
import openpyxl
from openpyxl import load_workbook
wb = load_wordbook(path)
ws = wb.active
ws.delete_rows(7)
Inserting rows:
import openpyxl
from openpyxl import load_workbook
wb = load_wordbook(path)
ws = wb.active
ws.insert_rows(7)
Here are some tutorials that you can take a look at:
Tutorial 1
Youtube Video
I'm using Python and openpyxl library, but, I'm not able to use the insert_cols() function in openpyxl when my spreadsheet is in write_only=True mode. So, basically, I just want to add a new column to my spreadsheet when it's in write_only=True mode.
I'm able to use insert_cols() when loading the workbook by load_workbook(), but, not when I'm using the write_only mode. I have to use the write_only mode because my spreadsheets are quite large.
Any ideas on how to add a new column are appreciated.
Thank you.
This is my code:
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
wb = load_workbook(filename=r'path\myExcel.xlsx', read_only=True)
ws = wb['PC Details']
wb_output = Workbook(write_only=True)
ws_output = wb_output.create_sheet(title='PC Details')
for row in ws.rows:
rowInCorrectFormat = [cell.value for cell in row]
ws_output.append(rowInCorrectFormat)
for cell in row:
print(cell.value)
### THIS IS THE PART OF THE CODE WHICH DOES NOT WORK
ws_output.insert_cols(12)
ws_output['L5'] = 'OK or NOT GOOD?'
###
wb_output.save(r'path\test_Output_optimized.xlsx')
This is the exact error that I'm getting:
ws_output.insert_cols(12)
AttributeError: 'WriteOnlyWorksheet' object has no attribute 'insert_cols'
The problem here lies in the flag write_only = True. Workbooks created by this flag set to true are different from regular Workbooks as you can look below.
Functions like insert_cols & insert_rows also do not work for such workbooks.
Possible solutions might be to not use this flag or use the ways suggested in the official documentation for adding data to the sheet.
For working with workbooks you might also find this article interesting. https://medium.com/aubergine-solutions/working-with-excel-sheets-in-python-using-openpyxl-4f9fd32de87f
You can read more in the official documentation. https://openpyxl.readthedocs.io/en/stable/optimized.html
I am using xlwings to place stock data I pull from the internet into worksheets. The workbook opens with a Sheet1, and upon running my program creates various sheets named according to the stock index. This leaves Sheet1 and causes problems with other methods I want to call. I want to test for any sheets that contain Sheet (plus an integer) and subsequently delete it similar to how you would test for the presence of a list element using the in operator. How would I go about doing this in xlwings? Current xlwings methods only allow sheets in which you manually name to be deleted.
My attempts have been rather lackluster. I've been trying loops to recognize the sheet names but to no avail. Here is my attempt to do so.
import xlwings as xw
wb = xw.Book('practice.xlsx')
for sheet in wb.sheets:
if 'Sheet' in sheet:
xw.Sheet[sheet].delete()
This works:
import xlwings as xw
wb = xw.Book('practice.xlsx')
for sheet in wb.sheets:
if 'Sheet' in sheet.name:
sheet.delete()
is the syntax more like sheet.api.Delete()? My xlwings is broken right now to check the exact syntax.
You can check, if the given sheet exist and you can delete the existing sheet and add a new one.
import xlwings as xw
def df_to_excel_util(excel,sheet_to_dataFrame_map):
with xw.App(visible=False) as app:
wb = app.books.open(excel)
current_sheets = [sheet.name for sheet in wb.sheets]
for sheet_name in sheet_to_dataFrame_map.keys():
if sheet_name in current_sheets:
wb.sheets[sheet_name].delete()
new_sheet = wb.sheets.add(after=wb.sheets.count)
new_sheet.range('A1').value = sheet_to_dataFrame_map.get(sheet_name)
new_sheet.name = sheet_name
wb.save()
if you have sheet object, you can delete as given below
sheet.delete()
if you want to delete a sheet with a given name.
wb.sheets['sheet_name'].delete
I have created an excel sheet using XLWT plugin using Python. Now, I need to re-open the excel sheet and append new sheets / columns to the existing excel sheet. Is it possible by Python to do this?
After investigation today, (2014-2-18) I cannot see a way to read in a XLS file using xlwt. You can only write from fresh. I think it is better to use openpyxl. Here is a simple example:
from openpyxl import Workbook, load_workbook
wb = Workbook()
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14156265
wb.save(filename=r'C:\book2.xls')
# Re-opening the file:
wb_re_read = load_workbook(filename=r'C:\book2.xls')
sheet = wb_re_read.get_sheet_by_name('Pi')
print sheet.cell('F5').value
See other examples here: http://pythonhosted.org/openpyxl/usage.html (where this modified example is taken from)
You read in the file using xlrd, and then 'copy' it to an xlwt Workbook using xlutils.copy.copy().
Note that you'll need to install both xlrd and xlutils libraries.
Note also that not everything gets copied over. Things like images and print settings are not copied, for example, and have to be reset.