A page break is a markup that divides the content of a document or spreadsheet into multiple pages for printing or display. This feature can be used to adjust the page layout of a document to ensure that each page contains the appropriate information. By placing page breaks appropriately, you can also ensure that your document is presented in a better format and layout when printed. This article will explain how to insert or remove horizontal/vertical page breaks in Excel on the Python platform 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 commands.

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 Horizontal Page Breaks in Excel Using Python

Spire.XLS for Python supports inserting horizontal page breaks to specified cell ranges by calling Worksheet.HPageBreaks.Add(CellRange) method. The following are detailed steps.

  • Create a Workbook instance.
  • Load an Excel file from disk using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Insert horizontal page breaks to specified cell ranges using Worksheet.HPageBreaks.Add(CellRange) method.
  • Set view mode to Preview mode by Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/InsertHPageBreak.xlsx"

#Create a Workbook instance
workbook = Workbook()

#Load an Excel file from disk
workbook.LoadFromFile(inputFile)

#Get the first worksheet of this file
sheet = workbook.Worksheets[0]

#Insert horizontal page breaks to specified cell ranges
sheet.HPageBreaks.Add(sheet.Range["A12"])
sheet.HPageBreaks.Add(sheet.Range["A20"])

#Set view mode to Preview mode
sheet.ViewMode = ViewMode.Preview

#Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Insert or Remove Page Breaks in Excel

Insert Vertical Page Breaks in Excel Using Python

Spire.XLS for Python also supports inserting vertical page breaks to specified cell ranges by calling Worksheet.VPageBreaks.Add(CellRange) method. The following are detailed steps.

  • Create a Workbook instance.
  • Load an Excel file from disk using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Insert vertical page breaks to specified cell ranges using Worksheet.VPageBreaks.Add(CellRange) method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/InsertVPageBreak.xlsx"

#Create a Workbook instance
workbook = Workbook()

#Load an Excel file from disk
workbook.LoadFromFile(inputFile)

#Get the first worksheet of this file
sheet = workbook.Worksheets[0]

#Insert vertical page breaks to specified cell ranges
sheet.VPageBreaks.Add(sheet.Range["B1"])
sheet.VPageBreaks.Add(sheet.Range["D3"])

#Set view mode to Preview mode
sheet.ViewMode = ViewMode.Preview

#Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Insert or Remove Page Breaks in Excel

Remove Horizontal Page Breaks from Excel Using Python

If you want to remove horizontal page breaks from Excel, call the Worksheet.HPageBreaks.RemoveAt() or Worksheet.HPageBreaks.Clear() methods. The following are detailed steps.

  • Create a Workbook instance.
  • Load an Excel file from disk using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Remove all the horizontal page breaks by calling Worksheet.HPageBreaks.Clear() method or remove a specific horizontal page break by calling Worksheet.HPageBreaks.RemoveAt() method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/InsertHPageBreak.xlsx"
outputFile = "C:/Users/Administrator/Desktop/RemoveHPageBreak.xlsx"

#Create a Workbook instance
workbook = Workbook()

#Load an Excel file from disk
workbook.LoadFromFile(inputFile)

#Get the first worksheet from this file
sheet = workbook.Worksheets[0]

#Clear all the horizontal page breaks
#sheet.HPageBreaks.Clear()

#Remove the first horizontal page break
sheet.HPageBreaks.RemoveAt(0)

#Set view mode to Preview mode
sheet.ViewMode = ViewMode.Preview

#Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Insert or Remove Page Breaks in Excel

Remove Vertical Page Breaks from Excel Using Python

If you want to remove vertical page breaks from Excel, call the Worksheet.VPageBreaks.RemoveAt() or Worksheet.VPageBreaks.Clear() methods. The following are detailed steps.

  • Create a Workbook instance.
  • Load an Excel file from disk using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Remove all the vertical page breaks by calling Worksheet.VPageBreaks.Clear() method or remove a specific vertical page break by calling Worksheet.VPageBreaks.RemoveAt() method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/InsertVPageBreak.xlsx"
outputFile = "C:/Users/Administrator/Desktop/RemoveVPageBreak.xlsx"

#Create a Workbook instance
workbook = Workbook()

#Load an Excel file from disk
workbook.LoadFromFile(inputFile)

#Get the first worksheet from this file
sheet = workbook.Worksheets[0]

#Clear all the vertical page breaks
#sheet.VPageBreaks.Clear()

#Remove the first vertical page break
sheet.VPageBreaks.RemoveAt(0)

#Set view mode to Preview mode
sheet.ViewMode = ViewMode.Preview

#Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Insert or Remove Page Breaks in Excel

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.

In the context of Excel, Open XML refers to the underlying file format used by Excel to store spreadsheet data, formatting, formulas, and other related information. It provides a powerful and flexible basis for working with Excel files programmatically.

By converting Excel to Open XML, developers gain greater control and automation when working with spreadsheet-related tasks. In turn, you can also generate Excel files from Open XML to take advantage of Excel's built-in capabilities to perform advanced data operations. In this article, you will learn how to convert Excel to Open XML or Open XML 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

Convert Excel to Open XML in Python

Spire.XLS for Python offers the Workbook.SaveAsXml() method to save an Excel file in Open XML format. The following are the detailed steps.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Save the Excel file in Open XML format using Workbook.SaveAsXml() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel file 
workbook.LoadFromFile("sample.xlsx")

# Save the Excel file in Open XML file format
workbook.SaveAsXml("ExcelToXML.xml")
workbook.Dispose()

Python: Convert Excel to Open XML or Open XML to Excel

Convert Open XML to Excel in Python

To convert an Open XML file to Excel, you need to load the Open XML file through the Workbook.LoadFromXml() method, and then call the Workbook.SaveToFile() method to save it as an Excel file. The following are the detailed steps.

  • Create a Workbook object.
  • Load an Open XML file using Workbook.LoadFromXml() method.
  • Save the Open XML file to Excel using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Open XML file
workbook.LoadFromXml("ExcelToXML.xml")

# Save the Open XML file to Excel XLSX format
workbook.SaveToFile("XMLToExcel.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Convert Excel to Open XML or Open XML to Excel

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.

Python: Edit or Remove Comments in Excel

2023-12-26 01:03:13 Written by Koohji

Comment in Excel is primarily used to add additional instructions or notes to cells. With this feature, users can add relevant content next to a specific cell to explain the data, provide contextual information, or give instructions. It also helps users to better organize and manage the data in the Excel workbook and improve the understanding and readability of the data. Spire.XLS for Python supports adding comments to Excel files. If necessary, you can also use this library to edit the content of the comments or delete unnecessary comments. In this article, we will show you how to edit or remove existing comments in Excel on Python platforms 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 commands.

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

Edit Existing Comments in Excel Using Python

Spire.XLS for Python allows users to edit existing comments in Excel, including setting new text or changing comment box size. The following are detailed steps.

  • Create a Workbook instance.
  • Load an Excel file from disk using Workbook.LoadFromFile() method.
  • Get the first worksheet of the Excel file using Workbook.Worksheets[] property.
  • Set new text for the existing comments using Worksheet.Range[].Comment.Text property.
  • Set the height and width of the existing comment by using Worksheet.Range[].Comment.Height and Worksheet.Range[].Comment.Width properties.
  • Automatically adapt to the size of the comment by setting the Worksheet.Range.Comment.AutoSize property to "True".
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/EditExcelComment.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an Excel file from disk
workbook.LoadFromFile(inputFile)

# Get the first worksheet of this file
sheet = workbook.Worksheets[0]

# Set new text for the existing comments 
sheet.Range["A8"].Comment.Text = "Frank has left the company."
sheet.Range["F6"].Comment.Text = "Best sales."

# Set the height and width of the comment of A8
sheet.Range["A8"].Comment.Height = 60
sheet.Range["A8"].Comment.Width = 100

# Automatically adapt to the size of the comment of F6
sheet.Range["F6"].Comment.AutoSize = True

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Edit or Remove Comments in Excel

Remove Existing Comments from Excel Using Python

The Worksheet.Range[].Comment.Remove() method offered by Spire.XLS for Python allows users to remove a specified comment easily. The detailed steps are as follows.

  • Create a Workbook instance.
  • Load an Excel file from disk using Workbook.LoadFromFile() method.
  • Get the first worksheet of the Excel file using Workbook.Worksheets[] property.
  • Remove the comment by using Worksheet.Range[].Comment.Remove() method.
  • Save the document to another file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/RemoveExcelComment.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an Excel file from disk
workbook.LoadFromFile(inputFile)

# Get the first worksheet of this file
sheet = workbook.Worksheets[0]

# Remove the comment from the sheet
sheet.Range["F6"].Comment.Remove()

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Edit or Remove Comments in Excel

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.

Python: Create a Bar Chart in Excel

2023-12-25 01:32:30 Written by Koohji

A bar chart is a type of graph that represents categorical data using rectangular bars. It is somewhat like a column chart, but with bars that extend horizontally from the Y-axis. The length of each bar corresponds to the value represented by a particular category or group, and changes, trends, or rankings can be quickly identified by comparing the lengths of the bars. In this article, you will learn how to create a clustered or stacked bar chart 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 Bar Chart in Excel in Python

The Worksheet.Chart.Add(ExcelChartType chartType) method provided by Spire.XLS for Python allows to add a chart to a worksheet. To add a clustered bar chart in Excel, you can set the chart type to BarClustered. The following are the steps.

  • Create a Workbook object.
  • Get a specific worksheet using Workbook.Worksheets[index] property.
  • Add chart data to specified cells and set the cell styles.
  • Add a clustered bar char to the worksheet using Worksheet.Chart.Add(ExcelChartType.BarClustered) method.
  • Set data range for the chart using Chart.DataRange property.
  • Set position, title, category axis and value axis for the chart.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.common import *
from spire.xls import *

# Create a Workbook instance
workbook = Workbook()

# Get the first sheet and set its name
sheet = workbook.Worksheets[0]
sheet.Name = "ClusteredBar"

# Add chart data to specified cells
sheet.Range["A1"].Value = "Quarter"
sheet.Range["A2"].Value = "Q1"
sheet.Range["A3"].Value = "Q2"
sheet.Range["A4"].Value = "Q3"
sheet.Range["A5"].Value = "Q4"
sheet.Range["B1"].Value = "Team A"
sheet.Range["B2"].NumberValue = 3000
sheet.Range["B3"].NumberValue = 8000
sheet.Range["B4"].NumberValue = 9000
sheet.Range["B5"].NumberValue = 8500
sheet.Range["C1"].Value = "Team B"
sheet.Range["C2"].NumberValue = 7000
sheet.Range["C3"].NumberValue = 2000
sheet.Range["C4"].NumberValue = 5000
sheet.Range["C5"].NumberValue = 4200

# Set cell style
sheet.Range["A1:C1"].RowHeight = 18
sheet.Range["A1:C1"].Style.Color = Color.get_Black()
sheet.Range["A1:C1"].Style.Font.Color = Color.get_White()
sheet.Range["A1:C1"].Style.Font.IsBold = True
sheet.Range["A1:C1"].Style.VerticalAlignment = VerticalAlignType.Center
sheet.Range["A1:C1"].Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.Range["A2:A5"].Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.Range["B2:C5"].Style.NumberFormat = "\"$\"#,##0"

# Add a clustered bar chart to the sheet
chart = sheet.Charts.Add(ExcelChartType.BarClustered)

# Set data range of the chart
chart.DataRange = sheet.Range["A1:C5"]
chart.SeriesDataFromRange = False

# Set position of the chart
chart.LeftColumn = 1
chart.TopRow = 6
chart.RightColumn = 11
chart.BottomRow = 29

# Set and format chart title
chart.ChartTitle = "Team Sales Comparison per Quarter"
chart.ChartTitleArea.IsBold = True
chart.ChartTitleArea.Size = 12

# Set and format category axis
chart.PrimaryCategoryAxis.Title = "Country"
chart.PrimaryCategoryAxis.Font.IsBold = True
chart.PrimaryCategoryAxis.TitleArea.IsBold = True
chart.PrimaryCategoryAxis.TitleArea.TextRotationAngle = 90

# Set and format value axis
chart.PrimaryValueAxis.Title = "Sales (in Dollars)"
chart.PrimaryValueAxis.HasMajorGridLines = False
chart.PrimaryValueAxis.MinValue = 1000
chart.PrimaryValueAxis.TitleArea.IsBold = True

# Show data labels for data points
for cs in chart.Series:
    cs.Format.Options.IsVaryColor = True
    cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = True

# Set legend position
chart.Legend.Position = LegendPositionType.Top

#Save the result file
workbook.SaveToFile("ClusteredBarChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Create a Bar Chart in Excel

Create a Stacked Bar Chart in Excel in Python

To create a stacked bar chart, you just need to change the Excel chart type to BarStacked. The following are the steps.

  • Create a Workbook object.
  • Get a specific worksheet using Workbook.Worksheets[index] property.
  • Add chart data to specified cells and set the cell styles.
  • Add a clustered bar char to the worksheet using Worksheet.Chart.Add(ExcelChartType.BarStacked) method.
  • Set data range for the chart using Chart.DataRange property.
  • Set position, title, category axis and value axis for the chart.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.common import *
from spire.xls import *

# Create a Workbook instance
workbook = Workbook()

# Get the first sheet and set its name
sheet = workbook.Worksheets[0]
sheet.Name = "StackedBar"

# Add chart data to specified cells
sheet.Range["A1"].Value = "Quarter"
sheet.Range["A2"].Value = "Q1"
sheet.Range["A3"].Value = "Q2"
sheet.Range["A4"].Value = "Q3"
sheet.Range["A5"].Value = "Q4"
sheet.Range["B1"].Value = "Team A"
sheet.Range["B2"].NumberValue = 3000
sheet.Range["B3"].NumberValue = 8000
sheet.Range["B4"].NumberValue = 9000
sheet.Range["B5"].NumberValue = 8500
sheet.Range["C1"].Value = "Team B"
sheet.Range["C2"].NumberValue = 7000
sheet.Range["C3"].NumberValue = 2000
sheet.Range["C4"].NumberValue = 5000
sheet.Range["C5"].NumberValue = 4200

# Set cell style
sheet.Range["A1:C1"].RowHeight = 18
sheet.Range["A1:C1"].Style.Color = Color.get_Black()
sheet.Range["A1:C1"].Style.Font.Color = Color.get_White()
sheet.Range["A1:C1"].Style.Font.IsBold = True
sheet.Range["A1:C1"].Style.VerticalAlignment = VerticalAlignType.Center
sheet.Range["A1:C1"].Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.Range["A2:A5"].Style.HorizontalAlignment = HorizontalAlignType.Center
sheet.Range["B2:C5"].Style.NumberFormat = "\"$\"#,##0"

# Add a clustered bar chart to the sheet
chart = sheet.Charts.Add(ExcelChartType.BarStacked)

# Set data range of the chart
chart.DataRange = sheet.Range["A1:C5"]
chart.SeriesDataFromRange = False

# Set position of the chart
chart.LeftColumn = 1
chart.TopRow = 6
chart.RightColumn = 11
chart.BottomRow = 29

# Set and format chart title
chart.ChartTitle = "Team Sales Comparison per Quarter"
chart.ChartTitleArea.IsBold = True
chart.ChartTitleArea.Size = 12

# Set and format category axis
chart.PrimaryCategoryAxis.Title = "Country"
chart.PrimaryCategoryAxis.Font.IsBold = True
chart.PrimaryCategoryAxis.TitleArea.IsBold = True
chart.PrimaryCategoryAxis.TitleArea.TextRotationAngle = 90

# Set and format value axis
chart.PrimaryValueAxis.Title = "Sales (in Dollars)"
chart.PrimaryValueAxis.HasMajorGridLines = False
chart.PrimaryValueAxis.MinValue = 1000
chart.PrimaryValueAxis.TitleArea.IsBold = True

# Show data labels for data points
for cs in chart.Series:
    cs.Format.Options.IsVaryColor = True
    cs.DataPoints.DefaultDataPoint.DataLabels.HasValue = True

# Set legend position
chart.Legend.Position = LegendPositionType.Top

#Save the result file
workbook.SaveToFile("StackedBarChart.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Create a Bar Chart in Excel

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.

Python: Lock Specific Cells in Excel

2023-12-18 01:53:04 Written by Koohji

Locking cells is often used to protect the contents of specific cell ranges in a spreadsheet from accidental modification, which is useful in situations such as sharing a worksheet or protecting specific data. When you lock a cell, no one else can edit it unless they know the password or have the appropriate permissions. This feature is important for data security and integrity. In this article, we will show you how to lock specific cells, columns or rows in Excel on python platforms 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 commands.

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

Lock Specific Cells in Python

Spire.XLS for Python supports users to lock a specified range of cells by setting the Worksheet.Range[].Style.Locked property to "True". Below are the detailed steps.

  • Create a Workbook instance and load a sample excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet using Workbook.Worksheets[] property.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "False".
  • Set text for the specific cells using Worksheet.Range[].Text property and then lock them by setting the Worksheet.Range[].Style.Locked property to "True".
  • Protect the worksheet using XlsWorksheetBase.Protect() method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/LockSpecificCells.xlsx"

# Create a Workbook instance and load a sample file
workbook = Workbook()
workbook.LoadFromFile(inputFile)

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Unlock all cells in the used range of the worksheet
sheet.Range.Style.Locked = False

# Lock a specific cell in the sheet
sheet.Range["A1"].Text = "Locked"
sheet.Range["A1"].Style.Locked = True

# Lock a specific range of cells in the sheet
sheet.Range["C1:E3"].Text = "Locked"
sheet.Range["C1:E3"].Style.Locked = True

# Protect the worksheet with a password
sheet.Protect("123456", SheetProtectionType.All)

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Lock Specific Cells in Excel

Lock a Specific Column in Python

If you want to lock a specific column in the worksheet, please set the Worksheet.Columns[].Style.Locked property to "True". Other steps are similar to the above method. Below are the detailed steps.

  • Create a Workbook instance and load a sample excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet using Workbook.Worksheets[] property.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "False".
  • Set text for the fourth column using the Worksheet.Columns[].Text property and then lock it by setting the Worksheet.Columns[].Style.Locked property to "True".
  • Protect the worksheet with a password by calling XlsWorksheetBase.Protect() method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/LockSpecificColumn.xlsx"

# Create a Workbook instance and load a sample file
workbook = Workbook()
workbook.LoadFromFile(inputFile)

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Unlock all cells in the used range of the worksheet
sheet.Range.Style.Locked = False

# Lock the fourth column in the sheet
sheet.Columns[3].Text = "Locked"
sheet.Columns[3].Style.Locked = True

# Protect the worksheet with a password
sheet.Protect("123456", SheetProtectionType.All)

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Lock Specific Cells in Excel

Lock a Specific Row in Python

Similarly, if you want to lock a certain row, please set the Worksheet.Rows[].Style.Locked property to "True". Here are the detailed steps.

  • Create a Workbook instance and load a sample excel file using Workbook.LoadFromFile() method.
  • Get the first worksheet using Workbook.Worksheets[] property.
  • Unlock all cells in the used range of the worksheet by setting the Worksheet.Range.Style.Locked property to "False".
  • Set text for the third row using the Worksheet.Rows[].Text property and then lock it by setting the Worksheet.Rows[].Style.Locked property to "True".
  • Protect the worksheet with a password using XlsWorksheetBase.Protect() method.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.xlsx"
outputFile = "C:/Users/Administrator/Desktop/LockSpecificRow.xlsx"

# Create a Workbook instance and load a sample file
workbook = Workbook()
workbook.LoadFromFile(inputFile)

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Unlock all cells in the used range of the worksheet
sheet.Range.Style.Locked = False

# Lock the third row in the worksheet
sheet.Rows[2].Text = "Locked"
sheet.Rows[2].Style.Locked = True

# Protect the worksheet with a password
sheet.Protect("123456", SheetProtectionType.All)

# Save the result file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Lock Specific Cells in Excel

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.

OLE enables users to incorporate diverse file types-such as images, charts, documents, and multimedia-directly into Excel workbooks, fostering a more dynamic and comprehensive representation of information. By inserting OLE objects, users can create interactive and engaging spreadsheets that integrate a variety of data formats to simplify analyses and presentations in a single Excel environment. In this article, you will learn how to insert linked or embedded OLE objects to Excel in Python as well as how to extract OLE objects from 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

Insert a Linked OLE Object to Excel in Python

To insert an OLE object to a worksheet, you use the Worksheet.OleObjects.Add(fileName, image, linkType) method, in which:

  • the fileName parameter specifies the path of an external file to be inserted,
  • the image parameter specifies a thumbnail of the first page or a document icon that the OLE object will be displayed as,
  • the linkType parameter determines whether the OLE object is inserted to the document as an embedded source or a linked source.

The following are the steps to insert a linked OEL object to Excel using Spire.XLS for Python.

  • Create a Workbook object.
  • Get the first worksheet through Workbook.Worksheet[index] property.
  • Load an image using Image.FromFile() method.
  • Insert an OLE object to the worksheet using Worksheet.OleObjects.Add() method, and specify the link type as OleLinkType.Link.
  • Specify the OLE object location through IOleObject.Location property.
  • Specify the OLE object type through IOleObject.ObjectType property.
  • 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 text to A1
sheet.Range["A1"].Text = "Here is an OLE Object."

# Load an image to be displayed as an icon of ole object
image = Image.FromFile("C:/Users/Administrator/Desktop/word_icon.png") 
with Stream() as stream:
    image.Save(stream,ImageFormat.get_Png())

    # Add an ole object to the worksheet that links to an external file
    oleObject = sheet.OleObjects.Add("C:/Users/Administrator/Desktop/invoice.docx", stream, OleLinkType.Link)

# Specify ole object location
oleObject.Location = sheet.Range["B3"]

# Specify ole object type
oleObject.ObjectType = OleObjectType.WordDocument

# Save to file
workbook.SaveToFile("output/OleObject.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Insert or Extract OLE Objects in Excel

Insert an Embedded OLE Object to Excel in Python

To insert an embedded OEL object to Excel, you specify the link type as OleLinkType.Embed while invoking the Worksheet.OleObjects.Add() method. The detailed steps are as follows.

  • Create a Workbook object.
  • Get the first worksheet through Workbook.Worksheet[index] property.
  • Load an image using Image.FromFile() method.
  • Insert an OLE object to the worksheet using Worksheet.OleObjects.Add() method, and specify the link type as OleLinkType.Embed.
  • Specify the OLE object location through IOleObject.Location property.
  • Specify the OLE object type through IOleObject.ObjectType property.
  • 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 text to A1
sheet.Range["A1"].Text = "Here is an OLE Object."

# Load an image that represents ole object
image = Image.FromFile("C:/Users/Administrator/Desktop/screenshot.png") 
with Stream() as stream:
    image.Save(stream,ImageFormat.get_Png())

    # Add an ole object to the worksheet as embedded source
    oleObject = sheet.OleObjects.Add("C:/Users/Administrator/Desktop/invoice.docx", stream, OleLinkType.Embed)

# Specify ole object location
oleObject.Location = sheet.Range["B3"]

# Specify ole object type
oleObject.ObjectType = OleObjectType.WordDocument

# Save to file
workbook.SaveToFile("output/OleObject.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Insert or Extract OLE Objects in Excel

Extract OLE Objects from Excel in Python

Spire.XLS for Python provides the Worksheet.HasOleObjects property to determine whether a worksheet has OLE objects. If it does, get all the objects through the Worksheet.OleObjects property. Then, determine the type of a particular OEL object and save the OEL as a file of the appropriate document type. The following are the steps to extract OLE objects from Excel using Spire.XLS for Python.

  • Create a Workbook object.
  • Get a specific worksheet through Workbook.Worksheet[index] property.
  • Determine if the worksheet contains OLE objects through Worksheet.HasOleObjects property.
  • Get all the OLE objects from the worksheet through Worksheet.OleObjects property.
  • Determine the type of a particular OEL object and save the OEL as a file of the appropriate document type.
  • Python
from spire.xls import *
from spire.xls.common import *

# Write data to file
def WriteAllBytes(fname:str,data):
    fp = open(fname,"wb")
    for d in data:
        fp.write(d)
    fp.close()

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\OleObjects.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Determine if the worksheet has ole objects
if sheet.HasOleObjects:

    # Iterate through the found objects
    for obj in sheet.OleObjects:

        # If the object type is a Word document, save it to a .docx file
        type = obj.ObjectType
        if type is OleObjectType.WordDocument:
            WriteAllBytes("output/ExtractedFiles/Word-Extracted.docx", obj.OleData)

        # If the object type is an Adobe Acrobat document, save it to a .pdf file
        if type is OleObjectType.AdobeAcrobatDocument:
            WriteAllBytes("output/ExtractedFiles/PDF-Extracted.pdf", obj.OleData)

        # If the object type is a PowerPoint document, save it to a .pptx file
        if type is OleObjectType.PowerPointPresentation:
            WriteAllBytes("output/ExtractedFiles/PPT-Extracted.pptx", obj.OleData)
workbook.Dispose()

Python: Insert or Extract OLE Objects in Excel

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.

Python: Find and Replace Data in Excel

2023-12-11 01:14:17 Written by Koohji

The Find and Replace feature in Excel allows you to quickly find specific values and perform targeted replacements based on specific requirements. With it, all occurrences of a specific value can be updated at once, which can significantly improve productivity when working with large data sets. In this article, you will learn how to programmatically find and replace data 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

Find and Replace Data in an Excel Worksheet in Python

Spire.XLS for Python offers the Worksheet.FindAllString() method to find the cells containing specific data values in an Excel worksheet. Once the cells are found, you can use the CellRange.Text property to update their values with new values. The detailed steps are as follows:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[] property.
  • Find the cells containing a specific value in the worksheet using Worksheet.FindAllString() method.
  • Iterate through the found cells.
  • Replace the value of each found cell with another value using CellRange.Text property.
  • Set a background color to highlight the cell using CellRange.Style.Color property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.common import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document from disk
workbook.LoadFromFile("input.xlsx")

# Get the first worksheet
worksheet = workbook.Worksheets[0]

# Find the cells with the specific string value “Total” in the worksheet
ranges = worksheet.FindAllString("Total", False, False)

# Iterate through the found cells
for range in ranges:
    
    # Replace the value of the cell with another value
    range.Text = "Sum"

    # Set a background color for the cell
    range.Style.Color = Color.get_Yellow()
    
# Save the result file
workbook.SaveToFile("FindAndReplaceData.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Find and Replace Data in Excel

Find and Replace Data in a Specific Cell Range in Excel in Python

Spire.XLS for Python also allows you to find the cells containing a specific value in a cell range through the CellRange.FindAllString() method. Then you can update the value of each found cell with another value using the CellRange.Text property. The detailed steps are as follows:

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[] property.
  • Get a specific cell range of the worksheet using Worksheet.Range[] property.
  • Find the cells with a specific value in the cell range using CellRange.FindAllString() method.
  • Iterate through the found cells.
  • Replace the value of each found cell with another value using CellRange.Text property.
  • Set a background color to highlight the cell using CellRange.Style.Color property.
  • Save the result file using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document from disk
workbook.LoadFromFile("input.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Get a specific cell range
range = sheet.Range["A6:C13"]

# Find the cells with the specific value "Total" in the cell range
cells = range.FindAllString("Total", False, False)

# Iterate through the found cells
for cell in cells:

    # Replace the value of the cell with another value
    cell.Text = "Sum"

    # Set a background color for the cell
    cell.Style.Color = Color.get_Yellow()

# Save the result file
workbook.SaveToFile("ReplaceDataInCellRange.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Find and Replace Data in Excel

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.

Deleting rows and columns from Excel is crucial for maintaining clean and organized data. For example, when a worksheet accumulates blank rows or columns that serve no purpose and clutter the data, removing them becomes necessary. By deleting these blank rows and columns, you can effectively reduce the file size and enhance the spreadsheet's readability. In this article, we will explain how to delete rows and columns from 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

Delete a Specific Row and Column from Excel in Python

The Worksheet.DeleteRow(rowIndex) and Worksheet.DeleteColumn(columnIndex) methods provided by Spire.XLS for Python enable you to delete a specific row and column from an Excel worksheet. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Delete the desired row from the worksheet by its index (1-based) using Worksheet.DeleteRow(rowIndex) method.
  • Delete the desired column from the worksheet by its index (1-based) using Worksheet.DeleteColumn(columnIndex) 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()
# Load an Excel file
workbook.LoadFromFile("Input.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Delete the 9th row
sheet.DeleteRow(9)
# Delete the 3rd column
sheet.DeleteColumn(3)

# Save the result file
workbook.SaveToFile("DeleteSpecificRowAndColumn.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Delete Rows and Columns from Excel

Delete Multiple Rows and Columns from Excel in Python

Spire.XLS for Python enables you to delete multiple adjacent rows and columns from an Excel worksheet at once by using the Worksheet.DeleteRow(startRowIndex, rowCount) and Worksheet.DeleteColumn(startColumnIndex, columnCount) methods. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Delete the desired rows from the worksheet using Worksheet.DeleteRow(startRowIndex, rowCount) method.
  • Delete the desired columns from the worksheet using Worksheet.DeleteColumn(startColumnIndex, columnCount) 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()
# Load an Excel file
workbook.LoadFromFile("Input.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Delete the 5th, 6th and 7th rows
sheet.DeleteRow(5, 3)
# Delete the 3rd and 4th columns
sheet.DeleteColumn(3, 2)

# Save the result file
workbook.SaveToFile("DeleteMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Delete Rows and Columns from Excel

Delete Blank Rows and Columns from Excel in Python

You can use the Worksheet.Row[rowIndex].IsBlank and Worksheet.Column[columnIndex].IsBlank properties to detect whether a specific row and column are blank or not. If the result is True, you can remove them from your woeksheet using the Worksheet.DeleteRow(rowIndex) and Worksheet.DeleteColumn(columnIndex) methods.

The following steps show how to delete the blank rows and columns from an Excel worksheet.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Loop through the used rows in the worksheet.
  • Find the blank rows using Worksheet.Row[rowIndex].IsBlank property and then delete them from the worksheet using Worksheet.DeleteRow(rowIndex) method.
  • Loop through the used columns in the worksheet.
  • Find the blank columns using Worksheet.Column[columnIndex].IsBlank property and then delete them from the worksheet using Worksheet.DeleteColumn(columnIndex) 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()
# Load an Excel file
workbook.LoadFromFile("Input1.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Delete blank rows from the worksheet
for i in range(sheet.Rows.Length - 1, -1, -1):
    if sheet.Rows[i].IsBlank:
        sheet.DeleteRow(i + 1)

# Delete blank columns from the worksheet
for j in range(sheet.Columns.Length - 1, -1, -1):
    if sheet.Columns[j].IsBlank:
        sheet.DeleteColumn(j + 1)

# Save the result file
workbook.SaveToFile("DeleteBlankRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Delete Rows and Columns from Excel

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.

If you need to display or interact with the contents of an Excel spreadsheet on a web page, converting Excel to HTML is a good choice. This conversion allows users to view and manipulate the table data directly on the web page without having to download the Excel file, providing a more convenient way to share and display the data. When needed, you can also convert the HTML file back to Excel format for better data editing. In this article, we will show you how to convert Excel to HTML and HTML to 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 commands.

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 Excel to HTML in Python

Spire.XLS for Python supports converting a specific Excel worksheet to HTML using Worksheet.SaveToHtml() method. Detailed steps are listed below.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[] property.
  • Save the worksheet as an HTML file using Worksheet.SaveToHtml() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample_1.xlsx"
outputFile = "C:/Users/Administrator/Desktop/ToHtml.html"

# Create a Workbook instance
workbook = Workbook()

# Load a sample Excel file
workbook.LoadFromFile(inputFile)

# Get the first sheet of this file
sheet = workbook.Worksheets[0]

# Save the worksheet to HTML
sheet.SaveToHtml(outputFile)
workbook.Dispose()

Python: Convert Excel to HTML and Vice Versa

Convert Excel to HTML with Images Embedded in Python

If the Excel file you want to convert contains images, you can embed the images into the HTML file by setting the ImageEmbedded property to "True". Detailed steps are listed below.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet using Workbook.Worksheets[] property.
  • Create an HTMLOptions instance.
  • Set the ImageEmbedded as “True” to embed images to HTML.
  • Save the worksheet as an HTML file using Worksheet.SaveToHtml() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample_2.xlsx"
outputFile = "C:/Users/Administrator/Desktop/ToHtmlwithImages.html"

# Create a Workbook instance
workbook = Workbook()

# Load a sample Excel file
workbook.LoadFromFile(inputFile)

# Get the first sheet of this file
sheet = workbook.Worksheets[0]

# Create an HTMLOptions instance
options = HTMLOptions()

# Embed images to HTML
options.ImageEmbedded = True

# Save the worksheet to HTML
sheet.SaveToHtml(outputFile, options)
workbook.Dispose()

Python: Convert Excel to HTML and Vice Versa

Convert HTML to Excel in Python

You are also allowed to convert an HTML back to an Excel file by calling the Workbook.SaveToFile() method provided by Spire.XLS for Python. Detailed steps are listed below.

  • Create a Workbook instance.
  • Load an HTML file from disk using Workbook.LoadFromFile() method.
  • Save the HTML file to an Excel file by using Workbook.SaveToFile() method.
  • Python
from spire.xls import *
from spire.xls.common import *

inputFile = "C:/Users/Administrator/Desktop/Sample.html"
outputFile = "C:/Users/Administrator/Desktop/ToExcel.xlsx"

# Create a Workbook instance
workbook = Workbook()

# Load an HTML file from disk
workbook.LoadFromHtml(inputFile)

# Save the HTML file to an Excel file
workbook.SaveToFile(outputFile, ExcelVersion.Version2013)
workbook.Dispose()

Python: Convert Excel to HTML and Vice Versa

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.

Hiding or unhiding rows and columns in Excel gives you precise control over the visibility of specific data within a worksheet. By hiding rows or columns, you can temporarily remove irrelevant information from view, reducing visual clutter and creating a cleaner workspace. This makes it easier to work with the data that truly matters and enhances your productivity. On the other hand, unhiding rows or columns allows you to restore visibility and regain access to previously hidden information whenever you need it. This is advantageous when you have hidden data that requires further review, modification, or analysis. In this article, we will explain how to hide or unhide rows and columns 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

Hide Specific Rows and Columns in Excel in Python

Spire.XLS for Python offers the Worksheet.HideRow(rowIndex) and Worksheet.HideColumn(columnIndex) methods to hide a specific row and column in an Excel worksheet. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[sheetIndex] property.
  • Hide specific rows in the worksheet using Worksheet.HideRow(rowIndex) method.
  • Hide Specific columns in the worksheet using Worksheet.HideColumn(columnIndex) 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()
# Load an Excel file
workbook.LoadFromFile("Input.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Hide the 3rd and the 7th rows
sheet.HideRow(3)
sheet.HideRow(7)

# Hide the 3rd and the 6th columns
sheet.HideColumn(3)
sheet.HideColumn(6)

# Save the result file
workbook.SaveToFile("HideRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Hide or Unhide Rows and Columns in Excel

Unhide Specific Hidden Rows and Columns in Excel in Python

You can use the Worksheet.ShowRow(rowIndex) and Worksheet.ShowColumn(columnIndex) methods to unhide a specific hidden row and column. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[sheetIndex] property.
  • Unhide specific hidden rows in the worksheet using Worksheet.ShowRow(rowIndex) method.
  • Unhide specific hidden columns in the worksheet using Worksheet.ShowColumn(columnIndex) 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()
# Load an Excel file
workbook.LoadFromFile("HideRowsAndColumns.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Unhide the 3rd and the 7th rows
sheet.ShowRow(3)
sheet.ShowRow(7)

# Unhide the 3rd and the 6th columns
sheet.ShowColumn(3)
sheet.ShowColumn(6)

# Save the result file
workbook.SaveToFile("ShowRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Hide or Unhide Rows and Columns in Excel

Hide Multiple Rows and Columns at Once in Excel in Python

To hide multiple rows and columns at once, you can use the Worksheet.HideRows(startRowIndex, rowCount) and Worksheet.HideColumns(startColumnIndex, columnCount) methods. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[sheetIndex] property.
  • Hide multiple rows in the worksheet using the Worksheet.HideRows(startRowIndex, rowCount) method.
  • Hide multiple columns in the worksheet using Worksheet.HideColumns(startColumnIndex, columnCount) 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()
# Load an Excel file
workbook.LoadFromFile("Input.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Hide 3, 4 and 5 rows
sheet.HideRows(3, 3)

# Hide 5, 6 and 7 columns
sheet.HideColumns(5, 3)

# Save the result file
workbook.SaveToFile("HideMultipleRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Hide or Unhide Rows and Columns in Excel

Unhide All Hidden Rows and Columns in Excel in Python

To unhide all hidden rows and columns, you first need to loop through the used rows and columns in the worksheet. Next, find the hidden rows and columns using Worksheet.GetRowIsHide(rowIndex) and Worksheet.GetColumnIsHide(columnIndex) methods, and then unhide them using Worksheet.ShowRow(rowIndex) and Worksheet.ShowColumn(columnIndex) methods. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[sheetIndex] property.
  • Iterate through the used rows in the worksheet and find the hidden rows using Worksheet.GetRowIsHide(rowIndex) method.
  • Unhide every hidden row using Worksheet.ShowRow(rowIndex) method.
  • Iterate through the used columns in the worksheet and find the hidden columns using Worksheet.GetColumnIsHide(columnIndex) method.
  • Unhide every hidden column using Worksheet.ShowColumn(columnIndex) 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()
# Load an Excel file
workbook.LoadFromFile("HideMultipleRowsAndColumns.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Iterate through the used rows in the worksheet
for i in range(1, sheet.LastRow + 1):
    # Check if the current row is hidden
    if sheet.GetRowIsHide(i):
        # Unhide the hidden row
        sheet.ShowRow(i)

# Iterate through the used columns in the worksheet
for j in range(1, sheet.LastColumn + 1):
    # Check if the current column is hidden
    if sheet.GetColumnIsHide(j):
        # Unhide the hidden column
        sheet.ShowColumn(j)

# Save the result file
workbook.SaveToFile("ShowAllHiddenRowsAndColumns.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python: Hide or Unhide Rows and Columns in Excel

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.

Page 6 of 8
page 6