Home » excel » python + excel: how to programmatically insert picture into comment

python + excel: how to programmatically insert picture into comment

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to insert a picture into an excel cell comment box. Example of what I mean here.

Is there a way to do this with an existing python library?

I have looked at both openpyxl and xlsxwriter docs – it seems they just allow the creation of text comments.

Xlsx writer allows you to change the background color of a comment box, but it appears there is no solution for inserting a picture.

How to&Answers:

YOu can insert picture in spreadsheet using xlsxwriter. Check out this, it might help you to solve your issue.

Answer:

I wanted the same feature yet I couldn’t find it in any python library.

I ended up using Excels “Macro” feature, you can find it under the “Developer” tab
which you need to enable in File -> Options -> Customize Ribbon; it can be found on the right side amongst the Main Tabs.

After you select “Macro”, give it a name and hit create it should create the sub for
you where you can write this Visual Basic code:

Sub addPic()
'
' Macro3 Macro
'
    Dim pic_file As String
    Dim pic_resolution As Long
    Dim pict As Object
    
    If ActiveCell.Comment Is Nothing Then ActiveCell.AddComment
    pic_file = Application.GetOpenFilename("GIF (*.GIF), *.GIF", Title:="Select chord picture: ")
    Set pict = CreateObject("WIA.ImageFile")
    pict.loadfile pic_file
    pic_resolution = pict.VerticalResolution
    
  With ActiveCell.Comment.Shape
     .Fill.Visible = msoTrue
     .Fill.UserPicture (pic_file)
     .Height = pict.Height / pic_resolution * 96
     .Width = pict.Width / pic_resolution * 96
   End With
 
  Set pict = Nothing
   
  ActiveCell.Comment.Visible = False
End Sub

You can change the .GIF extension and resolution to whatever you need.
Finally you should pick a keyboard shortcut which you can select
under Macro->(Select your macro)->Options