Working with spreadsheet document attachments
Leave feedback
On this page
Excel worksheets can embed file attachments (OLE objects). They are available through SpreadsheetContent.worksheets[i].attachments. Each attachment exposes alternative_text, is_link, source_full_name, content, and get_document_info(), and the document it contains can be opened in its own Watermarker. A linked attachment (is_link) stores only the path to its file in source_full_name; its content is None.
Extract attachments
fromgroupdocs.watermarkimportWatermarkerfromgroupdocs.watermark.options.spreadsheetimportSpreadsheetLoadOptionsdefextract_attachments():withWatermarker("./spreadsheet.xlsx",SpreadsheetLoadOptions())aswatermarker:content=watermarker.get_content()fori,worksheetinenumerate(content.worksheets):forattachmentinworksheet.attachments:ifattachment.is_link:# A linked object stores only the path to its file, not the file itselfprint(f"Worksheet {i}: {attachment.alternative_text!r} links to {attachment.source_full_name}")continueinfo=attachment.get_document_info()print(f"Worksheet {i}: {attachment.alternative_text!r} type={info.file_type}")withopen(f"./{attachment.alternative_text}","wb")asf:f.write(attachment.content)if__name__=="__main__":extract_attachments()
spreadsheet.xlsx is the sample file used in this example. Click here to download it.
The attachments collection supports remove_at(index) and remove(attachment). Iterate in reverse when removing by index. The example removes the linked attachments:
Open each attachment’s bytes in its own Watermarker, add a watermark, and write the result back:
importiofromgroupdocs.watermarkimportWatermarkerfromgroupdocs.watermark.watermarksimportTextWatermark,Font,Colorfromgroupdocs.watermark.options.spreadsheetimportSpreadsheetLoadOptionsdefwatermark_attached_documents():withWatermarker("./spreadsheet.xlsx",SpreadsheetLoadOptions())aswatermarker:content=watermarker.get_content()forworksheetincontent.worksheets:forattachmentinworksheet.attachments:ifattachment.is_link:continue# the linked file is not stored in the workbookwithWatermarker(io.BytesIO(attachment.content))asinner:wm=TextWatermark("CONFIDENTIAL",Font("Arial",19.0))wm.foreground_color=Color.redinner.add(wm)buffer=io.BytesIO()inner.save(buffer)# write the watermarked attachment bytes back as neededwatermarker.save("./output.xlsx")if__name__=="__main__":watermark_attached_documents()
spreadsheet.xlsx is the sample file used in this example. Click here to download it.