简体   繁体   中英

Using Python xlwings module to create cell comments

I am creating a spreadsheet from scratch using xlwings and populating it with data from a text file.

I am trying to figure out a way to create a comment for cells using xlwings. From everything I have seen this is not possible. Does anyone know of a way to do this?

If not, then I have already created a VBA script in the past that I can use but is there a way that I can port this VBA script into my python script? I would like to do this so I dont have to run the python script and then separately run a VBA script.

Thank you in advance.

As explained here , you can always fall back to the underlying pywin32 objects to workaround unimplemented features. In the case of comments, that would look something like this on Windows:

import xlwings as xw
wb = xw.Workbook.active()
xw.Range('A1').xl_range.AddComment()
xw.Range('A1').xl_range.Comment.Text('Some Text')

If you are actually updating a spreadsheet and so using xlwings, then xlwings has changed its its api .

import xlwings as xw
wb = xw.Workbook.active()
xw.Range('A1').api.AddComment('Some Text')

I second that xlsxwriter is nice for building from scratch.

If wb = xlwings.Book() on macOS 10.12 with Excel 2011 , then wb.range('A1').api.comment 's get and set methods don't seem to work with XLWings 0.11.4 . As a workaround, you can create a VBA macro in your workbook as follows

Sub AddCommentHook(address As String, message As String)
    Call Range(address).AddComment(message)
End Sub

(Don't forget to use the Developer toolbar's "Add Macro" dialog box to make sure the Excel workbook knows about the VBA code.) Then you can add an Excel cell comment from Python as follows:

ach = wb.macro('AddCommentHook')
ach('Sheet1!A1', 'test 123')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM