Code for textbox using python and spire library

31 Views Asked by At

I'm testing this way to insert a textbox in excel with python

from spire.xls import *
from spire.xls.common import *

output_file = "my_file.xlsx"
output_path = r'C:\Users\me\OneDrive'

### TextBoxes
workbook = Workbook(output_path + '\\' + output_file)
sheet = workbook.Worksheets[0]

# Add your text box to the found worksheet
textBox = sheet.TextBoxes.AddTextBox(5, 3, 120, 300)
textBox.text = "This is a textbox in Excel."

# Add text to the textbox and set the text alignment
textBox.Text = "This is a textbox in Excel."
textBox.HAlignment = CommentHAlignType.Center
textBox.VAlignment = CommentVAlignType.Center

# Set font for the text
font = workbook.CreateFont()
font.FontName = "Times New Roman"
font.Size = 18
font.IsBold = True
font.Color = Color.get_Blue()
richText = textBox.RichText
rt = RichText(richText)
rt.SetFont(0, len(textBox.Text) - 1, font)

# Save the workbook to an Excel file
workbook.SaveToFile(output_path + '\\' + output_file, ExcelVersion.Version2016)
workbook.Dispose()

The part that is not working is the sheet:

sheet = workbook.Worksheets[0]

it's giving me this error:

in CallCFunction
spire.xls.common.SpireException: Arg_NullReferenceException:   at Spire.Xls.AOT.NLWorkbook.Workbook_Dispose(IntPtr, IntPtr) + 0x47

I took this example code from the Spire webpage: https://www.e-iceblue.com/Tutorials/Python/Spire.XLS-for-Python/Program-Guide/Objects/Python-Add-Update-or-Delete-Textboxes-in-Excel.html

0

There are 0 best solutions below