Python Export Excel Sheet Range as Image - python

So it seems there's something weird going on with PIL ImageGrab.grabclipboard()
import win32com.client
from PIL import ImageGrab
o = win32com.client.Dispatch('Excel.Application')
o.visible = False
wb = o.Workbooks.Open(path)
ws = wb.Worksheets['Global Dash']
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture()
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)
When I run this, I notice that if I ctrl-V , the image is actually correctly saved on the clipboard, but my img variable returns None, meaning ImageGrab.grabclipboard() is somehow not working. Any ideas?

Here I have a solution which might help you.
import excel2img
excel2img.export_img("example.xlsx/example.csv","image.png/image.bmp","sheet!B2:H22")
This is working perfectly for me.

To clarify those comments of Florent B. and David Yang
Add optional parameter Format into .CopyPicture() will make ImageGrab.getclipboard() work as expected.
The following code will be
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture(Format = 2)
Number 2 is xlBitmap, refer to https://learn.microsoft.com/en-us/office/vba/api/excel.range.copypicture

I just replaced ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture() by ws.Range(ws.Cells(1,1),ws.Cells(66,16)).Copy() and it
worked perfectly.
So this is the entire code.
import win32com.client
from PIL import ImageGrab
o = win32com.client.Dispatch('Excel.Application')
o.visible = False
wb = o.Workbooks.Open(path)
ws = wb.Worksheets['Global Dash']
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).Copy()
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

I just tried the method posted in the comments under the question and it actually works!
Pay attention to use win32com.client.constants to get the xlBitmap.
In addition, my environment is Python 3.6 and I haven't tried it again in Python 2.7.
win32c = win32com.client.constants
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture(Format= win32c.xlBitmap)
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

This solution worked for me.
Try to start Excel with:
o = win32com.client.gencache.EnsureDispatch("Excel.Application")
Then use win32com.client.constants to get the xlBitmap
wb = o.Workbooks.Open(workbook_file_name)
ws = wb.Worksheets("Vs. Disk or Retrofit Chart View")
ws.Range(ws.Cells(22,1),ws.Cells(62,8)).CopyPicture(Format= win32com.client.constants.xlBitmap)
img = ImageGrab.grabclipboard()
imgFile = os.path.join(os.getcwd(),'test.jpg')
img.save(imgFile)

The best way to do it is:
import win32com.client
from PIL import ImageGrab
wb_file_name = 'Input.xlsx'
outputPNGImage = 'Output.png'
xls_file = win32com.client.gencache.EnsureDispatch("Excel.Application")
wb = xls_file.Workbooks.Open(Filename=wb_file_name)
xls_file.DisplayAlerts = False
ws = wb.Worksheets("Desired_Tab")
ws.Range(ws.Cells(1,1),ws.Cells(15,3)).CopyPicture(Format= win32com.client.constants.xlBitmap) # example from cell (1,1) to cell (15,3)
img = ImageGrab.grabclipboard()
img.save(outputPNGImage)
wb.Close(SaveChanges=False, Filename=wb_file_name)

Related

xlwings: pass a variable into formula bar

I want to loop over multiple files, creating new formulas for each file as I go. To do that I want to concatenate a string with a variable, then use excel wings create a new formula. To that end I've written this code:
file_name=r'[Element_IA_Gross.xlsx]'
equation=r'=SUM(\''+file_name+'Total Immediates\'!$R6:$T6)'
ws.range("O19").value= [equation]
If I print the variable equation I see what I want in the excel formula bar. However using the above code doesn't work? Any help much appreciated.
Thanks
The formula looks for the workbook in the default location so opens a file search window and waits for the input.
The following works based on why it worked for me by opening both workbooks, adding the formula to 'book1', save 'book1' and then close both books.
import xlwings as xw
file_name = 'Element_IA_Gross.xlsx'
workbook = 'Book1.xlsx'
with xw.App() as app:
wb1 = xw.Book(workbook)
wb2 = xw.Book(file_name)
ws = wb1.sheets('Sheet1')
equation = "=SUM('[" + file_name + "]Total Immediates'!$R6:$T6)"
ws["O19"].value = equation
wb1.save(workbook)
wb1.close()
wb2.close()
-------------Option 2 ----------
This option also worked including the whole path and filename in the formula.
import os
import xlwings as xw
path = r'F:\Projects\xlwings_test'
file_name = 'Element_IA_Gross.xlsx'
link = os.join(path, file_name)
workbook = 'Book1.xlsx'
with xw.App() as app:
wb1 = xw.Book(workbook)
ws = wb1.sheets('Sheet1')
equation = "SUM('[" + link + "]Total Immediates'!$R6:$T6)"
ws["O19"].value = equation
wb1.save(workbook)
wb1.close()

When using Rembg in python to remove image background, how can I turn on the alpha matting?

Here is shown how to do it using curl.
Here is my code also from the same website:
from rembg.bg import remove
import numpy as np
import io
from PIL import Image
input_path = 'input.png'
output_path = 'out.png'
f = np.fromfile(input_path)
result = remove(f)
img = Image.open(io.BytesIO(result)).convert("RGBA")
img.save(output_path)
Blockquote
result = remove(
f,
alpha_matting=True,
alpha_matting_foreground_threshold=240,
alpha_matting_background_threshold=10,
alpha_matting_erode_structure_size=10,
alpha_matting_base_size=1000,
)

Saving a pivot table as picture?

The following code selects the range of a pivot table and saves down as picture. How would it go to select the pivot table by its name (e.g., "Pivot1") and not by the range?
import win32com.client as win32
import sys
from pathlib import Path
import win32com.client as win32
from PIL import ImageGrab
excel_path = "C:/Prueba/GOOG-copia.xlsm"
excel = win32.DispatchEx('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open(Filename=excel_path)
ws = wb.Worksheets('Cacaca')
win32c = win32.constants
ws.Range("A3:B8").CopyPicture(Format=win32c.xlBitmap)
img = ImageGrab.grabclipboard()
image_path = 'C:/Prueba/test.png'
img.save(image_path)
excel.Quit()
You can select named ranges by using the range method:
wb.Worksheets('Cacaca').Range("Pivot1").Select()
When using the Win32 library, you can often try the process with VBA first as the Win32 calls tend to map to VBA.
Update - Here is the code to list all pivot tables in a Workbook:
# create dictionary of Pivot tables by sheet
dd = {}
ShtCnt = excel.Sheets.Count
for s in range(ShtCnt):
#print("Sheet Name:", wb.Sheets(s+1).Name)
dd[wb.Sheets(s+1).Name] = []
cnt = wb.Sheets(s+1).PivotTables().Count
for x in range(cnt):
#print(wb.Sheets(s+1).PivotTables(x+1).Name)
dd[wb.Sheets(s+1).Name].append(wb.Sheets(s+1).PivotTables(x+1).Name)
print(dd)

Image not displayed in excell cell (python and openpyxl)

i am tring to create a script using python and openpyxl`s function called add_image which will add resized photos into cells, for this i am using the
following code:
from PIL import Image
from openpyxl import load_workbook
from openpyxl import Workbook
wb = load_workbook('file.xlsx')
ws = wb.active
max_row = ws.max_row
########## SET DIMENSIONS FOR 'F' cells#######
ws.column_dimensions['F'].width=200
for x in range (2,max_row+1):
ws.row_dimensions[x].height=200
##############################################
img = Image.open(file)
bound_width_height = (195, 150)
img.thumbnail(bound_width_height, Image.ANTIALIAS)
nimg = openpyxl.drawing.image.Image(img)
ws.add_image(nimg,'F3')
wb.save('test.xlsx')
print('done!')
but when i am watching into test.xlsx file i see This image cannot curently be displayed.
Result:
https://imgur.com/a/mjgL4hn
Any ideeas why?

Insert image in openpyxl

Is it possible to insert an image (jpeg, png, etc) using openpyxl?
Basically I want to place a generated image with a chart below it.
I don't see anything in the documentation, which seems to be a little lacking compared to the maturity of the code.
The following inserts an image in cell A1. Adjust the image location to your needs or handle the creation of the PIL image yourself and hand that to Image()
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.image.Image('test.jpg')
img.anchor = 'A1'
ws.add_image(img)
wb.save('out.xlsx')
In older versions of openpyxl the following works:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)
wb.save('out.xlsx')
Providing a full update on how to do this. This solution uses openpyxl version 2.4.5.
I downloaded an image to my local directory, opened an existing workbook and saved with the image inserted.
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.drawing.image import Image
from openpyxl.utils import coordinate_from_string
openpyxl_version = openpyxl.__version__
print(openpyxl_version) #to see what version I'm running
# downloaded a .png to local directory manually from
# "https://www.python.org/static/opengraph-icon-200x200.png"
#change to the location and name of your image
png_loc = r'c:\users\me\opengraph-icon-200x200.png'
# test.xlsx already exists in my current directory
wb = load_workbook('test.xlsx')
ws = wb.active
my_png = openpyxl.drawing.image.Image(png_loc)
ws.add_image(my_png, 'B3')
wb.save('test.xlsx')
Results:
This code worked for me:
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
ws.merge_cells('A1:A3')
img = openpyxl.drawing.image.Image('image.jpg')
row_number = 1
col_idx = 1
cell = ws.cell(row=row_number, column=col_idx)
ws.add_image(img)
wb.save('output.xlsx')
Just to add, I have been using openpyxl==2.5.6 (with Python3.65), and I had to use img.anchor('A1') instead of img.anchor(ws.cell('A1')).
import openpyxl
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('test.jpg')
img.anchor('A1')
ws.add_image(img)
wb.save('out.xlsx')

Categories

Resources