Python (355)
Merging cells means combining multiple adjacent cells into a larger one. The merged cell will inherit all the properties and contents of the original cells. This feature is particularly useful when you need to create a larger cell to accommodate more content or create a header row. Unmerging cells, on the other hand, involves reverting the merged cells back to the original multiple cells. The unmerged cells will revert back to their original independent state, and you can input different content into each individual cell. Merging and unmerging cells are common operations in spreadsheet software, allowing you to adjust the layout and structure of a table as needed, making the data clearer and easier to understand. In this article, you will learn how to merge or unmerge cells in Excel in Python by using Spire.XLS for Python.
- Merge the Cells of the Specified Row or Column
- Merge Ranges of Cells
- Unmerge the Cells of the Specified Row or Column
- Unmerge Ranges of Cells
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Merge the Cells of the Specified Row or Column
With Spire.XLS for Python, users are able to effortlessly merge the cells of the specific column or row in Excel, thereby enhancing their data manipulation capabilities. The following are the detailed steps.
- Create an object of Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get the desired worksheet by using Workbook.Worksheets[] property.
- Access the cells of the specific column or row and merge them by calling Worksheet.Columns[].Merge() or Worksheet.Rows[].Merge() methods.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * inputFile = "Sample.xlsx" outputFile = "MergeRowColumn.xlsx" #Create an object of Workbook class workbook = Workbook() #Load a sample Excel file from disk workbook.LoadFromFile(inputFile) #Get the first worksheet of this file sheet = workbook.Worksheets[0] #Merge the first column in Excel #sheet.Columns[0].Merge() #Merge the first row in Excel sheet.Rows[0].Merge() #Save the result file workbook.SaveToFile(outputFile, ExcelVersion.Version2013) workbook.Dispose()

Merge Ranges of Cells
In addition to merging the specific column or row, Spire.XLS for Python also supports users to merge the specified cell ranges. The following are the detailed steps.
- Create an object of Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get the desired worksheet by using Workbook.Worksheets[] property.
- Access the specific range of cells and merge them together by calling Worksheet.Range[].Merge() method.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * inputFile = "Sample.xlsx" outputFile = "MergeCellRange.xlsx" #Create an object of Workbook class workbook = Workbook() #Load a sample Excel file from disk workbook.LoadFromFile(inputFile) #Get the first worksheet of this file sheet = workbook.Worksheets[0] #Merge the particular cell range in Excel sheet.Range["B6:G6"].Merge() #Save the result file workbook.SaveToFile(outputFile, ExcelVersion.Version2013) workbook.Dispose()

Unmerge the Cells of the Specified Row or Column
Additionally, users are also allowed to unmerge the merged cells of the specific column or row at any time with Spire.XLS for Python. The following are the detailed steps.
- Create an object of Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get the desired worksheet by using Workbook.Worksheets[] property.
- Access the merged cells of the specific column or row and unmerge them by calling Worksheet.Columns[].UnMerge() and Worksheet.Rows[].UnMerge() methods.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * inputFile = "MergeRowColumn.xlsx" outputFile = "UnmergeRowColumn.xlsx" #Create an object of Workbook class workbook = Workbook() #Load a sample file from disk workbook.LoadFromFile(inputFile) #Get the first worksheet of this file sheet = workbook.Worksheets[0] #Unmerge the first column in Excel #sheet.Columns[0].UnMerge() #Unmerge the first column in Excel sheet.Rows[0].UnMerge() #Save to file. workbook.SaveToFile(outputFile, ExcelVersion.Version2013) workbook.Dispose()

Unmerge Ranges of Cells
What's more, users are also able to unmerge the specified cell ranges using Spire.XLS for Python. The following are the detailed steps.
- Create an object of Workbook class.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get the desired worksheet by using Workbook.Worksheets[] property.
- Access the specific cell ranges and unmerge them by calling Worksheet.Range[].UnMerge() method.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import * from spire.xls.common import * inputFile = "MergeCellRange.xlsx" outputFile = "UnmergeCellRange.xlsx" #Create an object of Workbook class workbook = Workbook() #Load a sample file from disk workbook.LoadFromFile(inputFile) #Get the first worksheet of this file sheet = workbook.Worksheets[0] #Unmerge the particular cell range in Excel sheet.Range["B6:G6"].UnMerge() #Save to file. workbook.SaveToFile(outputFile, ExcelVersion.Version2013) workbook.Dispose()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Hyperlinks are a useful tool in Microsoft Excel that allows users to create clickable links within their spreadsheets. By adding hyperlinks, you can conveniently navigate between different sheets, workbooks, websites, or even specific cells within the same workbook. Whether you need to reference external resources, connect related data, or create interactive reports, hyperlinks can help you achieve your purpose with ease. In this article, we will demonstrate how to add hyperlinks to Excel in Python using Spire.XLS for Python.
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Add Text Hyperlinks to Excel in Python
Text hyperlinks in Excel are clickable words or phrases that can direct users to different parts of the Excel file, external resources, or email addresses. The following steps explain how to add a text hyperlink to an Excel file using Spire.XLS for Python:
- Create a Workbook object.
- Get the desired worksheet using Workbook.Worksheets[] property.
- Access the specific cell that you want to add a hyperlink to using Worksheet.Range[] property.
- Add a hyperlink to the cell using Worksheet.HyperLinks.Add() method.
- Set the type, display text and address of the hyperlink using XlsHyperLink.Type, XlsHyperLink.TextToDisplay and XlsHyperLink.Address properties.
- Save the resulting file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Add a text hyperlink that leads to a webpage
cell1 = sheet.Range["B3"]
urlLink = sheet.HyperLinks.Add(cell1)
urlLink.Type = HyperLinkType.Url
urlLink.TextToDisplay = "Link to a website"
urlLink.Address = "https://www.e-iceblue.com/"
# Add a text hyperlink that leads to an email address
cell2 = sheet.Range["E3"]
mailLink = sheet.HyperLinks.Add(cell2)
mailLink.Type = HyperLinkType.Url
mailLink.TextToDisplay = "Link to an email address"
mailLink.Address = "mailto:example@outlook.com"
# Add a text hyperlink that leads to an external file
cell3 = sheet.Range["B7"]
fileLink = sheet.HyperLinks.Add(cell3)
fileLink.Type = HyperLinkType.File
fileLink.TextToDisplay = "Link to an external file"
fileLink.Address = "C:\\Users\\Administrator\\Desktop\\Report.xlsx"
# Add a text hyperlink that leads to a cell in another sheet
cell4 = sheet.Range["E7"]
linkToSheet = sheet.HyperLinks.Add(cell4)
linkToSheet.Type = HyperLinkType.Workbook
linkToSheet.TextToDisplay = "Link to a cell in sheet2"
linkToSheet.Address = "Sheet2!B5"
# Add a text hyperlink that leads to a UNC address
cell5 = sheet.Range["B11"]
uncLink = sheet.HyperLinks.Add(cell5)
uncLink.Type = HyperLinkType.Unc
uncLink.TextToDisplay = "Link to a UNC address"
uncLink.Address = "\\\\192.168.0.121"
# Autofit column widths
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)
# Save the resulting file
workbook.SaveToFile("AddTextHyperlinks.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Add Image Hyperlinks to Excel in Python
Image hyperlinks in Excel work similarly to text hyperlinks but use images as clickable elements instead of words or phrases. They provide a visually appealing and intuitive way to navigate within the spreadsheet or to external resources. The following steps explain how to add an image hyperlink to an Excel file using Spire.XLS for Python:
- Create a Workbook object.
- Get the desired worksheet using Workbook.Worksheets[] property.
- Insert an image into the worksheet using Worksheet.Pictures.Add() method.
- Add a hyperlink to the image using XlsBitmapShape.SetHyperLink() method.
- Save the result file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Add text to the worksheet
sheet.Range["B2"].Text = "Image Hyperlink"
# Set the width of the second column
sheet.Columns[1].ColumnWidth = 15
# Insert an image into the worksheet
picture = sheet.Pictures.Add(3, 2, "logo2.png")
# Add a hyperlink to the image
picture.SetHyperLink("https://www.e-iceblue.com", True)
# Save the resulting file
workbook.SaveToFile("AddImageHyperlink.xlsx", ExcelVersion.Version2013)
workbook.Dispose()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Spire.Presentation for Python is a Python library for reading, creating, editing and converting PowerPoint (.ppt or .pptx) files in any Python application. This article shows you how to install Spire.Presentation for Python on Windows.
Step 1
Download the latest version of Python and install it on your computer. If you have already installed it, skip to step 2.

Step 2
Click "Extensions" in VS Code, search for "Python" and then install it.

Step 3
Click "Explorer" - "NO FOLRDER OPENED" - "Open Folder".

Choose an existing folder as the workspace, or you can create a new folder and then select it.

Add a .py file to the folder you just added (Python folder in this case), and name it whatever you like.

Step 4
Click "Terminal" and then "New Terminal".

Input the following pip command to install Spire.Presentation for Python and plum-dispatch v1.7.4.
pip install Spire.Presentation

Alternatively, you can download Spire.Presentation for Python from our website, and unzip it to get two .whl files from the "lib" folder. They're for Linux system and Windows system respectively.

After that, install Spire.Presentation for Python and plum-dispatch v1.7.4 by running the following pip command.
pip install E:\Library\Python\spire.presentation.python_8.8.3\lib\Spire.Presentation-8.8.3-py3-none-win_amd64.whl

Step 5
Add the following code snippet to the "HelloWorld.py" file.

Once you run the Python file, you'll see the result PowerPoint document in the "EXPORER" panel.

Spire.Presentation for Python is a professional presentation processing API that is highly compatible with PowerPoint. It is a completely independent class library that developers can use to create, edit, convert, and save PowerPoint presentations efficiently without installing Microsoft PowerPoint.
Spire.Presentation for Python supports a variety of presentation manipulation features, such as adding/deleting/hiding/showing/rearranging/copying slides, adding/extracting images, adding/removing hyperlinks, adding/extracting animations, creating tables/charts, adding/extracting/highlighting/replacing text, adding/extracting/replacing videos and audio, encrypting/decrypting presentations, adding text/image watermarks, setting/removing background, and manipulating comments/speaker note etc.
Spire.PDF for Python is a Python library for reading, creating, editing and converting PDF files in any Python application. This article shows you how to install Spire.PDF for Python on Windows.
Step 1
Download the latest version of Python and install it on your computer. If you have already installed it, skip to step 2.

Step 2
Click "Extensions" in VS Code, search for "Python" and then install it.

Step 3
Click "Explorer" - "NO FOLRDER OPENED" - "Open Folder".

Choose an existing folder as the workspace, or you can create a new folder and then select it.

Add a .py file to the folder you just added (Python folder in this case), and name it whatever you like.

Step 4
Click "Terminal" and then "New Terminal".

Input the following pip command to install Spire.PDF for Python and plum-dispatch v1.7.4.
pip install Spire.PDF

Alternatively, you can download Spire.PDF for Python from our website, and unzip it to get two .whl files from the "lib" folder. They're for Linux and Windows systems, respectively.

Then, install Spire.PDF for Python and plum-dispatch v1.7.4 by running the following pip command.
pip install E:\Library\Python\spire.pdf.python_9.8.0\lib\spire.pdf-9.8.0-py3-none-win_amd64.whl

Step 5
Add the following code snippet to the "HelloWorld.py" file.
- Python
from spire.pdf.common import *
from spire.pdf import *
doc= PdfDocument()
page = doc.Pages.Add()
str = "Hello, World"
x = 10.0
y = 10.0
font = PdfFont(PdfFontFamily.Helvetica ,30.0)
color = PdfRGBColor(Color.get_Black())
textBrush = PdfSolidBrush(color)
page.Canvas.DrawString(str, font, textBrush, x, y)
doc.SaveToFile("output.pdf")
doc.Close()

Once you run the Python file, you'll see the result PDF document in the 'EXPORER' panel.

Fonts play a crucial role in enhancing the visual appeal and readability of data in Microsoft Excel. Whether you're creating a spreadsheet, designing a report, or simply organizing information, the ability to set or change fonts can greatly impact the overall presentation. Excel offers a wide range of font options, allowing you to customize the style, size, and formatting to suit your specific needs. In this article, you will learn how to set or change fonts in Excel in Python using Spire.XLS for Python.
- Set Different Fonts for Different Cells in Python
- Apply Multiple Fonts in a Single Cell in Python
- Change the Font Style of a Cell Range in Python
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Set Different Fonts for Different Cells in Python
With Spire.XLS for Python, customizing fonts in specific cells becomes a breeze. By utilizing the CellRange.Style.Font property, you gain control over font name, color, size, and style effortlessly. Follow these steps to apply a font style to a particular cell using Spire.XLS for Python.
- Create a Workbook object.
- Get a specific worksheet through Workbook.Worksheets[index] property.
- Get a specific cell through Worksheet.Range[int Row, int Column] property.
- Set the value of the cell through CellRange.Value property.
- Set the font name, color, size and style of the cell value through the properties under the CellRange.Style.Font object.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Set font name
row = 1
sheet.Range[row, 1].Value = "Font Name"
sheet.Range[row, 2].Value = "Arial Black"
sheet.Range[row, 2].Style.Font.FontName = "Arial Black"
# Set font size
row += 2
sheet.Range[row, 1].Value = "Font Size"
sheet.Range[row, 2].Value = "15"
sheet.Range[row, 2].Style.Font.Size = 15
# Set font color
row += 2
sheet.Range[row, 1].Value = "Font Color"
sheet.Range[row, 2].Value = "Red"
sheet.Range[row, 2].Style.Font.Color = Color.get_Red()
# Make text bold
row += 2
sheet.Range[row, 1].Value = "Bold"
sheet.Range[row, 2].Value = "Bold"
sheet.Range[row, 2].Style.Font.IsBold = True;
# Make text italic
row += 2
sheet.Range[row, 1].Value = "Italic"
sheet.Range[row, 2].Value = "Italic"
sheet.Range[row, 2].Style.Font.IsItalic = True
# Underline text
row += 2
sheet.Range[row, 1].Value = "Underline"
sheet.Range[row, 2].Value = "Underline"
sheet.Range[row, 2].Style.Font.Underline = FontUnderlineType.Single
# Strikethrough text
row += 2
sheet.Range[row, 1].Value = "Strikethrough "
sheet.Range[row, 2].Value = "Strikethrough "
sheet.Range[row, 2].Style.Font.IsStrikethrough = True
# Set column width
sheet.Columns[0].ColumnWidth = 25
sheet.Columns[1].ColumnWidth = 25
# Save the workbook to an Excel file
workbook.SaveToFile("output/ApplyFontInCell.xlsx", ExcelVersion.Version2016)

Apply Multiple Fonts in a Single Cell in Python
To emphasize specific characters within a cell, you can mix fonts. Here are the steps to apply multiple fonts in a single cell using Spire.XLS for Python:
- Create a Workbook object.
- Get a specific worksheet through Workbook.Worksheets[index] property.
- Create two ExcelFont objects using Workbook.CreateFont() method.
- Get a specific cell through Worksheet.Range[int Row, int Column] property, and set the rich text content of the cell through CellRange.RichText.Text property.
- Apply the two ExcelFont objects to the rich text using RichText.SetFont() method.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Create a font
font1 = workbook.CreateFont()
font1.FontName = "Arial Black"
font1.KnownColor = ExcelColors.LightBlue
font1.IsBold = True
font1.Size = 13
# Create another font
font2 = workbook.CreateFont()
font2.KnownColor = ExcelColors.Red
font2.IsBold = True
font2.IsItalic = True
font2.FontName = "Algerian"
font2.Size = 15;
# Returns a RichText object from a specified cell
richText = sheet.Range["A1"].RichText
# Set the text of RichText object
richText.Text = "Buy One, Get One Free"
# Apply the first font to specified range of characters
richText.SetFont(0, 16, font1)
# Apply the second font to specified range of characters
richText.SetFont(17, 21, font2)
# Set column width
sheet.Columns[0].ColumnWidth = 33
# Save the workbook to an Excel file
workbook.SaveToFile("output/ApplyMultipleFontsInSingleCell.xlsx", ExcelVersion.Version2016)

Change the Font Style of a Cell Range in Python
Spire.XLS for Python offers the CellStyle class, enabling users to handle cell formatting like fill color, text alignment, and font style. By creating a cell style, you can apply it to a specific range of cells using the CellRange.ApplyStyle() method or to an entire worksheet using the Worksheet.ApplyStyle() method. To change the font style of a cell range using Spire.XLS for Python, follow these steps.
- Create a Workbook object.
- Load a sample Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet using Workbook.Worksheets[index] property.
- Create a CellStyle object using Workbook.Styles.Add() method, and set the font style through the CellStyle.Font property.
- Apply the cell style to a cell range using CellRange.ApplyStyle() method.
- Save the workbook to another Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Create a CellStyle object
fontStyle = workbook.Styles.Add("headerFontStyle")
# Set the font color, size and style
fontStyle.Font.Color = Color.get_White()
fontStyle.Font.IsBold = True
fontStyle.Font.Size = 12
# Create a CellStyleFlag object, setting the FontColor, FontBold, ad FontSize properties to true
flag = CellStyleFlag()
flag.FontColor = True
flag.FontBold = True
flag.FontSize = True
# Apply the cell style to header row
sheet.Range[1, 1, 1, 8].ApplyStyle(fontStyle, flag)
# Apply the cell style to the whole worksheet
# sheet.ApplyStyle(fontStyle)
# Save the workbook to another Excel file
workbook.SaveToFile("output/ApplyFontToCellRange.xlsx", ExcelVersion.Version2016)

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Converting Excel spreadsheets to image formats can be extremely valuable and versatile in a wide range of situations. Whether you need to share data with others who don’t have Excel installed on their devices, present information in a document or presentation, or publish content online, converting Excel to image format offers a convenient solution. In this article, we will introduce how to programmatically convert Excel to images in Python using Spire.XLS for Python.
- Convert an Excel Worksheet to an Image in Python
- Convert an Excel Worksheet to an Image without White Margins in Python
- Convert a Specific Cell Range to an Image in Python
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Convert an Excel Worksheet to an Image in Python
You can easily convert a whole Excel worksheet to an image by using the Worksheet.SaveToImage() method provided by Spire.XLS for Python. The detailed steps are as follows:
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index using Workbook.Worksheets[int index] property.
- Convert the worksheet to an image using Worksheet.ToImage() method.
- Save the image to a PNG file (you can also save the image as other image formats such as JPG and BMP).
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Save the worksheet to an image
image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn)
# Save the image to a PNG file
image.Save("SheetToImage.png")
workbook.Dispose()

Convert an Excel Worksheet to an Image without White Margins in Python
When converting an Excel worksheet to an image, you may find the resulting image has unwanted white margins surrounding the cells. If you want to convert the worksheet to an image without any extraneous margins, you can remove the page margins set in the original worksheet. The detailed steps are as follows:
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index using Workbook.Worksheets[int index] property.
- Remove all margins from the worksheet by setting its left, right, top, and bottom margin values to zero.
- Convert the worksheet to an image using Worksheet.ToImage() method.
- Save the image to a PNG file.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Set all margins of the worksheet to zero
sheet.PageSetup.LeftMargin = 0
sheet.PageSetup.BottomMargin = 0
sheet.PageSetup.TopMargin = 0
sheet.PageSetup.RightMargin = 0
# Convert the worksheet to an image
image = sheet.ToImage(sheet.FirstRow, sheet.FirstColumn, sheet.LastRow, sheet.LastColumn)
# Save the image to a PNG file
image.Save("SheetToImageWithoutMargins.png")
workbook.Dispose()

Convert a Specific Cell Range to an Image in Python
In addition to converting a whole worksheet to an image, Spire.XLS for Python also supports converting a specific cell range of a worksheet to an image. The detailed steps are as follows:
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet by its index using Workbook.Worksheets[int index] property.
- Convert a specific cell range of the worksheet to an image using Worksheet.ToImage() method and pass the index of the start row, start column, end row, and end column of the cell range to the method as parameters.
- Save the image to a PNG file.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("Sample.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Convert a specific cell range of the worksheet to an image
image = sheet.ToImage(5, 2, 17, 5)
# Save the image to a PNG file
image.Save("CellRangeToImage.png")
workbook.Dispose()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Inserting or deleting images in Excel can be a powerful way to enhance your spreadsheets and make them visually appealing. Whether you want to include logos, charts, diagrams, or any other graphical elements, Excel provides the functionality to seamlessly integrate images into your worksheets. Additionally, Excel offers the options to manipulate and organize images, allowing you to resize, move, or delete them as needed. In this article, we will explore how to programmatically insert or delete pictures in Excel in Python by using Spire.XLS for Python.
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Insert a Picture to a Specific Cell in Python
To add a picture to a certain cell, you use Worksheet.Pictures.Add(int topRow, int leftColumn, Image image) method. The following are the detailed steps.
- Initialize a Workbook instance.
- Get a specific worksheet through Workbook.Worksheets[sheetIndex] property.
- Insert a picture into a specific cell using Worksheet.Pictures.Add() method and return an object of ExcelPicture.
- Set the width and height of the picture, as well as the distance between the picture and the cell border through the properties under the ExcelPicture object.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first worksheet.
sheet = workbook.Worksheets[0]
# Add a picture to a specific cell
imgPath = "C:\\Users\\Administrator\\Desktop\\logo.png"
picture = sheet.Pictures.Add(1, 3, imgPath)
# Set the picture width and height
picture.Width = 150
picture.Height = 150
# Adjust the column width and row height so that the cell can accommodate the picture
sheet.Columns[2].ColumnWidth = 25
sheet.Rows[0].RowHeight = 135
# Set the distance between cell border and image
picture.LeftColumnOffset = 90
picture.TopRowOffset = 20
# Save to file
workbook.SaveToFile("output/InsertImage.xlsx", ExcelVersion.Version2013)
workbook.Dispose()

Delete Pictures in a Worksheet in Python
A picture in a worksheet can be removed using Worksheet.Pictures[imgIndex].Remove() method. To delete all pictures, you can use a for loop to iterate through the pictures in the worksheet. The following are the detailed steps.
- Create a Workbook object.
- Load an Excel file using Workbook.LoadFromFile() method.
- Get a specific worksheet through Workbook.Worksheets[sheetIndex] property.
- Delete images in the worksheet using Worksheet.Pictures[imgIndex].Remove() method.
- Save the workbook to another Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Load an Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\InsertImage.xlsx")
# Get the first worksheet
sheet = workbook.Worksheets[0]
# Delete all pictures from the worksheet
for i in range(sheet.Pictures.Count - 1, -1, -1):
sheet.Pictures[i].Remove()
# Delete a specific picture
# sheet.Pictures[imgIndex].Remove()
# Save to file
workbook.SaveToFile("output/DeleteImage.xlsx", ExcelVersion.Version2013)
workbook.Dispose()
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Nowadays, digital documents play a significant role in our daily lives, both in personal and professional settings. One such common format is Microsoft Word - used for creating and editing textual documents. However, there may come a time when you need to convert your Word files into a more universally accessible format, such as PDF. PDFs offer advantages like preserving formatting, ensuring compatibility, and maintaining document integrity across different devices and operating systems. In this article, you will learn how to convert Word to PDF in Python using Spire.Doc for Python.
- Convert Doc or Docx to PDF in Python
- Convert Word to Password-Protected PDF in Python
- Convert Word to PDF with Bookmarks in Python
- Convert Word to PDF with Fonts Embedded in Python
- Set Image Quality When Converting Word to PDF in Python
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Convert Doc or Docx to PDF in Python
Spire.Doc for Python offers the Document.SaveToFile(string fileName, FileFormat fileFormat) method that allows to save Word as PDF, XPS, HTML, RTF, etc. If you just want to save your Word documents as regular PDFs without additional settings, follow the steps below.
- Create a Document object.
- Load a sample Word document using Document.LoadFromFile() method.
- Save the document to PDF using Doucment.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create word document
document = Document()
# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Convert Word to Password-Protected PDF in Python
To convert Word to a Password-Protected PDF, you can utilize the Document.SaveToFile(string fileName, ToPdfParameterList paramList) method, where the ToPdfParameterList parameter allows you to control the conversion process of a Word document into a PDF format. This includes options such as encrypting the document during the conversion. Here are the specific steps to accomplish this task.
- Create a Document object.
- Load a sample Word document using Document.LoadFromFile() method.
- Create a ToPdfParameterList object, which is used to set conversion options.
- Specify the open password and permission password and then set both passwords for the generated PDF using ToPdfParameterList.PdfSecurity.Encrypt() method.
- Save the Word document to PDF with password using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"
# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)
# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Convert Word to PDF with Bookmarks in Python
Adding bookmarks to a document can improve its readability. When creating PDF from Word, you may want to keep the existing bookmarks or create new ones based on the headings. Here are the steps to convert Word to PDF while maintaining bookmarks.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Create a ToPdfParameterList object, which is used to set conversion options.
- Create bookmarks in PDF from the headings in Word by setting ToPdfParameterList.CreateWordBookmarksUsingHeadings to true.
- Save the document to PDF with bookmarks using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parames = ToPdfParameterList()
# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True
# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True
# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Convert Word to PDF with Fonts Embedded in Python
To ensure consistent appearance of a PDF document on any device, you probably need to embed fonts in the generated PDF document. The following are the steps to embed the fonts used in a Word document into the resulting PDF.
- Create a Document object.
- Load a sample Word file using Document.LoadFromFile() method.
- Create a ToPdfParameterList object, which is used to set conversion options.
- Embed fonts in generated PDF through ToPdfParameterList.IsEmbeddedAllFonts property.
- Save the document to PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True
# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Set Image Quality When Converting Word to PDF in Python
When converting a Word document to PDF, it is important to consider the size of the resulting file, especially if it contains numerous high-quality images. You have the option to compress the image quality during the conversion process. To do this, follow the steps below.
- Create a Document object.
- Load a sample Word file using Document.LoadFromFile() method.
- Set the image quality through Document.JPEGQuality property.
- Save the document to PDF using Doucment.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Compress image to 40% of its original quality
document.JPEGQuality = 40
# Preserve original image quality
# document.JPEGQuality = 100
# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()
Get a Free License
To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.
A clustered column chart and a stacked column chart are two variants of column chart. The clustered column chart enables straightforward comparison of values across different categories, while the stacked column chart displays both the total for each category and the proportion of its individual components. In this article, you will learn how to create clustered or stacked column charts in Excel in Python using Spire.XLS for Python.
Install Spire.XLS for Python
This scenario requires Spire.XLS for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.XLS
If you are unsure how to install, please refer to this tutorial: How to Install Spire.XLS for Python on Windows
Create a Clustered Column Chart in Excel in Python
To add a chart to a worksheet, use Worksheet.Chart.Add(ExcelChartType chartType) method. The ExcelChartType enumeration includes various chart types predefined in MS Excel. The following are the steps to add a clustered column chart in Excel using Spire.XLS for Python.
- Create a Workbook object.
- Get a specific worksheet through Workbook.Worksheets[index] property.
- Write data into the specified cells.
- Add a clustered column char to the worksheet using Worksheet.Chart.Add(ExcelChartType.ColumnClustered) method.
- Set the chart data through Chart.DataRange property.
- Set the position, title, and other attributes of the chart through the properties under the Chart object.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first sheet
sheet = workbook.Worksheets[0]
# Set chart data
sheet.Range["A1"].Value = "Product"
sheet.Range["A2"].Value = "Diet Coke"
sheet.Range["A3"].Value = "Mountain Dew"
sheet.Range["A4"].Value = "Diet Pesi"
sheet.Range["A5"].Value = "Cherry Coke"
sheet.Range["B1"].Value = "Store A"
sheet.Range["B2"].NumberValue = 35000
sheet.Range["B3"].NumberValue = 46000
sheet.Range["B4"].NumberValue = 28000
sheet.Range["B5"].NumberValue = 51000
sheet.Range["C1"].Value = "Store B"
sheet.Range["C2"].NumberValue = 41000
sheet.Range["C3"].NumberValue = 32000
sheet.Range["C4"].NumberValue = 38000
sheet.Range["C5"].NumberValue = 40000
# Set cell style
sheet.Range["A1:C1"].RowHeight = 15
sheet.Range["A1:C1"].Style.Color = Color.get_Black()
sheet.Range["A1:C1"].Style.Font.Color = Color.get_White()
sheet.Range["A1:C1"].Style.VerticalAlignment = VerticalAlignType.Center
sheet.Range["A1:C1"].Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.AutoFitColumn(1)
# Add a chart to the sheet
chart = sheet.Charts.Add(ExcelChartType.ColumnClustered)
# Set data range of chart
chart.DataRange = sheet.Range["A1:C5"]
chart.SeriesDataFromRange = False
# Set position of the chart
chart.LeftColumn = 5
chart.TopRow = 1
chart.RightColumn = 14
chart.BottomRow = 21
# Set chart title
chart.ChartTitle = "Store Wise Soda Soft Drink Sales"
chart.ChartTitleArea.IsBold = True
chart.ChartTitleArea.Size = 12
# Set axis title
chart.PrimaryCategoryAxis.Title = "Product"
chart.PrimaryCategoryAxis.Font.IsBold = True
chart.PrimaryCategoryAxis.TitleArea.IsBold = True
chart.PrimaryValueAxis.Title = "Sales"
chart.PrimaryValueAxis.HasMajorGridLines = False
chart.PrimaryValueAxis.TitleArea.IsBold = True
chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90
# Set series color, overlap, gap width and data labels
series = chart.Series
for i in range(len(series)):
cs = series[i]
cs.Format.Options.IsVaryColor = True
cs.Format.Options.Overlap = -50
cs.Format.Options.GapWidth = 350
cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = True
# Set legend position
chart.Legend.Position = LegendPositionType.Top
# Save the document
workbook.SaveToFile("ClusteredColumnChart.xlsx", ExcelVersion.Version2016)

Create a Stacked Column Chart in Excel in Python
The process of creating a stacked column chart is similar to that of creating a clustered column chart. The only difference is that you must change the Excel chart type from ColumnClustered to ColumnStacked.
- Create a Workbook object.
- Get a specific worksheet through Workbook.Worksheets[index] property.
- Write data into the specified cells.
- Add a clustered column char to the worksheet using Worksheet.Chart.Add(ExcelChartType.ColumnStacked) method.
- Set the chart data through Chart.DataRange property.
- Set the position, title, and other attributes of the chart through the properties under the Chart object.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
workbook = Workbook()
# Get the first sheet
sheet = workbook.Worksheets[0]
# Set chart data
sheet.Range["A1"].Value = "Product"
sheet.Range["A2"].Value = "Diet Coke"
sheet.Range["A3"].Value = "Mountain Dew"
sheet.Range["A4"].Value = "Diet Pesi"
sheet.Range["A5"].Value = "Cherry Coke"
sheet.Range["B1"].Value = "Store A"
sheet.Range["B2"].NumberValue = 35000
sheet.Range["B3"].NumberValue = 46000
sheet.Range["B4"].NumberValue = 28000
sheet.Range["B5"].NumberValue = 51000
sheet.Range["C1"].Value = "Store B"
sheet.Range["C2"].NumberValue = 41000
sheet.Range["C3"].NumberValue = 32000
sheet.Range["C4"].NumberValue = 38000
sheet.Range["C5"].NumberValue = 40000
# Set cell style
sheet.Range["A1:C1"].RowHeight = 15
sheet.Range["A1:C1"].Style.Color = Color.get_Black()
sheet.Range["A1:C1"].Style.Font.Color = Color.get_White()
sheet.Range["A1:C1"].Style.VerticalAlignment = VerticalAlignType.Center
sheet.Range["A1:C1"].Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.AutoFitColumn(1)
# Add a chart to the sheet
chart = sheet.Charts.Add(ExcelChartType.ColumnStacked)
# Set data range of chart
chart.DataRange = sheet.Range["A1:C5"]
chart.SeriesDataFromRange = False
# Set position of the chart
chart.LeftColumn = 5
chart.TopRow = 1
chart.RightColumn = 14
chart.BottomRow = 21
# Set chart title
chart.ChartTitle = "Store Wise Soda Soft Drink Sales"
chart.ChartTitleArea.IsBold = True
chart.ChartTitleArea.Size = 12
# Set axis title
chart.PrimaryCategoryAxis.Title = "Product"
chart.PrimaryCategoryAxis.Font.IsBold = True
chart.PrimaryCategoryAxis.TitleArea.IsBold = True
chart.PrimaryValueAxis.Title = "Sales"
chart.PrimaryValueAxis.HasMajorGridLines = False
chart.PrimaryValueAxis.TitleArea.IsBold = True
chart.PrimaryValueAxis.TitleArea.TextRotationAngle = 90
# Set series color, gap width and data labels
series = chart.Series
for i in range(len(series)):
cs = series[i]
cs.Format.Options.IsVaryColor = True
cs.Format.Options.GapWidth = 270
cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = True
cs.DataPoints.DefaultDataPoint.DataLabels.Position = DataLabelPositionType.Inside
# Set legend position
chart.Legend.Position = LegendPositionType.Top
# Save the document
workbook.SaveToFile("StackedColumnChart.xlsx", ExcelVersion.Version2016)

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.


