<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alice Yang on Medium]]></title>
        <description><![CDATA[Stories by Alice Yang on Medium]]></description>
        <link>https://medium.com/@alice.yang_10652?source=rss-ab67334728f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*s_IabP-ULpYzhSINpNzrPA.png</url>
            <title>Stories by Alice Yang on Medium</title>
            <link>https://medium.com/@alice.yang_10652?source=rss-ab67334728f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:07:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alice.yang_10652/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Lock Formula Cells in Excel with Python While Keeping Input Cells Editable]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-lock-formula-cells-in-excel-with-python-while-keeping-input-cells-editable-d87f3ce85ac8?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/d87f3ce85ac8</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[lock-formula-cells]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[worksheet-protection]]></category>
            <category><![CDATA[protect-cells]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 07:00:11 GMT</pubDate>
            <atom:updated>2026-11-17T07:00:11.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k09BfHqTaQIBE0OOb7QGDg.png" /><figcaption>Lock Formula Cells in Excel While Keeping Input Cells Editable with Python</figcaption></figure><p>When creating Excel templates for quotations or budgets, you may need to let users enter or update data without accidentally overwriting formulas.</p><p>For example, a quotation template may allow users to modify product quantities and unit prices while keeping the formulas for line amounts and the grand total protected.</p><p>With Python, you can unlock designated input cells, keep formula cells locked, and protect the worksheet to enforce these settings.</p><h3>Install the Required Python Excel Library</h3><p>To protect formula cells in Excel with Python, we’ll use <a href="https://www.e-iceblue.com/Introduce/free-xls-for-python.html">Free Spire.XLS for Python</a>. It’s a free library for creating and modifying Excel workbooks without requiring Microsoft Excel to be installed.</p><p>Install the package using pip:</p><pre>pip install Spire.Xls.Free</pre><p>Then import the required modules:</p><pre>from spire.xls.common import *<br>from spire.xls import *</pre><h3>How Excel Cell Protection Works</h3><p>Before writing the code, it’s important to understand how Excel handles locked cells.</p><p>By default, Excel cells are marked as locked. However, this setting does not prevent editing until worksheet protection is enabled.</p><p>To control which cells users can modify:</p><ol><li>Unlock the cells that users are allowed to edit.</li><li>Leave formula cells and other cells that should not be modified locked.</li><li>Protect the worksheet to enforce these settings.</li></ol><h3>Create an Excel Quotation Template with Locked Formula Cells in Python</h3><p>Suppose we’re building a sales quotation template with the following structure:</p><pre>| Column | Content              | Editable? |<br>|--------|----------------------|-----------|<br>| A      | Product descriptions | No        |<br>| B      | Quantities           | Yes       |<br>| C      | Unit prices          | Yes       |<br>| D      | Calculated amounts   | No        |</pre><p>Rows 4–6 contain the product information, while cell D7 calculates the grand total.</p><h4>Step 1: Create a Workbook and Add Data</h4><p>First, create a new Excel workbook, access its first worksheet, and populate it with sample quotation data.</p><pre>workbook = Workbook()<br>sheet = workbook.Worksheets[0]<br><br>sheet.Name = &quot;Sales Quotation&quot;<br><br># Add column headers<br>sheet.Range[&quot;A3&quot;].Text = &quot;Product&quot;<br>sheet.Range[&quot;B3&quot;].Text = &quot;Quantity&quot;<br>sheet.Range[&quot;C3&quot;].Text = &quot;Unit Price&quot;<br>sheet.Range[&quot;D3&quot;].Text = &quot;Amount&quot;<br><br># Add product information<br>sheet.Range[&quot;A4&quot;].Text = &quot;Cloud Service&quot;<br>sheet.Range[&quot;B4&quot;].NumberValue = 3<br>sheet.Range[&quot;C4&quot;].NumberValue = 199<br><br>sheet.Range[&quot;A5&quot;].Text = &quot;Technical Support&quot;<br>sheet.Range[&quot;B5&quot;].NumberValue = 2<br>sheet.Range[&quot;C5&quot;].NumberValue = 149<br><br>sheet.Range[&quot;A6&quot;].Text = &quot;Training Service&quot;<br>sheet.Range[&quot;B6&quot;].NumberValue = 1<br>sheet.Range[&quot;C6&quot;].NumberValue = 299</pre><p>Next, add formulas to calculate the amount for each product and the grand total.</p><pre># Calculate the amount for each product<br>sheet.Range[&quot;D4&quot;].Formula = &quot;=B4*C4&quot;<br>sheet.Range[&quot;D5&quot;].Formula = &quot;=B5*C5&quot;<br>sheet.Range[&quot;D6&quot;].Formula = &quot;=B6*C6&quot;<br><br># Calculate the grand total<br>sheet.Range[&quot;A7&quot;].Text = &quot;Grand Total&quot;<br>sheet.Range[&quot;D7&quot;].Formula = &quot;=SUM(D4:D6)&quot;<br><br># Calculate formula results<br>workbook.CalculateAllValue()</pre><p>At this stage, the worksheet contains the quotation data and calculation formulas. Cell protection has not yet been applied.</p><h4>Step 2: Unlock the Input Cells and Lock Formula Cells</h4><p>The quantity and unit price fields are located in B4:C6. To allow users to modify these values after worksheet protection is enabled, set their Style.Locked property to False.</p><pre># Unlock the input cells<br>sheet.Range[&quot;B4:C6&quot;].Style.Locked = False</pre><p>The formula cells in D4:D7 should remain locked:</p><pre># Lock the formula cells<br>sheet.Range[&quot;D4:D7&quot;].Style.Locked = True</pre><p>Since Excel cells are locked by default, other cells retain their default locked state. This keeps product names, headers, and other fixed content protected once worksheet protection is enabled.</p><p><strong>Optional: Hide Formulas in Protected Cells</strong></p><p>Locking formula cells prevents users from modifying them, but it does not automatically hide their formulas from the Formula Bar.</p><p>If you also want to hide formulas, set the Style.FormulaHidden property to True for the relevant cells before protecting the worksheet:</p><pre>sheet.Range[&quot;D4:D7&quot;].Style.FormulaHidden = True</pre><p>Formula hiding serves a different purpose from cell locking. For more details, see our guide on <a href="https://medium.com/@alice.yang_10652/how-to-hide-or-remove-formulas-in-excel-with-python-a4e83090519f">How to Hide or Remove Formulas in Excel with Python</a>.</p><h4>Step 3: Protect the Worksheet and Save the File</h4><p>After configuring the cell permissions, call Protect() to enable worksheet protection.</p><pre># Protect the worksheet with a password<br>sheet.Protect(&quot;Quote2026&quot;)<br><br># Save the workbook<br>workbook.SaveToFile(<br>    &quot;Protected_Quotation.xlsx&quot;,<br>    ExcelVersion.Version2016<br>)<br>workbook.Dispose()</pre><p>You’ll need the password to remove worksheet protection later. Replace Quote2026 with your own password when adapting the code.</p><h3>Complete Python Example</h3><p>The following code combines the previous steps into a complete example. It creates a sales quotation with sample data and formulas, applies basic formatting, and configures cell protection. No existing Excel file is required.</p><pre>from spire.xls.common import *<br>from spire.xls import *<br><br># Create a workbook<br>workbook = Workbook()<br><br>try:<br>    # Get the first worksheet<br>    sheet = workbook.Worksheets[0]<br>    sheet.Name = &quot;Sales Quotation&quot;<br><br>    # Add the title<br>    sheet.Range[&quot;A1&quot;].Text = &quot;Sales Quotation&quot;<br><br>    # Add column headers<br>    sheet.Range[&quot;A3&quot;].Text = &quot;Product&quot;<br>    sheet.Range[&quot;B3&quot;].Text = &quot;Quantity&quot;<br>    sheet.Range[&quot;C3&quot;].Text = &quot;Unit Price&quot;<br>    sheet.Range[&quot;D3&quot;].Text = &quot;Amount&quot;<br><br>    # Add product information<br>    sheet.Range[&quot;A4&quot;].Text = &quot;Cloud Service&quot;<br>    sheet.Range[&quot;B4&quot;].NumberValue = 3<br>    sheet.Range[&quot;C4&quot;].NumberValue = 199<br>    sheet.Range[&quot;A5&quot;].Text = &quot;Technical Support&quot;<br>    sheet.Range[&quot;B5&quot;].NumberValue = 2<br>    sheet.Range[&quot;C5&quot;].NumberValue = 149<br>    sheet.Range[&quot;A6&quot;].Text = &quot;Training Service&quot;<br>    sheet.Range[&quot;B6&quot;].NumberValue = 1<br>    sheet.Range[&quot;C6&quot;].NumberValue = 299<br><br>    # Add calculation formulas<br>    sheet.Range[&quot;D4&quot;].Formula = &quot;=B4*C4&quot;<br>    sheet.Range[&quot;D5&quot;].Formula = &quot;=B5*C5&quot;<br>    sheet.Range[&quot;D6&quot;].Formula = &quot;=B6*C6&quot;<br><br>    # Calculate the grand total<br>    sheet.Range[&quot;A7&quot;].Text = &quot;Grand Total&quot;<br>    sheet.Range[&quot;D7&quot;].Formula = &quot;=SUM(D4:D6)&quot;<br><br>    # Calculate formula results<br>    workbook.CalculateAllValue()<br><br>    # Apply basic formatting<br>    sheet.Range[&quot;A1&quot;].Style.Font.IsBold = True<br>    sheet.Range[&quot;A3:D3&quot;].Style.Font.IsBold = True<br>    sheet.Range[&quot;A7:D7&quot;].Style.Font.IsBold = True<br>    # Adjust column widths<br>    sheet.SetColumnWidth(1, 24)<br>    sheet.SetColumnWidth(2, 14)<br>    sheet.SetColumnWidth(3, 16)<br>    sheet.SetColumnWidth(4, 16)<br><br>    # Unlock the quantity and unit price input cells<br>    sheet.Range[&quot;B4:C6&quot;].Style.Locked = False<br><br>    # Lock formula cells<br>    sheet.Range[&quot;D4:D7&quot;].Style.Locked = True<br><br>    # Protect the worksheet<br>    sheet.Protect(&quot;Quote2026&quot;)<br><br>    # Save the workbook<br>    workbook.SaveToFile(<br>        &quot;Protected_Quotation.xlsx&quot;,<br>        ExcelVersion.Version2016<br>    )<br><br>    print(&quot;Protected Excel quotation created successfully.&quot;)<br><br>finally:<br>    workbook.Dispose()</pre><p>After running the program, you’ll get a file named Protected_Quotation.xlsx. Open it in Microsoft Excel to view the generated quotation and check the cell protection settings.</p><figure><img alt="Protected sales quotation showing product names, editable quantities and unit prices, calculated amounts, and the grand total." src="https://cdn-images-1.medium.com/max/663/1*zRhoeEReTqdOg6VmHYtLCQ.png" /><figcaption>Protected sales quotation showing product names, editable quantities and unit prices, calculated amounts, and the grand total.</figcaption></figure><p>Although the worksheet looks like a regular spreadsheet, its editing permissions have been configured:</p><ul><li><strong>B4:C6 (Quantities and unit prices):</strong> Users can edit these cells to update quotation information.</li><li><strong>D4:D7 (Amounts and grand total):</strong> These cells are locked. Users can view the calculated results but cannot overwrite the formulas.</li><li><strong>Other cells:</strong> Product names, column headers, and other fixed content remain locked.</li></ul><p>For example, if you change the quantity in B4 from 3 to 5, Excel recalculates the amount in D4 from 597 to 995. The grand total in D7 also updates from 1194 to 1592.</p><h3>Protect Specific Cells in an Existing Excel Workbook</h3><p>Besides creating a new quotation, you can also apply cell protection to an existing Excel workbook.</p><p>For example, suppose you already have a quotation template named Quotation_Template.xlsx and want to control which cells users can modify.</p><p>You don’t need to recreate the workbook. Simply load the existing file, configure the cell protection settings, and protect the worksheet.</p><pre>from spire.xls import *<br>from spire.xls.common import *<br><br># Load an existing Excel workbook<br>workbook = Workbook()<br><br>try:<br>    workbook.LoadFromFile(&quot;Quotation_Template.xlsx&quot;)<br><br>    # Get the first worksheet<br>    sheet = workbook.Worksheets[0]<br><br>    # Lock all cells in the used range<br>    sheet.AllocatedRange.Style.Locked = True<br><br>    # Unlock the quantity and unit price input cells<br>    sheet.Range[&quot;B4:C6&quot;].Style.Locked = False<br><br>    # Protect the worksheet<br>    sheet.Protect(&quot;Quote2026&quot;)<br><br>    # Save the protected workbook as a new file<br>    workbook.SaveToFile(<br>        &quot;Quotation_Protected.xlsx&quot;,<br>        ExcelVersion.Version2016<br>    )<br><br>finally:<br>    workbook.Dispose()</pre><p>Compared with the previous example, this code adds one important step:</p><pre>sheet.AllocatedRange.Style.Locked = True</pre><p>It locks all cells in the worksheet’s used range before the designated input cells are unlocked. This ensures that previously unlocked cells in the existing template won’t remain editable unintentionally.</p><p><strong>Note:</strong> This example assumes that the worksheet is not already protected. If it is, <a href="https://medium.com/@alice.yang_10652/how-to-remove-or-reset-excel-passwords-with-python-a-complete-guide-2b4b096ce1e1">remove the existing protection</a> with the correct password before changing its cell settings:</p><pre># Remove existing worksheet protection<br>sheet.Unprotect(&quot;ExistingPassword&quot;)</pre><h3>Frequently Asked Questions</h3><h4>1. Why Can Users Still Edit Cells After Setting Locked to True?</h4><p>The Locked property only defines a cell&#39;s protection status. It does not prevent editing until worksheet protection is enabled.</p><p>For example:</p><pre>sheet.Range[&quot;D4:D7&quot;].Style.Locked = True</pre><p>To enforce this setting, you also need to call:</p><pre>sheet.Protect(&quot;Quote2026&quot;)</pre><p>Once worksheet protection is enabled, users can no longer modify the locked cells through normal Excel editing.</p><h4>2. Why Can’t Users Edit the Input Cells After Protecting the Worksheet?</h4><p>The most common reason is that the input cells were not unlocked before worksheet protection was enabled.</p><p>Make sure to set the Locked property to False for the required input range:</p><pre>sheet.Range[&quot;B4:C6&quot;].Style.Locked = False</pre><p>Also, verify that the range matches the actual input cells in your workbook. For example, if quantities and unit prices are stored in columns C and D, adjust the range accordingly.</p><h4>3. Does Worksheet Protection Secure Sensitive Excel Data?</h4><p>No. Worksheet protection is primarily designed to restrict editing and prevent accidental changes to formulas, data, and worksheet structures. It is not a security mechanism for protecting confidential information.</p><p>If you need to prevent unauthorized access to sensitive workbook contents, use <a href="https://medium.com/@alice.yang_10652/7-ways-to-protect-or-encrypt-excel-files-in-python-5a01a8e55c9e">file-level encryption</a> with a password required to open the file, rather than relying solely on worksheet protection.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d87f3ce85ac8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Add Footnotes and Endnotes in Word Using Python]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-add-footnotes-and-endnotes-in-word-using-python-ce29628f5f93?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce29628f5f93</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[add-footnote-to-word]]></category>
            <category><![CDATA[insert-endnote-in-word]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 07:12:24 GMT</pubDate>
            <atom:updated>2026-11-16T07:12:24.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*k4H1TWfiCPVBoo5702hjiA.png" /><figcaption>Add Footnotes and Endnotes with Python</figcaption></figure><p>Footnotes and endnotes are commonly used in Word documents to provide source citations, definitions, and additional explanations without interrupting the main text. They are particularly useful in academic papers, research reports, technical documentation, and legal documents.</p><p>When generating or modifying Word documents programmatically, adding these notes can be challenging. Although python-docx supports many common document operations, it does not provide a native API for creating or editing footnotes. Its <a href="https://python-docx.readthedocs.io/en/latest/user/documents.html">official documentation</a> explains that existing footnotes are preserved when a document is loaded and saved, but cannot be manipulated through the library&#39;s API.</p><p>In this article, we’ll explore how to use Python to insert footnotes and endnotes into Word documents, customize their appearance, and configure their numbering and positions.</p><ul><li>Add a Footnote to a Word Document</li><li>Add an Endnote to a Word Document</li><li>Customize Footnote and Endnote Numbering and Position</li><li>Insert a Footnote After Specific Text</li></ul><h3>1. Install the Required Library</h3><p>To work with Word footnotes and endnotes programmatically, install Free <a href="https://www.e-iceblue.com/Introduce/free-doc-for-python.html?utm_source=medium&amp;utm_medium=referral&amp;utm_campaign=python_footnotes_endnotes&amp;utm_content=free_spire_doc_for_python">Spire.Doc for Python</a> using pip:</p><pre>pip install Spire.Doc.Free</pre><h3>2. Add a Footnote to a Word Document</h3><p>A footnote provides additional information related to a specific part of the main text. It is typically displayed at the bottom of the page where its reference mark appears.</p><p>To insert a footnote, use the Paragraph.AppendFootnote() method with FootnoteType.Footnote. You can then add the footnote content through the Footnote.TextBody property.</p><p>The following example creates a Word document and adds a footnote to a paragraph.</p><pre>from spire.doc import Document, FileFormat, FootnoteType<br><br># Create a new Word document<br>document = Document()<br>section = document.AddSection()<br>section.PageSetup.Margins.All = 72  # Set margins to 1 inch (72 points)<br><br># Add a paragraph<br>paragraph = section.AddParagraph()<br>paragraph.AppendText(<br>    &quot;The report summarizes the company&#39;s financial performance for the year.&quot;<br>)<br><br># Insert a footnote<br>footnote = paragraph.AppendFootnote(FootnoteType.Footnote)<br><br># Add the footnote content<br>footnote_text = footnote.TextBody.AddParagraph().AppendText(<br>    &quot;The figures are based on the company&#39;s audited financial statements.&quot;<br>)<br><br># Format the footnote text<br>footnote_text.CharacterFormat.FontName = &quot;Arial&quot;<br>footnote_text.CharacterFormat.FontSize = 9<br><br># Customize the footnote reference mark<br>footnote.MarkerCharacterFormat.FontName = &quot;Arial&quot;<br>footnote.MarkerCharacterFormat.FontSize = 9<br><br># Save the document<br>document.SaveToFile(&quot;AddFootnote.docx&quot;, FileFormat.Docx2016)<br>document.Close()</pre><p>The AppendFootnote() method creates a footnote reference in the paragraph. Its associated content is added through TextBody.AddParagraph().AppendText().</p><p>You can also customize the footnote text and its reference mark independently using their respective CharacterFormat properties.</p><h3>3. Add an Endnote to a Word Document</h3><p>Unlike footnotes, which appear at the bottom of individual pages, endnotes are generally placed at the end of a document or section. They are useful for references, source citations, and supplementary explanations that would otherwise take up too much space on individual pages.</p><p>The process of adding an endnote is almost identical to inserting a footnote. The main difference is that you specify FootnoteType.Endnote when calling AppendFootnote().</p><p>The following example adds an endnote to a paragraph:</p><pre>from spire.doc import Document, FileFormat, FootnoteType<br><br># Create a new Word document<br>document = Document()<br>section = document.AddSection()<br>section.PageSetup.Margins.All = 72  # Set margins to 1 inch (72 points)<br><br># Add a paragraph<br>paragraph = section.AddParagraph()<br>paragraph.AppendText(<br>    &quot;The study adopts a standardized classification system for its analysis.&quot;<br>)<br><br># Insert an endnote<br>endnote = paragraph.AppendFootnote(FootnoteType.Endnote)<br><br># Add the endnote content<br>endnote_text = endnote.TextBody.AddParagraph().AppendText(<br>    &quot;For a detailed explanation of the classification system, &quot;<br>    &quot;refer to the methodology appendix.&quot;<br>)<br><br># Format the endnote text<br>endnote_text.CharacterFormat.FontName = &quot;Arial&quot;<br>endnote_text.CharacterFormat.FontSize = 9<br><br># Customize the endnote reference mark<br>endnote.MarkerCharacterFormat.FontName = &quot;Arial&quot;<br>endnote.MarkerCharacterFormat.FontSize = 9<br><br># Save the document<br>document.SaveToFile(&quot;AddEndnote.docx&quot;, FileFormat.Docx2016)<br>document.Close()</pre><p>Here, FootnoteType.Endnote tells the API to create an endnote rather than a footnote. The remaining operations, including adding the note content and formatting its reference mark, follow the same approach.</p><h3>4. Customize Footnote and Endnote Numbering and Position</h3><p>Word allows you to configure how footnotes and endnotes are numbered and where they appear. For example, you may want footnotes to use Arabic numerals, restart numbering on each page, or display endnotes at the end of the document.</p><p>You can configure these settings through the FootnoteOptions and EndnoteOptions properties.</p><p>The following example demonstrates how to customize these settings:</p><pre>from spire.doc import Document, FileFormat, FootnoteType, FootnoteNumberFormat, FootnoteRestartRule, FootnotePosition<br><br># Create a new Word document<br>document = Document()<br><br># Configure footnote numbering and position<br>document.FootnoteOptions.NumberFormat = FootnoteNumberFormat.Arabic<br>document.FootnoteOptions.RestartRule = FootnoteRestartRule.DoNotRestart<br>document.FootnoteOptions.Position = FootnotePosition.PrintAtBottomOfPage<br><br># Configure endnote numbering and position<br>document.EndnoteOptions.NumberFormat = FootnoteNumberFormat.LowerCaseRoman<br>document.EndnoteOptions.RestartRule = FootnoteRestartRule.DoNotRestart<br>document.EndnoteOptions.Position = FootnotePosition.PrintAsEndOfDocument<br><br>section = document.AddSection()<br>section.PageSetup.Margins.All = 72  # Set margins to 1 inch (72 points)<br><br># Add a paragraph with a footnote<br>paragraph1 = section.AddParagraph()<br>paragraph1.AppendText(<br>    &quot;The company published its annual report in March 2026.&quot;<br>)<br><br># Insert a footnote<br>footnote = paragraph1.AppendFootnote(FootnoteType.Footnote)<br>footnote_text = footnote.TextBody.AddParagraph().AppendText(<br>    &quot;The report covers the fiscal year ending December 31, 2025.&quot;<br>)<br>footnote_text.CharacterFormat.FontName = &quot;Arial&quot;<br>footnote_text.CharacterFormat.FontSize = 9<br><br># Add another paragraph with an endnote<br>paragraph2 = section.AddParagraph()<br>paragraph2.AppendText(<br>    &quot;The financial statements follow the applicable accounting standards.&quot;<br>)<br><br># Insert an endnote<br>endnote = paragraph2.AppendFootnote(FootnoteType.Endnote)<br>endnote_text = endnote.TextBody.AddParagraph().AppendText(<br>    &quot;For more information, refer to the applicable accounting standards.&quot;<br>)<br>endnote_text.CharacterFormat.FontName = &quot;Arial&quot;<br>endnote_text.CharacterFormat.FontSize = 9<br><br># Save the document<br>document.SaveToFile(&quot;CustomizeNotes.docx&quot;, FileFormat.Docx2016)<br>document.Close()</pre><p>The main properties used in this example are:</p><ul><li>NumberFormat: Specifies the numbering format, such as Arabic numerals, uppercase letters, or lowercase Roman numerals.</li><li>RestartRule: Controls whether numbering continues throughout the document or restarts according to a specified rule.</li><li>Position: Determines where the notes appear, such as at the bottom of the page, at the end of a section, or at the end of the document.</li></ul><p>Footnote and endnote settings can be configured independently. In this example, the options are set at the document level, so the numbering and positioning settings apply to the document as a whole.</p><h3>5. Insert a Footnote After Specific Text</h3><p>In some scenarios, you may not want to add a footnote at the end of an entire paragraph. Instead, you may need to associate it with a particular word or phrase.</p><p>For example, consider a paragraph containing the phrase annual survey. You want the footnote reference to appear immediately after that phrase.</p><p>You can accomplish this by locating the target text with Document.FindString(), retrieving its position within the paragraph, and inserting the footnote at the corresponding index.</p><pre>from spire.doc import Document, FileFormat, FootnoteType<br><br># Load an existing Word document<br>document = Document()<br>document.LoadFromFile(&quot;Input.docx&quot;)<br><br># Find the target text<br>selection = document.FindString(&quot;annual survey&quot;, False, True)<br><br>if selection is not None:<br>    # Get the matched text range<br>    text_range = selection.GetAsOneRange()<br><br>    # Get the paragraph containing the text<br>    paragraph = text_range.OwnerParagraph<br><br>    # Get the position of the matched text<br>    index = paragraph.ChildObjects.IndexOf(text_range)<br><br>    # Create a footnote<br>    footnote = paragraph.AppendFootnote(FootnoteType.Footnote)<br><br>    # Insert the footnote immediately after the matched text<br>    paragraph.ChildObjects.Insert(index + 1, footnote)<br><br>    # Add the footnote content<br>    footnote.TextBody.AddParagraph().AppendText(<br>        &quot;The survey was conducted between January and March 2026.&quot;<br>    )<br><br># Save the modified document<br>document.SaveToFile(&quot;AddFootnoteToText.docx&quot;, FileFormat.Docx2016)<br>document.Close()</pre><p>In this example, FindString() locates the specified phrase, while GetAsOneRange() retrieves the corresponding text range. The ChildObjects.IndexOf() method determines its position within the paragraph.</p><p>After creating the footnote, ChildObjects.Insert() places the reference immediately after the matched text rather than at the end of the paragraph.</p><h3>Conclusion</h3><p>Footnotes and endnotes help organize supplementary information and references in Word documents without disrupting the main content.</p><p>With Python, you can insert either type of note, customize its text and reference mark, and configure numbering and placement through the corresponding options.</p><p>These capabilities are particularly useful when generating academic papers, research reports, and other structured Word documents that require consistently formatted notes.</p><h3>See Also</h3><ul><li><a href="https://medium.com/@alice.yang_10652/how-to-edit-word-documents-in-python-beyond-text-replacement-10f43148a86d">How to Edit Word Documents in Python: Beyond Text Replacement</a></li><li><a href="https://medium.com/@alice.yang_10652/how-to-dynamically-fill-word-templates-with-python-e7b39620abdd">How to Dynamically Fill Word Templates with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/get-word-document-statistics-in-python-count-words-pages-more-0b469022b3c2">Get Word Document Statistics in Python: Count Words, Pages &amp; More</a></li><li><a href="https://medium.com/@alice.yang_10652/master-word-track-changes-with-python-enable-disable-accept-reject-more-ae72c47c8656">Master Word Track Changes with Python: Enable, Disable, Accept, Reject &amp; More</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce29628f5f93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Sort Data in Excel Ranges and Tables with Python]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-sort-data-in-excel-ranges-and-tables-with-python-94945b8410da?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/94945b8410da</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[excel-data-sort]]></category>
            <category><![CDATA[sort-data-in-excel]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 02:28:48 GMT</pubDate>
            <atom:updated>2026-11-16T04:01:58.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Guide to Sorting Data in Excel with Python" src="https://cdn-images-1.medium.com/max/650/1*7MFrsOeQDgFBaNEw0_UOCA.png" /><figcaption>Guide to Sorting Data in Excel with Python</figcaption></figure><p>Excel provides several ways to sort data, including sorting by column values, cell formatting, multiple columns, or a custom order. You can also sort records in an Excel Table, such as arranging orders by date.</p><p>This article explains how to sort data in Excel ranges and tables using Python, with practical examples covering the following scenarios:</p><ul><li><a href="#a2f3">Sort Excel Data by a Single Column in Python</a></li><li><a href="#6844">Sort Excel Data by Multiple Columns in Python</a></li><li><a href="#1a8b">Sort Excel Data in a Custom Order</a></li><li><a href="#35ee">Sort Data in an Excel Table with Python</a></li></ul><h3>Set Up the Python Environment</h3><h4>1. Install the Required Python Excel Library</h4><p>To sort Excel data programmatically, you need a Python library that can read and modify Excel workbooks. This article uses <a href="https://www.e-iceblue.com/Introduce/excel-for-python.html">Spire.XLS for Python</a>, which supports sorting worksheet ranges and working with Excel Tables without requiring Microsoft Excel.</p><p>Install the library using pip:</p><pre>pip install Spire.XLS</pre><h4>2. Prepare the Sample Excel File</h4><p>We’ll use a workbook named sales_orders.xlsx containing eight sales records. The worksheet has six columns: Order ID, Region, Product, Sales, Priority, and Order Date.</p><p>The headers are in row 1, and the records occupy A2:F9. Sales amounts are stored as numbers, while Order Date contains actual Excel dates rather than text.</p><figure><img alt="Sample Excel worksheet containing sales orders, regions, products, sales amounts, priorities, and order dates" src="https://cdn-images-1.medium.com/max/783/1*om-Cf_m43CiLVyGqczJG8Q.png" /><figcaption>Sample Excel worksheet containing sales orders, regions, products, sales amounts, priorities, and order dates</figcaption></figure><p>We’ll use this workbook throughout the examples.</p><h3>1. Sort Excel Data by a Single Column in Python</h3><p>You can sort Excel records based on the values in a specific column, either in ascending or descending order.</p><p>For example, in our sample sales worksheet, we can sort by Sales (column D) in descending order to show the highest-value orders first. The following code sorts the records while keeping the data in each row together:</p><pre>from spire.xls import *<br>from spire.xls.common import *<br> <br>workbook = Workbook()<br> <br>try:<br>    workbook.LoadFromFile(&quot;sales_orders.xlsx&quot;)<br>    sheet = workbook.Worksheets[0]<br> <br>    # Configure sorting by Sales (column D)<br>    sorter = workbook.DataSorter<br>    sorter.SortColumns.Clear()<br>    sorter.IsIncludeTitle = False<br>    sorter.SortColumns.Add(3, SortComparisonType.Values, OrderBy.Descending)<br> <br>    # Sort the records without including the header<br>    sorter.Sort(sheet.Range[&quot;A2:F9&quot;])<br> <br>    workbook.SaveToFile(&quot;sales_by_amount.xlsx&quot;, ExcelVersion.Version2016)<br> <br>finally:<br>    workbook.Dispose()</pre><p>SortColumns.Add() defines the sorting rule. Here, 3 refers to column D (using a zero-based index), SortComparisonType.Values sorts by cell values, and OrderBy.Descending places the largest values first.</p><p>The sorting range A2:F9 includes all related columns but excludes the header row, so each record stays intact.</p><p>After sorting, order SO-1005, with sales of 5100, appears first, followed by SO-1001 (4700). Order SO-1006, with sales of 1800, moves to the bottom.</p><h4>Sort in Ascending Order</h4><p>To sort sales amounts from smallest to largest, change the sorting rule to:</p><pre>sorter.SortColumns.Add(3, SortComparisonType.Values, OrderBy.Ascending)</pre><p>The same approach works for sorting text alphabetically or dates chronologically, as long as the cells contain the correct data types.</p><h4>Other Sorting Options: Cell Color, Font Color, and Icons</h4><p>Besides sorting by cell values, SortComparisonType also supports other sorting types:</p><ul><li>BackgroundColor — Sort by cell background color.</li><li>FontColor — Sort by font color.</li><li>Icon — Sort by conditional formatting icons.</li></ul><p>For example, if certain orders are highlighted in red, you can sort the records to bring those orders to the top.</p><p>To try this with the original sales_orders.xlsx file, replace the value-based sorting and saving statements in the first example with the following snippet:</p><pre># Highlight two sales cells in red<br>sheet.Range[&quot;D3&quot;].Style.Color = Color.get_Red()<br>sheet.Range[&quot;D6&quot;].Style.Color = Color.get_Red()<br> <br># Move records with red-highlighted cells to the top<br>sorter.SortColumns.Clear()<br>color_sort = sorter.SortColumns.Add(3, SortComparisonType.BackgroundColor, OrderBy.Top)<br>color_sort.Color = Color.get_Red()<br>sorter.Sort(sheet.Range[&quot;A2:F9&quot;])<br> <br>workbook.SaveToFile(&quot;sales_by_color.xlsx&quot;, ExcelVersion.Version2016)</pre><p>In the original worksheet, cells D3 and D6 belong to orders SO-1002 and SO-1005. After sorting by background color, these two records move to the top, while the remaining records follow below. Their relative order is not specified because no secondary sorting rule has been applied.</p><p>You can use OrderBy.Bottom instead if you want the red-highlighted records to appear at the bottom.</p><h3>2. Sort Excel Data by Multiple Columns in Python</h3><p>When sorting by multiple columns, the first column defines the primary sort order. Additional columns are used to sort records that have the same value in the preceding column.</p><p>For example, in our sales worksheet, we can sort by Region alphabetically, then by Sales from highest to lowest within each region. The following code applies both sorting rules:</p><pre>from spire.xls import *<br>from spire.xls.common import *<br> <br>workbook = Workbook()<br> <br>try:<br>    workbook.LoadFromFile(&quot;sales_orders.xlsx&quot;)<br>    sheet = workbook.Worksheets[0]<br> <br>    sorter = workbook.DataSorter<br>    sorter.SortColumns.Clear()<br>    sorter.IsIncludeTitle = False<br> <br>    # Sort by Region first, then by Sales<br>    sorter.SortColumns.Add(1, SortComparisonType.Values, OrderBy.Ascending)<br>    sorter.SortColumns.Add(3, SortComparisonType.Values, OrderBy.Descending)<br> <br>    sorter.Sort(sheet.Range[&quot;A2:F9&quot;])<br> <br>    workbook.SaveToFile(&quot;sales_by_region.xlsx&quot;, ExcelVersion.Version2016)<br> <br>finally:<br>    workbook.Dispose()</pre><p>After sorting, the records are grouped in alphabetical order by Region: East, North, and West. Within each region, the sales amounts are arranged from highest to lowest.</p><p>For example, the East region’s sales values appear in the order 3800, 3200, and 2500, while the North region’s values appear as 5100, 3300, and 2600.</p><p>Notice that North’s sales of 5100 appear below the smaller East region values. This is because Region is the primary sort key, while Sales determines the order within each region.</p><p>The order of the sorting rules matters. To sort primarily by Sales, add the Sales rule before the Region rule. You can also add more sorting levels when needed, such as sorting by Region, then Sales, and finally Order Date.</p><h3>3. Sort Excel Data in a Custom Order</h3><p>Alphabetical sorting doesn’t always match business priorities.</p><p>For example, sorting High, Medium, and Low alphabetically produces High, Low, Medium. But in a priority-based report, you may want to display High first, followed by Medium and Low.</p><p>To achieve this, we can define a custom sorting list.</p><p>In our sample workbook, Priority is in column E. The following code arranges the records according to the specified priority order:</p><pre>from spire.xls import *<br>from spire.xls.common import *<br> <br>workbook = Workbook()<br> <br>try:<br>    workbook.LoadFromFile(&quot;sales_orders.xlsx&quot;)<br>    sheet = workbook.Worksheets[0]<br> <br>    # Define the custom priority order<br>    priority_order = [&quot;High&quot;, &quot;Medium&quot;, &quot;Low&quot;]<br> <br>    sorter = workbook.DataSorter<br>    sorter.SortColumns.Clear()<br>    sorter.IsIncludeTitle = False<br> <br>    # Sort Priority (column E) using the custom list<br>    sorter.SortColumns.Add(4, priority_order)<br>    sorter.Sort(sheet.Range[&quot;A2:F9&quot;])<br> <br>    workbook.SaveToFile(&quot;sales_by_priority.xlsx&quot;, ExcelVersion.Version2016)<br> <br>finally:<br>    workbook.Dispose()</pre><p>Instead of using a standard ascending or descending rule, SortColumns.Add(4, priority_order) follows the sequence specified in the custom list.</p><p>In the resulting workbook, orders SO-1001, SO-1004, and SO-1005 are grouped under High priority. Medium-priority orders follow, and the Low-priority orders, SO-1003 and SO-1006, appear last.</p><p>The custom list determines the order of the priority groups, but it doesn’t specify how records within the same group should be arranged.</p><p>This approach also works for workflow stages such as Pending, In Progress, and Completed, or other categories that need to follow a defined sequence.</p><p>Make sure the entries in your custom list match the values used in the worksheet.</p><h3>4. Sort Data in an Excel Table with Python</h3><p>An Excel Table is a structured table object with its own headers, formatting, and filtering controls. Unlike a manually specified cell range, a table provides information about its location in the worksheet.</p><p>We can use that information to identify the table’s data rows and apply sorting without hardcoding the sorting range.</p><p>In this example, we’ll convert the sample sales data into an Excel Table and sort the orders by date, with the newest orders appearing first.</p><pre>from spire.xls import *<br>from spire.xls.common import *<br> <br>workbook = Workbook()<br> <br>try:<br>    workbook.LoadFromFile(&quot;sales_orders.xlsx&quot;)<br>    sheet = workbook.Worksheets[0]<br> <br>    # Create an Excel Table<br>    table = sheet.ListObjects.Create(&quot;SalesTable&quot;, sheet.Range[&quot;A1:F9&quot;])<br>    table.BuiltInTableStyle = TableBuiltInStyles.TableStyleMedium2<br> <br>    # Get the table&#39;s data range, excluding the header<br>    location = table.Location<br>    data_range = sheet.Range[location.Row + 1, location.Column, location.LastRow, location.LastColumn]<br> <br>    # Sort by Order Date (column F), newest first<br>    sorter = workbook.DataSorter<br>    sorter.SortColumns.Clear()<br>    sorter.IsIncludeTitle = False<br>    sorter.SortColumns.Add(5, SortComparisonType.Values, OrderBy.Descending)<br>    sorter.Sort(data_range)<br> <br>    workbook.SaveToFile(&quot;sorted_sales_table.xlsx&quot;, ExcelVersion.Version2016)<br> <br>finally:<br>    workbook.Dispose()</pre><p>The code creates an Excel Table named SalesTable using ListObjects.Create() and applies a built-in table style.</p><p>The key difference from the earlier examples is how the sorting range is selected:</p><pre>location = table.Location<br>data_range = sheet.Range[location.Row + 1, location.Column, location.LastRow, location.LastColumn]</pre><p>table.Location provides the table’s boundaries. Since the table includes a header row, the starting row is increased by one to select only the data records.</p><p>The sorting rule uses the Order Date column to arrange records from newest to oldest. In the sorted data, order SO-1001, dated October 8, 2026, appears first, while SO-1006, dated October 1, 2026, appears last.</p><p>If your workbook already contains an Excel Table, you don’t need to create another one. You can retrieve the first existing table using:</p><pre>table = sheet.ListObjects[0]</pre><p>Then use its Location property to determine the sorting range.</p><p>This example assumes the table has a header row and no totals row. If your table includes a totals row, adjust the range to exclude it from sorting.</p><h3>Common Issues When Sorting Excel Data</h3><p>Even with the correct sorting rules, the structure and contents of a worksheet can affect the results.</p><h4><strong>Sorting only one column instead of complete records</strong></h4><p>If you sort only D2:D9, the Sales values may become disconnected from their corresponding orders. When sorting a dataset, make sure the selected range includes all related columns.</p><h4><strong>Numbers or dates stored as text</strong></h4><p>Imported spreadsheets sometimes contain numbers or dates stored as strings. These values may not sort as expected. Check the underlying cell types, especially when sorting dates or numeric values.</p><h4><strong>Leading or trailing spaces in text values</strong></h4><p>Text imported from external sources may contain extra spaces, which can affect alphabetical sorting. Clean up these values before applying the sorting rules.</p><h4><strong>Including headers or totals rows</strong></h4><p>Make sure headers and totals rows aren’t treated as regular records. In these examples, IsIncludeTitle is set to False, and the sorting ranges exclude the header row. For Excel Tables with totals rows, exclude those rows as well.</p><h4><strong>Sorting workbooks containing formulas</strong></h4><p>If your worksheet includes formulas that depend on specific cell positions, verify the results after sorting. Saving the sorted workbook as a separate file lets you check the output without changing the original.</p><p>For more information about Excel’s sorting behavior, see <a href="https://support.microsoft.com/en-gb/excel/sort-data-in-a-range-or-table-in-excel">Microsoft’s guide to sorting data in Excel</a>.</p><h3>Conclusion</h3><p>Python provides a practical way to sort Excel data by a single column, multiple columns, cell formatting, or a custom order. When working with Excel Tables, you can also retrieve the table’s data range dynamically instead of hardcoding cell references.</p><p>Before sorting, make sure the selected range includes all related columns and excludes headers or totals rows. This helps keep records intact and prevents unexpected sorting results.</p><h3>See More Topics</h3><ul><li><a href="https://medium.com/@alice.yang_10652/how-to-perform-what-if-analysis-in-excel-using-python-scenario-manager-bdb3ff7a77b5">How to Perform What-If Analysis in Excel Using Python</a></li><li><a href="https://medium.com/@alice.yang_10652/how-to-add-edit-excel-vba-macros-in-python-without-excel-installed-1d75520bed52">How to Add &amp; Edit Excel VBA Macros in Python (Without Excel Installed)</a></li><li><a href="https://medium.com/@alice.yang_10652/how-to-add-and-manage-excel-slicers-in-python-a-practical-guide-a615022416bf">How to Add and Manage Excel Slicers in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94945b8410da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Markdown to PDF Methods Python Developers Should Try]]></title>
            <link>https://python.plainenglish.io/4-markdown-to-pdf-methods-python-developers-should-try-6a9a8d3e5df5?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a9a8d3e5df5</guid>
            <category><![CDATA[markdowntopdf]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[markdown-library]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 12:29:40 GMT</pubDate>
            <atom:updated>2026-11-05T12:29:40.357Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Markdown to PDF in Python (4 methods compared)" src="https://cdn-images-1.medium.com/max/650/1*1Q4PdUsdcCgUXJRNMAadRg.png" /><figcaption>Markdown to PDF in Python (4 methods compared)</figcaption></figure><p>Markdown is widely used for README files, technical documentation, project notes, and reports. It’s easy to write, works well with version control, and keeps content simple. However, when you need to share documentation with non-technical users, prepare printable reports, or archive finalized files, PDF is often a more convenient format.</p><p>Python offers several ways to convert Markdown to PDF. Some libraries handle the conversion directly, while others use HTML and CSS or provide document-processing APIs for additional control over the output.</p><p>In this article, we’ll explore four practical methods, with Python code examples, customization options, and a comparison to help you choose the right approach.</p><h3>Method 1: Convert Markdown to PDF with markdown-pdf</h3><p><strong>Suitable for:</strong> Generating PDFs from Markdown documentation with heading-based bookmarks and basic CSS styling.</p><p><a href="https://github.com/vb64/markdown-pdf">markdown-pdf</a> is an open-source Python library designed to convert Markdown content into PDF documents. It uses markdown-it-py for Markdown parsing and PyMuPDF for PDF generation.</p><p>The library supports common Markdown elements such as headings, lists, tables, images, and hyperlinks. It also offers options for creating PDF bookmarks, applying custom CSS, and using different page sizes.</p><h4>Install markdown-pdf</h4><p>Install the package using pip:</p><pre>pip install markdown-pdf</pre><h4>Convert a Markdown File to PDF</h4><p>The following example reads a Markdown file and converts it into a PDF with bookmarks generated from headings up to level 2.</p><pre>from pathlib import Path<br>from markdown_pdf import MarkdownPdf, Section<br> <br># Read the Markdown file<br>source = Path(&quot;README.md&quot;)<br>markdown_text = source.read_text(encoding=&quot;utf-8&quot;)<br> <br># Create the PDF converter<br>pdf = MarkdownPdf(toc_level=2)<br> <br># Add Markdown content<br>pdf.add_section(<br>    Section(markdown_text, root=str(source.resolve().parent))<br>)<br> <br># Save the PDF<br>pdf.save(&quot;README.pdf&quot;)</pre><p>Here, MarkdownPdf manages PDF generation, while Section holds the Markdown content. Setting toc_level=2 creates PDF bookmarks from first- and second-level headings.</p><p>The root parameter specifies the directory used to resolve relative image paths. This is useful when your Markdown file references images stored in a project folder.</p><h4>Customize the PDF with CSS</h4><p>You can also customize the appearance of the resulting PDF using CSS.</p><p>For example, replace the pdf.add_section() call in the previous example with:</p><pre>css = &quot;&quot;&quot;<br>h1, h2 {<br>    color: #24527a;<br>}<br> <br>table, th, td {<br>    border: 1px solid #cccccc;<br>    border-collapse: collapse;<br>}<br> <br>th, td {<br>    padding: 8px;<br>}<br>&quot;&quot;&quot;<br> <br>pdf.add_section(<br>    Section(markdown_text, root=str(source.resolve().parent)),<br>    user_css=css<br>)</pre><p>This changes heading colors and table formatting without modifying the original Markdown content.</p><p>For more specialized documentation, markdown-pdf also provides plugins for rendering diagrams created with Mermaid or PlantUML. Some plugin configurations rely on external services, so check how diagrams are processed before using them with sensitive documents.</p><h3>Method 2: Convert Markdown to PDF with Python-Markdown and WeasyPrint</h3><p><strong>Suitable for:</strong> Creating styled PDF reports with flexible HTML and CSS customization.</p><p>Another way to convert Markdown to PDF is to use HTML as an intermediate format. This approach combines two open-source Python libraries:</p><ul><li><a href="https://python-markdown.github.io/">Python-Markdown</a> converts Markdown content into HTML.</li><li><a href="https://weasyprint.org/">WeasyPrint</a> renders HTML and CSS into PDF documents.</li></ul><p>The main advantage is layout flexibility. You can use CSS to control page size, fonts, colors, spacing, tables, and other print-specific properties, making this approach useful for documents that need consistent visual styling.</p><h4>Install the Required Libraries</h4><pre>pip install markdown weasyprint</pre><p>Depending on your operating system, WeasyPrint may require additional native rendering libraries. Check its installation documentation if you encounter dependency-related errors.</p><h4>Convert Markdown to HTML and Then PDF</h4><p>The following example converts a Markdown report into an A4 PDF with custom heading, table, and code-block styles.</p><pre>from pathlib import Path<br>import markdown<br>from weasyprint import HTML, CSS<br> <br># Read the Markdown file<br>source = Path(&quot;report.md&quot;)<br>md_text = source.read_text(encoding=&quot;utf-8&quot;)<br> <br># Convert Markdown to HTML<br>html_body = markdown.markdown(<br>    md_text,<br>    extensions=[&quot;tables&quot;, &quot;fenced_code&quot;]<br>)<br> <br># Create the HTML document<br>html_content = f&quot;&quot;&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    {html_body}<br>&lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;<br> <br># Define PDF styles<br>css = CSS(string=&quot;&quot;&quot;<br>    @page {<br>        size: A4;<br>        margin: 20mm;<br>    }<br> <br>    body {<br>        font-family: sans-serif;<br>        font-size: 11pt;<br>        line-height: 1.6;<br>    }<br> <br>    h1, h2 {<br>        color: #24527a;<br>    }<br> <br>    pre {<br>        background: #f4f4f4;<br>        padding: 10px;<br>        white-space: pre-wrap;<br>    }<br> <br>    table {<br>        border-collapse: collapse;<br>        width: 100%;<br>    }<br> <br>    th, td {<br>        border: 1px solid #ccc;<br>        padding: 8px;<br>    }<br>&quot;&quot;&quot;)<br> <br># Generate the PDF<br>HTML(<br>    string=html_content,<br>    base_url=source.resolve().as_uri()<br>).write_pdf(&quot;report.pdf&quot;, stylesheets=[css])</pre><p>The tables and fenced_code extensions enable support for Markdown tables and fenced code blocks.</p><p>After converting Markdown into HTML, WeasyPrint uses the CSS stylesheet to control the PDF layout. In this example, the stylesheet defines A4 paper, 20 mm margins, heading colors, table borders, and code-block formatting.</p><p>The base_url parameter helps resolve relative image paths in the original Markdown file.</p><p>You can extend this approach with external stylesheets, reusable HTML templates, page headers and footers, or company branding.</p><p>The trade-off is additional setup. You need to manage Markdown parsing, HTML generation, CSS styles, and the rendering environment. However, this flexibility can be valuable when producing reports or documents with specific layout requirements.</p><h3>Method 3: Convert Markdown to PDF Directly with PyMuPDF</h3><p><strong>Suitable for:</strong> Direct Markdown-to-PDF conversion in applications that already use PyMuPDF for PDF processing.</p><p><a href="https://pymupdf.readthedocs.io/">PyMuPDF</a> is a Python library used for reading, modifying, and generating PDF documents. Recent versions also support opening Markdown files directly and converting them to PDF.</p><p>Unlike the HTML-based approach, you don’t need to manually convert Markdown into HTML before generating the PDF.</p><h4>Install PyMuPDF</h4><p>For the examples below, install PyMuPDF 1.28.0 or later:</p><pre>pip install &quot;pymupdf&gt;=1.28.0&quot;</pre><p>This version requirement ensures that the Markdown conversion and CSS customization APIs demonstrated below are available.</p><h4>Convert Markdown to PDF</h4><pre>import pymupdf<br> <br># Open the Markdown file<br>doc = pymupdf.open(<br>    &quot;README.md&quot;,<br>    rect=pymupdf.paper_rect(&quot;A4&quot;)<br>)<br> <br># Save as PDF<br>doc.ez_save(&quot;README.pdf&quot;)<br> <br># Release resources<br>doc.close()</pre><p>The pymupdf.open() method loads the Markdown document, while pymupdf.paper_rect(“A4”) specifies the page dimensions.</p><p>The ez_save() method saves the resulting document as a PDF.</p><p>This requires relatively little code and can fit naturally into applications that already use PyMuPDF for tasks such as extracting PDF content, combining files, or modifying existing PDFs.</p><h4>Customize the PDF with CSS</h4><p>PyMuPDF 1.28.0 introduced Document.apply_css(), which lets you apply supported CSS rules to Markdown documents.</p><p>For example:</p><pre>import pymupdf<br> <br># Open the Markdown file<br>doc = pymupdf.open(<br>    &quot;README.md&quot;,<br>    rect=pymupdf.paper_rect(&quot;A4&quot;)<br>)<br> <br># Define CSS styles<br>css = &quot;&quot;&quot;<br>h1 { color: #24527a; }<br>h2 { color: #4472c4; }<br>&quot;&quot;&quot;<br> <br># Apply CSS<br>doc.apply_css(css)<br> <br># Save the PDF<br>doc.ez_save(&quot;README_styled.pdf&quot;)<br>doc.close()</pre><p>This example changes the colors of first- and second-level headings.</p><p>However, PyMuPDF supports only a subset of CSS properties for Markdown documents. If your project requires complex HTML/CSS layouts, WeasyPrint offers more extensive styling capabilities.</p><h3>Method 4: Convert Markdown to PDF with Spire.Doc for Python</h3><p><strong>Suitable for:</strong> Converting Markdown to PDF in applications that also process Word documents or require document-level customization.</p><p>Unlike dedicated Markdown converters such as markdown-pdf, <a href="https://www.e-iceblue.com/Introduce/doc-for-python.html">Spire.Doc for Python</a> is a document-processing library primarily designed for creating, editing, and converting Word documents. It also supports working with other document formats, including Markdown, HTML, TXT, and RTF, and converting supported documents to formats such as PDF.</p><p>One advantage of this approach is that you can work with imported Markdown content through a document object model. This allows you to adjust page settings and configure PDF export options without building a separate HTML/CSS conversion pipeline.</p><h4>Install Spire.Doc for Python</h4><p>Install the library using pip:</p><pre>pip install Spire.Doc</pre><p>Markdown import and conversion are supported in Spire.Doc for Python 12.6.0 and later.</p><h4>Convert a Markdown File to PDF</h4><p>The following example loads a Markdown file and saves it as PDF.</p><pre>from spire.doc import Document, FileFormat<br> <br># Load the Markdown file<br>doc = Document()<br>doc.LoadFromFile(&quot;README.md&quot;, FileFormat.Markdown)<br> <br># Convert Markdown to PDF<br>doc.SaveToFile(&quot;README.pdf&quot;, FileFormat.PDF)<br> <br># Release resources<br>doc.Dispose()</pre><p>The LoadFromFile() method reads the Markdown document, while SaveToFile() exports it in PDF format.</p><h4>Customize the PDF Page Layout</h4><p>For reports and printable documentation, you may need to adjust the page size, orientation, or margins before generating the PDF.</p><p>Spire.Doc provides the PageSetup API for configuring these properties after importing the Markdown file.</p><p>The following example sets the page size to A4, uses portrait orientation, and applies 50-point margins.</p><pre>from spire.doc import (<br>    Document, FileFormat,<br>    PageSize, PageOrientation<br>)<br> <br># Load the Markdown file<br>doc = Document()<br>doc.LoadFromFile(&quot;report.md&quot;, FileFormat.Markdown)<br> <br># Configure page settings for every section<br>for i in range(doc.Sections.Count):<br>    section = doc.Sections.get_Item(i)<br>    page_setup = section.PageSetup<br> <br>    page_setup.PageSize = PageSize.A4()<br>    page_setup.Orientation = PageOrientation.Portrait<br>    page_setup.Margins.All = 50<br> <br># Export to PDF<br>doc.SaveToFile(&quot;report.pdf&quot;, FileFormat.PDF)<br> <br>doc.Dispose()</pre><p>This gives you control over basic print-layout settings without requiring CSS. For example, changing PageOrientation.Portrait to PageOrientation.Landscape may help accommodate documents containing wide tables.</p><h4>Additional PDF Export Options</h4><p>For applications with specific PDF output requirements, Spire.Doc also provides ToPdfParameterList, which allows you to configure options such as PDF bookmarks, PDF/A conformance, and document security.</p><p>To use these options, create a ToPdfParameterList object:</p><pre>from spire.doc import ToPdfParameterList<br><br>parameters = ToPdfParameterList()</pre><p>You can then apply the settings you need, as shown below.</p><p><strong>Generate PDF Bookmarks from Headings</strong></p><p>For longer documents, PDF bookmarks can help readers navigate between sections.</p><pre>parameters.CreateWordBookmarksUsingHeadings = True</pre><p>This option generates PDF bookmarks from recognized document heading styles.</p><p>Since the input is Markdown, the result depends on how headings are represented after import. Check the generated PDF to confirm that the bookmarks correspond to the original Markdown headings.</p><p><strong>Export Markdown as PDF/A for Long-Term Archiving</strong></p><p>If you’re converting Markdown reports or technical documentation for long-term preservation, you can request PDF/A output, an ISO-standardized PDF format designed for digital archiving.</p><p>For example, the following setting requests PDF/A-1b:</p><pre>from spire.doc import PdfConformanceLevel<br><br>parameters.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1B</pre><p>PDF/A-1b focuses on preserving the document’s visual appearance over time. For workflows with strict archival requirements, validate the generated PDF using a tool such as <a href="https://verapdf.org/">veraPDF</a> to confirm that it meets the required standard.</p><p><strong>Protect the PDF with a Password</strong></p><p>For internal documentation or reports that require restricted access, you can configure PDF encryption with an opening password and an owner password.</p><pre>from spire.doc import PdfPermissionsFlags, PdfEncryptionKeySize<br><br>parameters.PdfSecurity.Encrypt(<br>    &quot;viewer123&quot;,<br>    &quot;owner456&quot;,<br>    PdfPermissionsFlags.Default,<br>    PdfEncryptionKeySize.Key128Bit<br>)</pre><p>The opening password controls access to the PDF, while the owner password is associated with document permissions. Replace these demonstration passwords with securely managed credentials in production.</p><p><strong>Note:</strong> PDF/A-1b does not permit encryption, so do not combine PDF/A export and password protection in the same conversion.</p><p>After configuring the required options, save the document as PDF using the parameter object:</p><pre>doc.SaveToFile(&quot;report.pdf&quot;, parameters)<br><br>doc.Dispose()</pre><h3>Comparing the Four Markdown-to-PDF Methods</h3><p>All four methods can generate PDFs from Markdown, but they differ in customization capabilities, setup requirements, licensing, and the workflows they support.</p><pre><br>| Method                       | Key Strengths                                                                                   | Main Limitations                              | Suitable For                                       | License / Availability            |<br>|------------------------------|-------------------------------------------------------------------------------------------------|-----------------------------------------------|----------------------------------------------------|-----------------------------------|<br>| markdown-pdf                 | Markdown-focused API, CSS customization, heading-based bookmarks                                | Specialized syntax may need additional handling | README files, user guides, technical documentation | Open source (AGPL-3.0)            |<br>| Python-Markdown + WeasyPrint | Flexible HTML/CSS styling and print-layout control                                              | Additional setup and native rendering dependencies | Styled reports and reusable PDF templates         | Open source (BSD licenses)        |<br>| PyMuPDF                      | Direct Markdown input, concise API, PDF-processing functionality                                | Limited CSS support; version requirements     | Simple conversions and existing PDF workflows      | AGPL / commercial                 |<br>| Spire.Doc for Python         | Document object model, page settings, PDF export options, support for multiple document formats | Complex Markdown syntax requires testing      | Integrated Markdown and Word processing workflows  | Limited free edition / commercial |</pre><h3>Which Method Should You Choose?</h3><p>For straightforward Markdown-to-PDF conversion, <strong>PyMuPDF</strong> and <strong>markdown-pdf</strong> are both worth considering. PyMuPDF is convenient when you already use it for PDF processing, while markdown-pdf provides Markdown-focused features such as heading-based bookmarks.</p><p>If you need carefully styled reports, <strong>Python-Markdown with WeasyPrint</strong> offers greater control through HTML and CSS. <strong>Spire.Doc for Python</strong> is more relevant when PDF generation is part of a broader workflow involving Markdown, Word documents, or document-level customization.</p><p>Beyond functionality, consider installation requirements and how well each library handles the Markdown syntax used in your project.</p><h3>Common Markdown-to-PDF Conversion Issues</h3><p>Even when a conversion succeeds, the resulting PDF may not look exactly like the Markdown preview in your editor.</p><h4>1. Images Are Missing</h4><p>Markdown files often reference images using relative paths:</p><pre>![Architecture Diagram](images/architecture.png)</pre><p>If the converter cannot locate the image, it may not appear in the resulting PDF.</p><p>Check that the image exists and that the converter can resolve its path. Where supported, configure a root directory or base URL for relative resources.</p><h4>2. Tables Extend Beyond the Page</h4><p>Wide tables may overflow the printable area, especially when they contain long descriptions or multiple columns.</p><p>Depending on the converter, you can adjust page orientation, font sizes, column widths, or table styling. CSS-based approaches provide more detailed control, while document-processing libraries allow you to modify page settings.</p><h4>3. Code Blocks Lose Their Formatting</h4><p>Fenced code blocks are common in technical documentation:</p><pre>print(&quot;Hello, PDF!&quot;)</pre><p>However, converters differ in how they handle code formatting and syntax highlighting.</p><p>Make sure your Markdown parser supports fenced code blocks. If syntax highlighting is required, you may need an additional extension, plugin, or stylesheet.</p><h4>4. Special Markdown Features Are Not Rendered</h4><p>Features such as task lists, Mermaid diagrams, mathematical expressions, and embedded HTML are not supported uniformly across Markdown converters.</p><p>Check which Markdown extensions your project uses and whether your chosen tool supports them directly or requires preprocessing.</p><h3>Conclusion</h3><p>There’s no single best way to convert Markdown to PDF in Python. The right approach depends on your document structure, formatting requirements, and existing workflow.</p><p>Before settling on a library, try it with a representative Markdown file containing tables, images, code blocks, and other elements your project relies on. This will help you identify rendering differences before integrating the conversion into your application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a9a8d3e5df5" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/4-markdown-to-pdf-methods-python-developers-should-try-6a9a8d3e5df5">4 Markdown to PDF Methods Python Developers Should Try</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Compare Two PDF Files in Python]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-compare-two-pdf-files-in-python-c0d791d97f27?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0d791d97f27</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[compare-pdf]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 10:59:06 GMT</pubDate>
            <atom:updated>2026-10-30T10:59:06.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*c4JC3cp3pWmudmUb25Efew.png" /><figcaption>Compare PDF Files in Python</figcaption></figure><p>When reviewing an updated contract, financial report, or technical document, identifying exactly what changed between two PDF versions isn’t always straightforward. Even small revisions can be difficult to spot when the files contain dozens of pages.</p><p>Instead of comparing pages manually, you can use Python to detect differences between PDF files and generate a comparison report with the changes highlighted.</p><p>In this article, we’ll cover four practical scenarios:</p><ul><li>Compare two PDF documents.</li><li>Compare specific pages from two PDFs.</li><li>Compare only text differences between PDFs.</li><li>Batch compare multiple pairs of PDF files.</li></ul><h3>Install the Required Python Library</h3><p>We’ll use <a href="https://www.e-iceblue.com/Introduce/pdf-for-python.html">Spire.PDF for Python</a>, which supports comparing PDF documents and generating PDF reports with highlighted differences. It works without requiring Adobe Acrobat to be installed.</p><p>Install the library using pip:</p><pre>pip install Spire.PDF</pre><h3>Compare Two PDF Documents in Python</h3><p>To compare two PDF files, load both documents into PdfDocument objects and pass them to PdfComparer. The Compare() method generates a new PDF containing the comparison results.</p><p>The following example compares an original project proposal with a revised version that contains changes to its budget, delivery schedule, and support terms.</p><pre>from spire.pdf import *<br>from spire.pdf.common import *<br><br># Load the original PDF<br>original = PdfDocument()<br>original.LoadFromFile(&quot;proposal_original.pdf&quot;)<br><br># Load the revised PDF<br>revised = PdfDocument()<br>revised.LoadFromFile(&quot;proposal_revised.pdf&quot;)<br><br># Create a comparer<br>comparer = PdfComparer(original, revised)<br># Compare the two PDFs<br>comparer.Compare(&quot;comparison_result.pdf&quot;)<br><br># Release resources<br>original.Dispose()<br>revised.Dispose()</pre><p>The generated comparison_result.pdf presents the two document versions with detected differences marked for review. This makes it easier to identify changes without switching back and forth between the original and revised files.</p><h3>Compare Specific PDF Pages in Python</h3><p>Sometimes, only part of a document needs to be compared. For example, you may have two versions of a 40-page financial report, but only the revenue analysis section has been updated.</p><p>In this case, you can use PdfCompareOptions.SetPageRanges() to limit the comparison to specific pages instead of processing the entire document.</p><p>The following example compares the first three pages of two PDF files:</p><pre>from spire.pdf import *<br>from spire.pdf.common import *<br><br># Load two PDF versions<br>original = PdfDocument()<br>original.LoadFromFile(&quot;report_original.pdf&quot;)<br><br>revised = PdfDocument()<br>revised.LoadFromFile(&quot;report_revised.pdf&quot;)<br><br># Create a comparer<br>comparer = PdfComparer(original, revised)<br># Compare the first three pages<br>comparer.PdfCompareOptions.SetPageRanges(0, 2, 0, 2)<br># Save the comparison result<br>comparer.Compare(&quot;selected_pages_comparison.pdf&quot;)<br><br># Release resources<br>original.Dispose()<br>revised.Dispose()</pre><p>The SetPageRanges() method takes four parameters:</p><pre>SetPageRanges(start1, end1, start2, end2)</pre><p>The first two specify the page indexes in the original PDF, while the last two specify the indexes in the revised PDF. Page indexes start at 0, and the specified endpoints are included.</p><p>You can also compare different page ranges. For example, if a section originally appeared on pages 5–7 but moved to pages 6–8 in the revised document, use:</p><pre># Compare pages 5–7 with pages 6–8<br>comparer.PdfCompareOptions.SetPageRanges(4, 6, 5, 7)</pre><p>This is useful when pages have been inserted or when corresponding sections appear at different positions in the two files.</p><h3>Compare PDF Text Only in Python</h3><p>Not every difference between two PDFs involves changes to the text. Sometimes, a revised document contains updated images, graphics, or other visual elements while the wording remains the same.</p><p>If you’re mainly interested in textual changes, you can use the PdfCompareOptions.OnlyCompareText property to enable text-only comparison.</p><p>The following example compares the text content of two PDF documents:</p><pre>from spire.pdf import *<br>from spire.pdf.common import *<br><br># Load the original and revised PDFs<br>original = PdfDocument()<br>original.LoadFromFile(&quot;contract_original.pdf&quot;)<br><br>revised = PdfDocument()<br>revised.LoadFromFile(&quot;contract_revised.pdf&quot;)<br><br># Create a comparer<br>comparer = PdfComparer(original, revised)<br># Compare text content only<br>comparer.PdfCompareOptions.OnlyCompareText = True<br># Save the comparison result<br>comparer.Compare(&quot;text_comparison.pdf&quot;)<br><br># Release resources<br>original.Dispose()<br>revised.Dispose()</pre><p>Setting OnlyCompareText to True instructs the comparer to focus on text differences rather than non-text visual changes.</p><p>This can be useful when reviewing contract wording, policy revisions, or other documents where textual changes are the main concern.</p><p>Keep in mind that text-only comparison is not the same as comparing two plain-text files. Differences in PDF text extraction or reading order may still affect the results, especially in documents with complex layouts.</p><p>Also, this option does not perform OCR. For scanned PDFs that contain only page images, text recognition may be necessary before meaningful textual differences can be identified.</p><h3>Batch Compare Multiple PDF Files in Python</h3><p>If you regularly work with revised reports, contracts, or technical documents, comparing each pair individually can become repetitive.</p><p>Python’s pathlib module allows you to find matching PDF files in a folder and generate comparison reports automatically.</p><p>Suppose your files are organized like this:</p><pre>pdf_versions/<br>    finance_original.pdf<br>    finance_revised.pdf<br>    sales_original.pdf<br>    sales_revised.pdf<br>    operations_original.pdf<br>    operations_revised.pdf</pre><p>Each document has an original version and a revised version. The following script identifies matching pairs and saves their comparison results to a separate folder.</p><pre>from pathlib import Path<br>from spire.pdf import *<br>from spire.pdf.common import *<br><br># Define input and output folders<br>input_dir = Path(&quot;pdf_versions&quot;)<br>output_dir = Path(&quot;comparison_results&quot;)<br>output_dir.mkdir(parents=True, exist_ok=True)<br><br># Find all original PDF files<br>for original_path in input_dir.glob(&quot;*_original.pdf&quot;):<br>    # Find the corresponding revised file<br>    revised_path = input_dir / original_path.name.replace(<br>        &quot;_original.pdf&quot;, &quot;_revised.pdf&quot;<br>    )<br>    if not revised_path.exists():<br>        print(f&quot;Missing revised file: {revised_path.name}&quot;)<br>        continue<br>    # Define the output file<br>    output_name = original_path.name.replace(<br>        &quot;_original.pdf&quot;, &quot;_comparison.pdf&quot;<br>    )<br>    output_path = output_dir / output_name<br>    original = PdfDocument()<br>    revised = PdfDocument()<br><br>    try:<br>        # Load both PDF versions<br>        original.LoadFromFile(str(original_path))<br>        revised.LoadFromFile(str(revised_path))<br>        # Compare and save the result<br>        comparer = PdfComparer(original, revised)<br>        comparer.Compare(str(output_path))<br>        print(f&quot;Created: {output_path.name}&quot;)<br>    except Exception as e:<br>        print(f&quot;Failed to compare {original_path.name}: {e}&quot;)<br>    finally:<br>        original.Dispose()<br>        revised.Dispose()</pre><p>The script matches each _original.pdf file with its corresponding _revised.pdf version and saves the comparison reports in the comparison_results folder. Missing files and failed comparisons are reported without interrupting the remaining tasks.</p><p>After processing the files, the output folder will contain:</p><pre>comparison_results/<br>    finance_comparison.pdf<br>    sales_comparison.pdf<br>    operations_comparison.pdf</pre><p>You can adjust the filename pattern to match how documents are named in your project.</p><h3>Things to Consider When Comparing PDFs</h3><p>Although automated comparison can help identify document changes, a few factors may affect the results.</p><p><strong>1. Page layout and formatting differences</strong></p><p>Changes to fonts, margins, line spacing, or page sizes may shift content between pages. Even when the text remains unchanged, these layout differences can affect the comparison results.</p><p><strong>2. Scanned or image-based PDFs</strong></p><p>Scanned PDFs usually contain page images rather than selectable text. Comparing these documents may reveal visual differences, but identifying individual word or sentence changes can require OCR.</p><p><strong>3. Inserted or removed pages</strong></p><p>Adding or deleting pages can shift subsequent content. When comparing selected page ranges, make sure they refer to the corresponding sections in both documents.</p><p><strong>4. Password-protected PDFs</strong></p><p>If either document is encrypted, you may need to provide the correct password when loading it. Both PDFs must be opened successfully before the comparison can proceed.</p><p>For important documents such as contracts and financial statements, always review the generated comparison report. Automated comparison can identify differences, but it cannot determine whether a particular change is correct or intentional.</p><h3>PDF Comparison vs. Word Document Comparison</h3><p>If you’re working with editable Word documents rather than finalized PDFs, comparing the original DOCX files may provide more useful revision information.</p><p>Word comparison works with the document’s editable structure and can produce tracked revisions, making it easier to inspect inserted, deleted, or modified content. PDF comparison, on the other hand, is useful when documents are already in PDF format and you need to review differences between versions.</p><p>If you have access to the original Word files and need detailed revision tracking, see our blog on <a href="https://medium.com/@alice.yang_10652/mastering-word-document-comparison-in-python-a-complete-guide-a0e8dee85ff8">comparing Word documents in Python</a>.</p><h3>Conclusion</h3><p>Python provides several ways to compare PDF versions, whether you need to review entire documents, focus on specific pages, examine text changes, or process multiple file pairs.</p><p>By selecting the appropriate comparison options, you can focus on the changes relevant to your task and generate PDF reports for further review. For important revisions, checking the detected differences remains an essential part of the process.</p><h3>See Also</h3><ul><li><a href="https://medium.com/@alice.yang_10652/how-to-convert-pdf-to-markdown-complete-guide-27f072b1c18e">How to Convert PDF to Markdown in Python: Complete Guide</a></li><li><a href="https://medium.com/@alice.yang_10652/split-pdf-files-or-pages-with-python-7721b656d987">Split PDF Files or Pages with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/merge-pdf-files-or-pages-into-one-with-python-301b1bbdaf7e">Merge PDF Files or Pages into One with Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0d791d97f27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Perform What-If Analysis in Excel Using Python (Scenario Manager)]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-perform-what-if-analysis-in-excel-using-python-scenario-manager-bdb3ff7a77b5?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdb3ff7a77b5</guid>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[what-if-analysis]]></category>
            <category><![CDATA[scenario-manager]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 06:40:25 GMT</pubDate>
            <atom:updated>2026-10-22T06:40:25.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="What-If Analysis in Excel with Python" src="https://cdn-images-1.medium.com/max/650/1*_sVZbSPpzJ03chYmr3fCeA.png" /><figcaption>What-If Analysis in Excel with Python</figcaption></figure><p>What happens to your profit if sales drop by 20%? How much could you earn if demand increases and production costs decrease? When preparing a sales forecast or budget, exploring different possibilities is an important part of planning.</p><p>Excel’s <a href="https://support.microsoft.com/en-us/excel/introduction-to-what-if-analysis">What-If Analysis</a> lets you change input values to see how they affect formula results. One of its tools, Scenario Manager, allows you to save different sets of assumptions, switch between them, and compare the outcomes without creating separate workbooks.</p><p>In this tutorial, we’ll use Python to put Scenario Manager into practice with a simple sales forecast. We’ll explore how to create and manage scenarios, generate summary reports, and visualize the results with an Excel chart.</p><h3>Understanding What-If Analysis Tools in Excel</h3><p>Microsoft Excel provides three main What-If Analysis tools:</p><ul><li><strong>Scenario Manager:</strong> Saves and compares different sets of input values.</li><li><strong>Goal Seek:</strong> Finds the input value needed to achieve a specific formula result.</li><li><strong>Data Table:</strong> Calculates how different values of one or two variables affect formula results.</li></ul><p>This article focuses on <strong>Scenario Manager</strong>, which is useful when you want to compare several predefined situations, such as pessimistic, expected, and optimistic sales forecasts.</p><p>For example, suppose a company wants to estimate its profit under three different sales conditions:</p><pre><br>| Variable             | Pessimistic | Expected   | Optimistic |<br>|:---------------------|------------:|-----------:|-----------:|<br>| Selling Price        | $90         | $100       | $110       |<br>| Unit Cost            | $65         | $60        | $55        |<br>| Units Sold           | 800         | 1,000      | 1,300      |<br>| Projected Profit     | $20,000     | $40,000    | $71,500    |</pre><p>The projected profit is calculated using:</p><p>Projected Profit = (Selling Price — Unit Cost) × Units Sold</p><p>Instead of manually replacing the input values each time, we can store these assumptions as separate Excel scenarios and compare their results whenever needed.</p><h3>Set Up the Excel Workbook and Python Environment</h3><p>For this tutorial, we’ll use <a href="https://www.e-iceblue.com/Introduce/xls-for-python.html">Spire.XLS for Python</a>, which provides APIs for working with Excel files, including creating and managing scenarios, without requiring Microsoft Excel to be installed.</p><p>Install the library using pip:</p><pre>pip install spire.xls</pre><p>Scenario Manager support was introduced in version 16.7.1, so make sure you are using that version or a later one.</p><h4>Prepare a Sales Forecast Workbook</h4><p>Let’s start with an Excel worksheet containing three input variables and a profit calculation.</p><pre><br>| Cell | Description      | Value           |<br>|:-----|:-----------------|----------------:|<br>| B2   | Selling Price    | 100             |<br>| B3   | Unit Cost        | 60              |<br>| B4   | Units Sold       | 1,000           |<br>| B6   | Projected Profit | =(B2-B3)*B4     |</pre><p>Cells <strong>B2:B4</strong> are the <em>changing cells</em>, which contain the input values that vary between scenarios. Cell <strong>B6</strong> is the <em>result cell</em>, which calculates the projected profit.</p><p>You can prepare this worksheet manually in Excel or create it with Python:</p><pre>from spire.xls import Workbook, ExcelVersion<br><br>workbook = Workbook()<br>sheet = workbook.Worksheets[0]<br>sheet.Name = &quot;Sales Forecast&quot;<br><br># Add labels<br>sheet.Range[&quot;A1&quot;].Text = &quot;Quarterly Sales Forecast&quot;<br>sheet.Range[&quot;A2&quot;].Text = &quot;Selling Price&quot;<br>sheet.Range[&quot;A3&quot;].Text = &quot;Unit Cost&quot;<br>sheet.Range[&quot;A4&quot;].Text = &quot;Units Sold&quot;<br>sheet.Range[&quot;A6&quot;].Text = &quot;Projected Profit&quot;<br><br># Enter initial values<br>sheet.Range[&quot;B2&quot;].NumberValue = 100<br>sheet.Range[&quot;B3&quot;].NumberValue = 60<br>sheet.Range[&quot;B4&quot;].NumberValue = 1000<br><br># Calculate projected profit<br>sheet.Range[&quot;B6&quot;].Formula = &quot;=(B2-B3)*B4&quot;<br><br># Set column width for better visibility<br>sheet.SetColumnWidth(1, 26.0)<br><br># Save the workbook<br>workbook.SaveToFile(&quot;sales_model.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>This creates sales_model.xlsx, which we’ll use for the following examples.</p><h3>1. Create Multiple Scenarios in Excel Using Python</h3><p>Let’s begin by creating three scenarios based on our sales assumptions.</p><p>Each scenario needs a name, a range of changing cells, and a corresponding set of values. We can define these using the <strong>Scenarios.Add()</strong> method.</p><pre>from spire.xls import Workbook, ExcelVersion<br><br># Load the sales forecast<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;sales_model.xlsx&quot;)<br><br>sheet = workbook.Worksheets[0]<br>scenarios = sheet.Scenarios<br><br># Define scenario values<br>pessimistic = [90, 65, 800]<br>expected = [100, 60, 1000]<br>optimistic = [110, 55, 1300]<br><br># Specify the changing cells<br>changing_cells = sheet.Range[&quot;B2:B4&quot;]<br><br># Create three scenarios<br>scenarios.Add(&quot;Pessimistic&quot;, changing_cells, pessimistic)<br>scenarios.Add(&quot;Expected&quot;, changing_cells, expected)<br>scenarios.Add(&quot;Optimistic&quot;, changing_cells, optimistic)<br><br># Save the workbook<br>workbook.SaveToFile(&quot;sales_scenarios.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>Each list contains the selling price, unit cost, and units sold, in that order. These values are associated with cells B2, B3, and B4, respectively.</p><p>The scenarios are stored in the workbook without changing the existing profit formula. To view them in Microsoft Excel, open sales_scenarios.xlsx and go to:</p><p><strong>Data → What-If Analysis → Scenario Manager</strong></p><p>You’ll find the three saved scenarios, which can be selected and applied without manually re-entering their values.</p><h3>2. Apply a Scenario to the Worksheet</h3><p>Creating scenarios stores different sets of assumptions, but it doesn’t mean all their values are applied to the worksheet simultaneously.</p><p>To examine a particular outcome, use the <strong>Scenario.Show()</strong> method to apply the corresponding scenario.</p><p>For example, let’s apply the Optimistic scenario:</p><pre>from spire.xls import Workbook, ExcelVersion<br><br># Load the workbook containing scenarios<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;sales_scenarios.xlsx&quot;)<br><br>sheet = workbook.Worksheets[0]<br>scenarios = sheet.Scenarios<br><br># Apply the optimistic scenario<br>scenarios[2].Show()<br><br># Save the updated workbook<br>workbook.SaveToFile(&quot;optimistic_forecast.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>Here, <strong>scenarios[2]</strong> refers to the third scenario because the collection uses zero-based indexing.</p><p>After applying the scenario, the worksheet contains these input values:</p><ul><li>Selling Price: $110</li><li>Unit Cost: $55</li><li>Units Sold: 1,300</li></ul><p>The profit formula then produces:</p><p>(110–55) × 1300 = $71,500</p><p>Notice that <strong>Show()</strong> updates the input cells, not the formula itself. This allows you to evaluate different assumptions while keeping the calculation logic unchanged.</p><h3>3. Generate a Scenario Summary Report in Python</h3><p>Switching between scenarios works well when examining individual outcomes. However, comparing several scenarios becomes easier when their results are displayed together.</p><p>Excel’s Scenario Manager can generate a <strong>Scenario Summary Report</strong>, which lists the changing values and corresponding calculation results for each scenario.</p><p>To generate one, call <strong>Scenarios.Summary()</strong> and specify the result cell:</p><pre>from spire.xls import Workbook, ExcelVersion<br><br># Load the workbook containing scenarios<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;sales_scenarios.xlsx&quot;)<br><br>sheet = workbook.Worksheets[0]<br><br># Generate a summary report using the profit cell<br>sheet.Scenarios.Summary(sheet.Range[&quot;B6&quot;])<br><br># Save the workbook with the summary report<br>workbook.SaveToFile(&quot;scenario_summary.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>Here, B6 contains the formula used to calculate projected profit.</p><p>The report brings together the different assumptions and their calculated outcomes. For our sales forecast, the results are:</p><pre><br>| Scenario    | Projected Profit |<br>|:------------|-----------------:|<br>| Pessimistic | $20,000          |<br>| Expected    | $40,000          |<br>| Optimistic  | $71,500          |</pre><p>This makes it easier to compare potential outcomes without repeatedly applying each scenario.</p><p>One thing to keep in mind is that <strong>scenario summary reports are snapshots</strong>. If you change the scenarios or their underlying formulas later, the existing report won’t automatically update. You’ll need to generate a new summary.</p><h3>4. Visualize Scenario Results with an Excel Chart</h3><p>A summary report is useful for comparing numbers, but a chart can make the differences easier to see.</p><p>Since we’re comparing three distinct scenarios, a clustered column chart is a natural choice. We can create one directly in Excel using the profit results from our earlier analysis.</p><p>The example below adds a new worksheet, writes the scenario results into cells, and creates an Excel chart based on those values.</p><pre>from spire.xls import Workbook, ExcelVersion, ExcelChartType<br><br># Results from the three sales scenarios<br>scenarios = [&quot;Pessimistic&quot;, &quot;Expected&quot;, &quot;Optimistic&quot;]<br>profits = [20000, 40000, 71500]<br><br># Load the workbook containing the scenario summary<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;scenario_summary.xlsx&quot;)<br><br># Add a worksheet for visualization<br>sheet = workbook.Worksheets.Add(&quot;Scenario Chart&quot;)<br><br># Add headers<br>sheet.Range[&quot;A1&quot;].Text = &quot;Scenario&quot;<br>sheet.Range[&quot;B1&quot;].Text = &quot;Projected Profit&quot;<br><br># Write scenario results into the worksheet<br>for i, (scenario, profit) in enumerate(zip(scenarios, profits), 2):<br>    sheet.Range[i, 1].Text = scenario<br>    sheet.Range[i, 2].NumberValue = profit<br><br># Create a clustered column chart<br>chart = sheet.Charts.Add(ExcelChartType.ColumnClustered)<br><br># Set the chart data range<br>chart.DataRange = sheet.Range[&quot;A1:B4&quot;]<br>chart.SeriesDataFromRange = False<br><br># Set the chart title and position<br>chart.ChartTitle = &quot;Projected Profit by Scenario&quot;<br>chart.LeftColumn = 4<br>chart.TopRow = 2<br>chart.RightColumn = 13<br>chart.BottomRow = 20<br><br># Save the workbook<br>workbook.SaveToFile(&quot;scenario_analysis.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>The resulting workbook contains a column chart comparing the projected profits of the Pessimistic, Expected, and Optimistic scenarios.</p><p>The differences are immediately visible: projected profit ranges from $20,000 in the pessimistic case to $71,500 in the optimistic case.</p><p>Unlike an image generated by an external plotting tool, this chart is part of the Excel workbook. You can open it in Excel, change its formatting, or modify the underlying chart data.</p><p><strong>Note:</strong> This example uses the previously calculated profit values rather than reading them directly from the Scenario Summary Report. If the scenario assumptions change, you’ll need to update the comparison data as well.</p><p><em>For more Excel charting options, see </em><a href="https://medium.com/@alice.yang_10652/create-various-types-of-charts-in-excel-with-python-e6509194a21a"><em>Create Various Types of Charts in Excel with Python</em></a><em>, which covers column, line, pie, histogram, waterfall, and other chart types.</em></p><h3>5. Modify an Existing Scenario in Excel</h3><p>Forecasting assumptions often change as new information becomes available.</p><p>Suppose our original pessimistic forecast was too conservative. After reviewing updated sales estimates, we want to revise it to:</p><ul><li>Selling Price: $95</li><li>Unit Cost: $65</li><li>Units Sold: 900</li></ul><p>There’s no need to delete the existing scenario and create another one. We can update its changing cells and values using <strong>SetVariableCells()</strong>.</p><pre>from spire.xls import Workbook, ExcelVersion<br><br># Load the workbook containing scenarios<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;sales_scenarios.xlsx&quot;)<br><br>sheet = workbook.Worksheets[0]<br>scenarios = sheet.Scenarios<br><br># Get the pessimistic scenario<br>scenario = scenarios[0]<br><br># Define the updated assumptions<br>new_values = [95, 65, 900]<br><br># Update the existing scenario<br>scenario.SetVariableCells(<br>    sheet.Range[&quot;B2:B4&quot;],<br>    new_values<br>)<br><br># Apply the updated scenario<br>scenario.Show()<br><br># Save the workbook<br>workbook.SaveToFile(&quot;revised_forecast.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>The revised profit is:</p><p>(95–65) × 900 = $27,000</p><p><strong>SetVariableCells()</strong> changes the values stored in the scenario, while <strong>Show()</strong> applies those updated values to the worksheet.</p><p>If you only want to update the saved scenario without applying it immediately, you can omit the Show() call.</p><p>This distinction is useful when maintaining multiple scenarios over time. You can revise their assumptions without immediately changing the worksheet’s current values.</p><h3>6. Delete Scenarios That Are No Longer Needed</h3><p>As forecasts evolve, some scenarios may become outdated.</p><p>For example, suppose we no longer need the original Pessimistic scenario. We can remove it from the workbook using either its name or index. The available methods include:</p><ul><li><strong>RemoveScenarioAt(index)</strong> — removes a scenario by its position.</li><li><strong>RemoveScenarioByName(name)</strong> — removes a scenario by its name.</li></ul><p>To avoid attempting to delete a scenario that doesn’t exist, we can first check the collection using <strong>ContainsScenario()</strong>.</p><p>The following example removes the Pessimistic scenario.</p><pre>from spire.xls import Workbook, ExcelVersion<br><br># Load the workbook<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;sales_scenarios.xlsx&quot;)<br><br>sheet = workbook.Worksheets[0]<br>scenarios = sheet.Scenarios<br><br># Remove the scenario if it exists<br>if scenarios.ContainsScenario(&quot;Pessimistic&quot;):<br>    scenarios.RemoveScenarioByName(&quot;Pessimistic&quot;)<br><br># Check the remaining scenario count<br>print(&quot;Remaining scenarios:&quot;, scenarios.Count)<br><br># Save the updated workbook<br>workbook.SaveToFile(&quot;updated_scenarios.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>After running the code, the workbook retains the Expected and Optimistic scenarios.</p><p>Removing a scenario deletes its saved assumptions, but it doesn’t remove the worksheet’s existing cell values or formulas.</p><h3>7. Merge Scenarios from Different Worksheets</h3><p>Sometimes, scenarios are prepared by different teams or maintained in separate worksheets.</p><p>For example, a sales team might define several revenue forecasts, while a finance team prepares an additional scenario that accounts for higher operating costs.</p><p>If the worksheets use the same changing-cell structure, their scenarios can be combined using <strong>Scenarios.Merge()</strong>.</p><p>Let’s add a Higher Costs scenario to a second worksheet and merge it into the main sales forecast.</p><pre>from spire.xls import Workbook, ExcelVersion<br><br># Load the existing sales scenarios<br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;sales_scenarios.xlsx&quot;)<br><br># Get the destination worksheet<br>main_sheet = workbook.Worksheets[0]<br><br># Create a worksheet for the finance scenario<br>finance_sheet = workbook.Worksheets.Add(&quot;Finance Scenario&quot;)<br><br># Create a scenario using the same changing-cell layout<br>finance_sheet.Scenarios.Add(<br>    &quot;Higher Costs&quot;,<br>    finance_sheet.Range[&quot;B2:B4&quot;],<br>    [100, 70, 1000]<br>)<br><br># Merge the finance scenario into the main worksheet<br>main_sheet.Scenarios.Merge(finance_sheet)<br><br># Save the workbook<br>workbook.SaveToFile(&quot;merged_scenarios.xlsx&quot;, ExcelVersion.Version2016)<br>workbook.Dispose()</pre><p>The main worksheet now contains the original sales scenarios along with the Higher Costs scenario.</p><p>With a selling price of $100, a unit cost of $70, and 1,000 units sold, this additional scenario produces a projected profit of $30,000.</p><p>When merging scenarios, it’s important to ensure that the changing cells represent the same variables in both worksheets. Otherwise, the merged assumptions may not match the intended calculation model.</p><h3>Best Practices for What-If Analysis in Excel</h3><p>When working with Excel scenarios, a few practices can help keep your analysis reliable and easy to maintain.</p><h4>1. Keep changing cells separate from formulas.</h4><p>Scenarios should modify input assumptions, not overwrite the formulas used to calculate the results. Clearly identify the changing cells and result cells before creating scenarios.</p><h4>2. Use descriptive scenario names.</h4><p>Names such as “Higher Costs,” “Reduced Demand,” or “Optimistic Sales” are more informative than generic labels such as “Scenario 1” or “Scenario 2.”</p><h4>3. Keep Excel’s changing-cell limit in mind.</h4><p>A single Excel scenario can contain up to 32 changing cells. For analyses involving many possible values of one or two variables, Excel’s Data Table feature may be more appropriate.</p><h4>4. Regenerate reports after changing assumptions.</h4><p>Scenario summary reports do not automatically update when their underlying scenarios change. If you modify the assumptions, create a new summary report and update any separately maintained comparison charts.</p><h4>5. Remember that scenarios are not predictions.</h4><p>Scenario Manager calculates what would happen under the assumptions you define. It does not estimate the probability of those outcomes or perform random simulations like Monte Carlo analysis.</p><h3>Conclusion</h3><p>Excel’s Scenario Manager makes it easier to evaluate how different assumptions affect the outcomes of a spreadsheet model.</p><p>In this article, we’ve covered how to use Python to create, apply, and modify scenarios, generate summary reports, visualize results with Excel charts, and manage scenarios through deletion and merging.</p><p>These techniques help you explore different possibilities, compare outcomes, and automate repetitive tasks in financial planning, sales forecasting, and other data-driven workflows.</p><h3>See Also</h3><ul><li><a href="https://medium.com/@alice.yang_10652/working-with-excel-formulas-in-python-a-practical-guide-e695dceec406">Working with Excel Formulas in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/create-update-and-remove-pivot-tables-in-excel-with-python-a7db24d02445">Create, Update and Remove Pivot Tables in Excel with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/mastering-conditional-formatting-in-excel-using-python-a-comprehensive-guide-9032b196dc7b">Mastering Conditional Formatting in Excel Using Python</a></li><li><a href="https://medium.com/@alice.yang_10652/export-excel-charts-shapes-and-other-elements-as-images-with-python-da2b29096ec8">Export Excel Charts, Shapes and Other Elements as Images with Python</a></li></ul><p><em>Thank you for taking the time to read our article. If you found it helpful or enjoyable, feel free to clap for it. We appreciate your support!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdb3ff7a77b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Edit Word Documents in Python: Beyond Text Replacement]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-edit-word-documents-in-python-beyond-text-replacement-10f43148a86d?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/10f43148a86d</guid>
            <category><![CDATA[edit-word-document]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[edit-docx-file]]></category>
            <category><![CDATA[update-word-document]]></category>
            <category><![CDATA[edit-doc-file]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 07:45:38 GMT</pubDate>
            <atom:updated>2026-10-15T08:56:09.321Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From simple text updates to page layouts, forms, shapes, and embedded objects, explore practical ways to automate Word document editing with Python.</em></p><figure><img alt="Editing Word Documents with Python" src="https://cdn-images-1.medium.com/max/650/0*bcGQTnZEbTp0S2e9.png" /><figcaption>Editing Word Documents with Python</figcaption></figure><p>Editing a Word document is easy when you only need to change a few sentences. But what if you have fifty reports to update, multiple documents to combine, or a template that needs to be filled with different information every week?</p><p>Making those changes manually can become tedious, especially when they involve more than just text. Word documents contain tables, images, headers, footers, sections, metadata, bookmarks, and other elements that may all need updating.</p><p>Fortunately, Python can automate much of this work. In this article, we’ll explore how to edit existing Word documents in Python. We’ll start with common tasks like replacing text and modifying formatting, then move on to document structure, properties, merging and splitting files, bookmarks, backgrounds, watermarks, fillable forms, and review-related features.</p><ul><li><a href="#4531">Part 1: Edit Word Document Content</a></li><li><a href="#f680">Part 2: Edit Word Document Properties or Metadata</a></li><li><a href="#d05e">Part 3: Edit Word Document Structure and Page Layout</a></li><li><a href="#dde7">Part 4: Merge and Split Word Documents</a></li><li><a href="#04ff">Part 5: Work with Word Bookmarks</a></li><li><a href="#f4c2">Part 6: Edit Word Document Backgrounds and Watermarks</a></li><li><a href="#10c7">Part 7: Create and Edit Fillable Word Forms</a></li><li><a href="#5a58">Part 8: Manage Comments, Tracked Changes, and Editing Restrictions</a></li><li><a href="#2966">Part 9: Handle Shapes, WordArt, and OLE Objects</a></li><li><a href="#f636">Practical Tips for Editing Word Documents with Python</a></li></ul><h3>Prerequisites: Install a Python Word Document Editor</h3><p>To work with Word files programmatically, we’ll use <a href="https://www.e-iceblue.com/Introduce/doc-for-python.html">Spire.Doc for Python</a>. It provides APIs for reading, editing, and saving DOC and DOCX files without requiring Microsoft Word to be installed.</p><p>You can install it from PyPI by running the following commands in your terminal:</p><pre>pip install Spire.Doc</pre><h3>Part 1: Edit Word Document Content in Python</h3><p>Editing Word document content involves more than changing text. You may need to replace outdated information, rewrite paragraphs, adjust text formatting, insert images, or update data in existing tables. Python allows you to handle these common editing tasks without rebuilding the document from scratch.</p><h4>Find and Replace Text</h4><p>Suppose you’re updating a project report and need to replace every mention of an old project name.</p><p>Rather than searching through the document manually, you can use the Replace() method to update all matching occurrences.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Replace text throughout the document<br>doc.Replace(&quot;Project Alpha&quot;, &quot;Project Beta&quot;, False, True)<br><br>doc.SaveToFile(&quot;replaced_text.docx&quot;, FileFormat.Docx)<br>doc.Close()<br></pre><p>The last two parameters of the Replace method control case sensitivity and whole-word matching, respectively.</p><p>You can also replace several placeholders at once. For example, if your document contains fields such as {client_name} and {report_date}, a dictionary makes the replacements easier to manage.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br>replacements = {<br>    &quot;{client_name}&quot;: &quot;Northwind Traders&quot;,<br>    &quot;{report_date}&quot;: &quot;October 15, 2026&quot;,<br>    &quot;{project_status}&quot;: &quot;Completed&quot;<br>}<br><br>for old_text, new_text in replacements.items():<br>    doc.Replace(old_text, new_text, False, False)<br><br>doc.SaveToFile(&quot;filled_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This is particularly useful for generating personalized documents from reusable templates, such as invoices, agreements, certificates, or monthly reports.</p><p>In addition to replacing text with other text, you can also replace it with images, tables, or content from another document. For more details, see <a href="https://medium.com/@alice.yang_10652/find-and-replace-text-in-word-doc-or-docx-documents-with-python-8ed04d1722f6">Find and Replace Text in Word DOC or DOCX Documents</a>.</p><h4>Modify an Existing Paragraph</h4><p>Sometimes a paragraph needs to be rewritten entirely instead of having individual words replaced.</p><p>Word documents are organized into sections, and each section contains paragraphs and other elements. You can access an existing paragraph and update its Text property directly.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Access the first paragraph in the first section<br>paragraph = doc.Sections[0].Paragraphs[0]<br><br># Replace the paragraph content<br>paragraph.Text = (<br>    &quot;This report provides an updated overview of &quot;<br>    &quot;project performance and future priorities.&quot;<br>)<br><br>doc.SaveToFile(&quot;updated_paragraph.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>Both section and paragraph indexes start at zero.</p><p><strong>One thing to keep in mind: </strong>replacing a paragraph’s Text property can remove its existing inline content and formatting. If a paragraph contains multiple text styles, hyperlinks, or embedded elements, it’s generally better to update only the necessary text rather than rewrite the entire paragraph.</p><h4>Change Text Formatting</h4><p>You may also want to emphasize certain words without changing the surrounding content.</p><p>For example, you can search for every occurrence of “Important” and make it bold, blue, and 12 points in size.</p><pre>from spire.doc import *<br>from spire.doc.common import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Find matching text<br>selections = doc.FindAllString(&quot;Important&quot;, False, True)<br><br>for selection in selections:<br>    text_range = selection.GetAsOneRange()<br><br>    # Apply character formatting<br>    text_range.CharacterFormat.Bold = True<br>    text_range.CharacterFormat.FontSize = 12<br>    text_range.CharacterFormat.TextColor = Color.get_Blue()<br><br>doc.SaveToFile(&quot;formatted_text.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>You can also highlight matching text by setting the HighlightColor property:</p><pre>text_range.CharacterFormat.HighlightColor = Color.get_Yellow()</pre><p>It’s useful for reviewing documents, emphasizing technical terms, or marking information that needs attention.</p><h4>Add New Text to a Document</h4><p>In addition to modifying existing content, you can insert new paragraphs.</p><p>For example, you might want to append a note explaining changes made to a report.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Get the last section<br>section = doc.Sections[doc.Sections.Count - 1]<br><br># Add a paragraph at the end of the section<br>paragraph = section.AddParagraph()<br><br># Insert new text<br>paragraph.AppendText(<br>    &quot;Note: The figures in this report have been &quot;<br>    &quot;updated to reflect the latest available data.&quot;<br>)<br><br>doc.SaveToFile(&quot;report_with_note.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>Here, AddParagraph() creates a new paragraph, while AppendText() inserts text into it.</p><p>You can also apply formatting to the returned text range if you want the new content to appear in bold, italic, or a particular font.</p><h4>Edit Images and Tables</h4><p>Word documents often contain visual content and structured data alongside ordinary text.</p><p>For reports, proposals, and technical documentation, being able to update images and tables is just as important as editing paragraphs.</p><p><strong>Insert an Image</strong></p><p>Suppose your monthly report needs an updated sales chart. You can insert the image directly into the document.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Get the first section<br>section = doc.Sections[0]<br><br># Create a paragraph for the image<br>paragraph = section.AddParagraph()<br><br># Insert the image<br>picture = paragraph.AppendPicture(&quot;sales_chart.png&quot;)<br><br># Set the image dimensions<br>picture.Width = 320<br>picture.Height = 180<br><br>doc.SaveToFile(&quot;report_with_chart.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This example adds an image at the end of the first section.</p><p>For existing documents, images can also be replaced by locating the relevant DocPicture object and calling its LoadImage() method.</p><p>When resizing an image, it’s worth keeping its original aspect ratio in mind to avoid distortion.</p><p><strong>Modify Tables</strong></p><p>Tables are widely used for financial figures, schedules, comparison data, and project statuses.</p><p>Instead of recreating a table, you can access its cells and modify their contents. For example, the following code updates a project status and appends another row to an existing table.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Get the first table in the first section<br>table = doc.Sections[0].Tables[0]<br><br># Update an existing cell<br>cell = table.Rows[1].Cells[2]<br>cell.Paragraphs[0].Text = &quot;Completed&quot;<br><br># Add another row<br>new_row = table.AddRow()<br><br># Insert data into the new row<br>row_data = [<br>    &quot;Website Redesign&quot;,<br>    &quot;Marketing&quot;,<br>    &quot;In Progress&quot;<br>]<br><br>for i, value in enumerate(row_data):<br>    new_row.Cells[i].AddParagraph().AppendText(value)<br><br>doc.SaveToFile(&quot;updated_table.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This example assumes that the table contains at least two rows and three columns.</p><p>You can use similar operations to insert or delete rows, update individual cells, and change table formatting.</p><p>For more complex tables, such as those containing merged cells, nested tables, or multiple paragraphs per cell, it’s important to inspect the table structure before modifying it.</p><h3>Part 2: Edit Word Document Properties and Metadata in Python</h3><p>Not every part of a Word document is visible on the page. Word files also store document properties, including information such as the title, author, subject, company, keywords, and comments. These properties help identify, classify, and organize documents in file management systems.</p><p>For example, when preparing a report for distribution, you may want to update its title, author, and other properties.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Access built-in document properties<br>properties = doc.BuiltinDocumentProperties<br><br># Update metadata<br>properties.Title = &quot;Annual Performance Report&quot;<br>properties.Subject = &quot;Business Performance Review&quot;<br>properties.Author = &quot;Data Analytics Team&quot;<br>properties.Company = &quot;Northwind Traders&quot;<br>properties.Keywords = &quot;Performance, Sales, Annual Report&quot;<br>properties.Comments = &quot;Updated for the annual review&quot;<br><br>doc.SaveToFile(&quot;report_with_metadata.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>These changes don’t alter the visible document content. Instead, they update the metadata associated with the file.</p><p>To clear selected metadata fields instead of updating them, set their values to None before saving the document:</p><pre>properties.Author = None<br>properties.Comments = None</pre><p>These changes take effect when the document is saved. Keep in mind that clearing built-in properties does not remove all potentially sensitive information, such as tracked changes or hidden document content.</p><h3>Part 3: Edit Word Document Structure and Page Layout in Python</h3><p>Beyond editing text and images, you may need to reorganize a Word document by removing unwanted paragraphs, deleting pages, inserting page breaks, or adjusting its layout.</p><p>These operations are especially useful when preparing reports for distribution, cleaning up templates, or standardizing documents from different sources.</p><h4>Remove Unwanted Paragraphs</h4><p>Suppose a report contains temporary notes that should be removed before publication.</p><p>You can locate paragraphs by their text and delete them using the Paragraphs.RemoveAt() method.</p><pre><br>from spire.doc import Document, FileFormat<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Loop through all sections<br>for s in range(doc.Sections.Count):<br>    section = doc.Sections[s]<br><br>    # Iterate through paragraphs in reverse order<br>    for i in range(section.Paragraphs.Count - 1, -1, -1):<br>        paragraph = section.Paragraphs[i]<br><br>        if paragraph.Text.strip() == &quot;For internal review only.&quot;:<br>            section.Paragraphs.RemoveAt(i)<br><br>doc.SaveToFile(&quot;cleaned_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The backward iteration ensures that removing a paragraph doesn’t affect the indexes of the remaining paragraphs.</p><p>Since this example uses an exact-text match, it only deletes paragraphs containing the specified phrase and no other text. It checks the main paragraphs of each section, not content inside tables or other containers.</p><h4>Remove Blank or Specific Pages</h4><p>Unwanted pages can appear when documents are edited, combined, or generated from templates. Sometimes these are empty pages caused by formatting; other times, they contain outdated content that should be removed entirely.</p><p>To remove blank pages, you can use the RemoveBlankPages() method:</p><pre>from spire.doc import Document, FileFormat<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Remove blank pages<br>doc.RemoveBlankPages()<br><br>doc.SaveToFile(&quot;report_without_blank_pages.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>If you need to delete particular pages instead, use RemovePages() and provide their indexes.</p><p>For example, the following code removes pages 2 and 4:</p><pre>from spire.doc import Document, FileFormat<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Remove pages 2 and 4 (zero-based indexes)<br>doc.RemovePages([1, 3])<br><br>doc.SaveToFile(&quot;report_without_selected_pages.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p><strong>Keep in mind:</strong> Word doesn’t store content as fixed pages in the same way a PDF does. Pagination depends on the document’s layout, fonts, and formatting. It’s worth checking the page count and reviewing the output before deleting pages from important documents.</p><p>Also, not every visually blank page has the same cause. Some are produced by section breaks or other formatting settings and may need additional cleanup.</p><p>For more examples, see this guide on <a href="https://medium.com/@alice.yang_10652/remove-specific-or-blank-pages-from-word-in-python-complete-guide-0dcccc5c7f84">removing specific or blank pages from Word documents in Python</a>.</p><h4>Insert or Remove Page Breaks</h4><p>Page breaks control where the next page begins. They’re commonly used to separate chapters, appendices, and major report sections.</p><p>To insert a page break after a particular paragraph, use AppendBreak():</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Get the second paragraph<br>paragraph = doc.Sections[0].Paragraphs[1]<br><br># Insert a page break after the paragraph<br>paragraph.AppendBreak(BreakType.PageBreak)<br><br>doc.SaveToFile(&quot;report_with_page_break.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>You can also remove manual page breaks if they are no longer needed.</p><pre><br>from spire.doc import Document, FileFormat, Break, BreakType<br><br>doc = Document()<br>doc.LoadFromFile(&quot;Sample.docx&quot;)<br><br># Loop through all sections<br>for s in range(doc.Sections.Count):<br>    section = doc.Sections[s]<br><br>    # Loop through all paragraphs in the section<br>    for p in range(section.Paragraphs.Count):<br>        paragraph = section.Paragraphs[p]<br><br>        # Remove manual page breaks in reverse order<br>        for i in range(paragraph.ChildObjects.Count - 1, -1, -1):<br>            obj = paragraph.ChildObjects[i]<br><br>            if isinstance(obj, Break) and obj.BreakType == BreakType.PageBreak:<br>                paragraph.ChildObjects.RemoveAt(i)<br><br>doc.SaveToFile(&quot;report_without_page_breaks.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This removes explicit page-break objects in the main paragraphs. It doesn’t prevent Word from creating automatic page breaks when content reaches the bottom of a page.</p><p>Section breaks and paragraph settings such as <em>Page break before</em> can also affect pagination and must be handled separately.</p><h4>Change Page Margins and Orientation</h4><p>Page layout settings determine how content is arranged within each section of a Word document.</p><p>For instance, you might want to apply consistent margins and page orientation throughout a report.</p><pre><br>from spire.doc import Document, FileFormat, PageOrientation<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Update page layout for all sections<br>for i in range(doc.Sections.Count):<br>    section = doc.Sections[i]<br>    page_setup = section.PageSetup<br><br>    # Set one-inch margins (72 points)<br>    page_setup.Margins.Top = 72<br>    page_setup.Margins.Bottom = 72<br>    page_setup.Margins.Left = 72<br>    page_setup.Margins.Right = 72<br><br>    # Set portrait orientation<br>    page_setup.Orientation = PageOrientation.Portrait<br><br>doc.SaveToFile(&quot;report_with_new_layout.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>To switch to landscape orientation, change PageOrientation.Portrait to PageOrientation.Landscape.</p><p>These settings apply at the section level, so different sections can have different page layouts.</p><p>Be aware that changing margins or orientation can affect pagination and the placement of tables and images.</p><h4>Edit Headers, Footers, and Page Numbers</h4><p>Headers and footers often contain repeated information such as report titles, dates, company names, and page numbers.</p><p>For example, you can add a report title to the header and automatic page numbering to the footer.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br>section = doc.Sections[0]<br><br># Add a report title to the header<br>header = section.HeadersFooters.Header<br>header_paragraph = header.AddParagraph()<br>header_paragraph.AppendText(&quot;Annual Performance Report&quot;)<br><br># Add page numbers to the footer<br>footer = section.HeadersFooters.Footer<br>footer_paragraph = footer.AddParagraph()<br><br>footer_paragraph.AppendText(&quot;Page &quot;)<br>footer_paragraph.AppendField(<br>    &quot;Current Page&quot;, FieldType.FieldPage<br>)<br>footer_paragraph.AppendText(&quot; of &quot;)<br>footer_paragraph.AppendField(<br>    &quot;Total Pages&quot;, FieldType.FieldNumPages<br>)<br><br># Center the footer text<br>footer_paragraph.Format.HorizontalAlignment = (<br>    HorizontalAlignment.Center<br>)<br><br>doc.SaveToFile(&quot;report_with_header_footer.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The page fields display the current page number and total page count when updated by a compatible Word application.</p><p>This example adds content to the first section’s header and footer. If the document already contains header or footer information, you may want to modify the existing elements instead of appending new ones.</p><p>For multi-section documents, you should also consider whether headers and footers are linked between sections.</p><h3>Part 4: Merge and Split Word Documents in Python</h3><p>When working with multiple reports, chapters, or document templates, it can be useful to combine Word files into one document or split a large document into smaller parts.</p><p>Python can handle both tasks, whether you’re organizing content by document, page range, or section.</p><h4>Merge Multiple Word Documents</h4><p>Suppose you have three Word documents containing a main report, supporting analysis, and an appendix.</p><p>You can combine them into a single file using InsertTextFromFile().</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;main_report.docx&quot;)<br><br># Append additional documents<br>doc.InsertTextFromFile(<br>    &quot;analysis.docx&quot;, FileFormat.Auto<br>)<br><br>doc.InsertTextFromFile(<br>    &quot;appendix.docx&quot;, FileFormat.Auto<br>)<br><br>doc.SaveToFile(&quot;combined_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The inserted content begins on a new page, making this approach suitable for assembling separate reports or chapters.</p><p>For more control over how content is combined, you can also clone paragraphs, tables, and other document objects into a destination section. See <a href="https://medium.com/@alice.yang_10652/merge-word-documents-into-one-with-python-9ba9f68a04f2">Merge Word Documents into One</a> for more details.</p><h4>Split a Word Document into Individual Pages</h4><p>If you need to divide a long document into separate files, one file per page, you can use ExtractPages().</p><p>The method takes two parameters: the zero-based starting page index and the number of pages to extract. For example, ExtractPages(0, 1) extracts the first page, while ExtractPages(2, 1) extracts the third.</p><p>By combining this method with the PageCount property, you can split an entire document automatically.</p><pre>from pathlib import Path<br>from spire.doc import Document, FileFormat<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Create a folder for the output files<br>output_dir = Path(&quot;split_pages&quot;)<br>output_dir.mkdir(exist_ok=True)<br><br># Get the total number of pages<br>page_count = doc.PageCount<br><br># Extract and save each page<br>for i in range(page_count):<br>    page_doc = doc.ExtractPages(i, 1)<br><br>    output_file = output_dir / f&quot;Page_{i + 1}.docx&quot;<br>    page_doc.SaveToFile(str(output_file), FileFormat.Docx)<br><br>    page_doc.Close()<br><br>doc.Close()</pre><p>This produces separate files named Page_1.docx, Page_2.docx, and so on.</p><p>It’s useful when you need to archive documents page by page, distribute selected pages, or process individual pages separately.</p><h4>Split a Word Document by Page Range</h4><p>You may not always want one document per page. For example, you might need to separate the first three pages of a report from the remaining pages.</p><p>The same ExtractPages() method can handle this by specifying the starting page and the number of pages to include.</p><pre>from spire.doc import Document, FileFormat<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br>page_count = doc.PageCount<br><br>if page_count &gt; 3:<br>    # Extract the first three pages<br>    first_part = doc.ExtractPages(0, 3)<br>    first_part.SaveToFile(&quot;Part_1.docx&quot;, FileFormat.Docx)<br>    first_part.Close()<br><br>    # Extract the remaining pages<br>    second_part = doc.ExtractPages(3, page_count - 3)<br>    second_part.SaveToFile(&quot;Part_2.docx&quot;, FileFormat.Docx)<br>    second_part.Close()<br>else:<br>    print(&quot;The document must contain more than three pages.&quot;)<br><br>doc.Close()</pre><p>You can adjust the starting index and page count to extract any continuous range.</p><p>Because Word pages are determined by layout rather than fixed page objects, extracted content may reflow when opened in another environment, especially if the required fonts aren’t available.</p><p>For additional examples, including extracting non-contiguous pages, see <a href="https://medium.com/@alice.yang_10652/how-to-extract-pages-from-word-documents-in-python-ea7d18917eb0">how to extract pages from Word documents in Python</a>.</p><h4>Split a Word Document by Sections</h4><p>For documents organized into chapters or logical sections, splitting by section boundaries may be more appropriate than splitting by page number.</p><p>You can loop through the sections, clone each one, and save it as a separate document.</p><pre>from pathlib import Path<br>from spire.doc import Document, FileFormat<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br>output_dir = Path(&quot;split_sections&quot;)<br>output_dir.mkdir(exist_ok=True)<br><br># Save each section as a separate document<br>for i in range(doc.Sections.Count):<br>    new_doc = Document()<br><br>    # Clone the section<br>    section = doc.Sections[i].Clone()<br>    new_doc.Sections.Add(section)<br><br>    output_file = output_dir / f&quot;Section_{i + 1}.docx&quot;<br>    new_doc.SaveToFile(str(output_file), FileFormat.Docx)<br><br>    new_doc.Close()<br><br>doc.Close()</pre><p>Unlike page-based splitting, this approach uses the document’s logical section boundaries rather than its rendered page layout.</p><p>It’s a useful alternative for manuals, contracts, or reports where each section represents an independent part.</p><p>However, a section may span multiple pages, and a document may have multiple sections on the same page. Choose the method that matches how you want to divide the content.</p><h3>Part 5: Work with Word Bookmarks in Python</h3><p>Bookmarks provide a way to identify specific locations or content ranges inside Word documents.</p><p>They are especially useful when building document templates because they allow you to target content by name rather than relying on paragraph indexes.</p><h4>Add a Bookmark to an Existing Paragraph</h4><p>For example, suppose you want to mark a paragraph containing an executive summary.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Select a paragraph<br>paragraph = doc.Sections[0].Paragraphs[1]<br><br># Create a bookmark start<br>start = paragraph.AppendBookmarkStart(&quot;ExecutiveSummary&quot;)<br><br># Move the bookmark start to the beginning<br>paragraph.Items.Insert(0, start)<br><br># Add the bookmark end<br>paragraph.AppendBookmarkEnd(&quot;ExecutiveSummary&quot;)<br><br>doc.SaveToFile(&quot;report_with_bookmark.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The bookmark is defined by a start marker and an end marker, enclosing the paragraph’s content.</p><p>Once created, the bookmark can be used to locate that part of the document later.</p><h4>Replace Content at a Bookmark</h4><p>Bookmarks become even more useful when the document already contains predefined bookmark names.</p><p>For example, imagine a report template containing bookmarks named introduction, findings, and conclusion.</p><p>You can replace their contents without searching for specific text.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report_template.docx&quot;)<br><br># Define content for existing bookmarks<br>replacements = {<br>    &quot;introduction&quot;: &quot;This report evaluates annual performance.&quot;,<br>    &quot;findings&quot;: &quot;Revenue increased during the reporting period.&quot;,<br>    &quot;conclusion&quot;: &quot;The overall results indicate positive growth.&quot;<br>}<br><br># Update each bookmark<br>for name, content in replacements.items():<br>    navigator = BookmarksNavigator(doc)<br><br>    navigator.MoveToBookmark(name)<br>    navigator.ReplaceBookmarkContent(content, True)<br><br>doc.SaveToFile(&quot;completed_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This assumes the template already contains all three bookmarks.</p><p>Compared with relying on paragraph positions, bookmarks are often more reliable for structured templates because changes elsewhere in the document don’t necessarily affect the named locations.</p><p>They can be particularly helpful for automated report generation and document assembly.</p><h3>Part 6: Edit Word Document Backgrounds and Watermarks with Python</h3><p>Sometimes the required changes are visual rather than textual. For example, you might want to apply a background color to an invitation or mark a document as confidential before distribution.</p><p>Word supports both document backgrounds and watermarks, but they serve different purposes.</p><h4>Change the Document Background</h4><p>A background color can be applied through the document’s Background property.</p><pre>from spire.doc import *<br>from spire.doc.common import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Access the document background<br>background = doc.Background<br><br># Set the background type and color<br>background.Type = BackgroundType.Color<br>background.Color = Color.get_AliceBlue()<br><br>doc.SaveToFile(&quot;report_with_background.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This changes the document-level background rather than the shading of individual paragraphs or table cells.</p><p>You can also use a background image by replacing the background configuration lines with:</p><pre>background.Type = BackgroundType.Picture<br>background.SetPicture(&quot;background.jpg&quot;)</pre><p>Backgrounds can work well for designed documents, invitations, or promotional materials. Their visibility in print or PDF output may depend on the application and its print-background settings.</p><h4>Add a Text Watermark</h4><p>Watermarks are commonly used to indicate document status, such as “DRAFT” or “CONFIDENTIAL.”</p><p>The following example adds a diagonal text watermark.</p><pre>from spire.doc import *<br>from spire.doc.common import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Create a text watermark<br>watermark = TextWatermark()<br><br>watermark.Text = &quot;CONFIDENTIAL&quot;<br>watermark.FontSize = 55<br>watermark.Color = Color.get_LightGray()<br>watermark.Layout = WatermarkLayout.Diagonal<br><br># Apply the watermark<br>doc.Watermark = watermark<br><br>doc.SaveToFile(&quot;confidential_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>You can also use an image watermark by creating a PictureWatermark object and loading an image through its SetPicture() method.</p><p>For example, a company logo can be placed behind the document content.</p><p>Watermarks provide a visual indication of document status, but they should not be treated as a security mechanism that prevents copying or unauthorized access.</p><h3>Part 7: Create and Edit Fillable Word Forms in Python</h3><p>Word forms are another area where programmatic editing can be useful. A form might contain fields for employee information, customer details, feedback, or approval status.</p><p>Word supports structured content controls, including plain-text fields, rich-text fields, dropdown lists, checkboxes, and date pickers. These controls can be added to documents and updated programmatically.</p><h4>Insert a Fillable Text Field</h4><p>Suppose you’re preparing a form and want to insert a field where users can enter their names.</p><p>You can create a plain-text content control using StructureDocumentTagInline.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;form_template.docx&quot;)<br><br># Add a paragraph to the first section<br>paragraph = doc.Sections[0].AddParagraph()<br>paragraph.AppendText(&quot;Employee Name: &quot;)<br><br># Create a text content control<br>sdt = StructureDocumentTagInline(doc)<br>paragraph.ChildObjects.Add(sdt)<br><br># Configure the control<br>sdt.SDTProperties.SDTType = SdtType.Text<br>sdt.SDTProperties.Alias = &quot;Employee Name&quot;<br>sdt.SDTProperties.Tag = &quot;employee_name&quot;<br>sdt.SDTProperties.IsShowingPlaceHolder = True<br><br># Configure text input<br>text_settings = SdtText(True)<br>text_settings.IsMultiline = False<br><br>sdt.SDTProperties.ControlProperties = text_settings<br><br># Add placeholder text<br>placeholder = TextRange(doc)<br>placeholder.Text = &quot;Enter your name&quot;<br><br>sdt.SDTContent.ChildObjects.Add(placeholder)<br><br>doc.SaveToFile(&quot;form_with_text_field.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The Tag property gives the control a recognizable identifier that can be used when editing it later.</p><p>This is useful for structured templates because fields can be identified by purpose rather than their physical position.</p><h4>Update an Existing Form Field</h4><p>Once a document contains content controls, you can locate a control by its tag and update its text.</p><p>The following example updates a plain-text control tagged employee_name in a normal body paragraph.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;form_with_text_field.docx&quot;)<br><br># Iterate through document sections<br>for s in range(doc.Sections.Count):<br>    section = doc.Sections[s]<br><br>    # Check paragraphs in each section<br>    for p in range(section.Paragraphs.Count):<br>        paragraph = section.Paragraphs[p]<br><br>        for i in range(paragraph.ChildObjects.Count):<br>            obj = paragraph.ChildObjects[i]<br><br>            if obj.DocumentObjectType == (<br>                DocumentObjectType.StructureDocumentTagInline<br>            ):<br>                control = StructureDocumentTagInline(obj)<br><br>                if control.SDTProperties.Tag == &quot;employee_name&quot;:<br><br>                    # Find and update the text inside the control<br>                    for j in range(control.ChildObjects.Count):<br>                        child = control.ChildObjects[j]<br><br>                        if child.DocumentObjectType == (<br>                            DocumentObjectType.TextRange<br>                        ):<br>                            text_range = TextRange(child)<br>                            text_range.Text = &quot;Alex Morgan&quot;<br><br>doc.SaveToFile(&quot;completed_form.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This example targets inline text controls in the main body paragraphs. Controls inside table cells, block-level controls, or other containers require traversing those structures as well.</p><p>For more sophisticated forms, you can use content-control tags to automate document population while keeping the rest of the template structure consistent.</p><h3>Part 8: Manage Comments, Tracked Changes, and Editing Restrictions in Word with Python</h3><p>Editing Word documents isn’t always a single-person process. Documents frequently go through review cycles involving comments, suggested revisions, and restrictions on what recipients can change.</p><p>Python can help manage some of these review-related operations.</p><h4>Add a Comment to a Paragraph</h4><p>For example, suppose a paragraph in a report requires further clarification.</p><p>You can attach a comment to it programmatically.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Get a paragraph<br>paragraph = doc.Sections[0].Paragraphs[1]<br><br># Add a comment<br>comment = paragraph.AppendComment(<br>    &quot;Please verify these figures before publication.&quot;<br>)<br><br>comment.Format.Author = &quot;Review Team&quot;<br><br># Mark the beginning and end of the commented range<br>start = CommentMark(doc, CommentMarkType.CommentStart)<br>end = CommentMark(doc, CommentMarkType.CommentEnd)<br><br>start.CommentId = comment.Format.CommentId<br>end.CommentId = comment.Format.CommentId<br><br>paragraph.ChildObjects.Insert(0, start)<br>paragraph.ChildObjects.Add(end)<br><br>doc.SaveToFile(&quot;report_with_comment.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This associates the comment with the paragraph.</p><p>Comments are helpful when automating review preparation, especially for documents that contain information requiring human verification.</p><h4>Accept Existing Tracked Changes</h4><p>When multiple people have edited a document using Track Changes, the file may contain pending insertions, deletions, or formatting revisions.</p><p>You can check whether a document contains revisions and accept them.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;reviewed_report.docx&quot;)<br><br># Accept all existing tracked changes<br>if doc.HasChanges:<br>    doc.AcceptChanges()<br><br>doc.SaveToFile(&quot;final_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This applies all pending tracked changes to the document.</p><p>If you want to discard the tracked changes instead, you can use RejectChanges().</p><p>Be careful when automating either operation. Accepting or rejecting revisions in bulk can permanently resolve changes that may still require review.</p><h4>Restrict Editing</h4><p>You can also apply editing restrictions to a Word document.</p><p>For example, the following code restricts editing while still allowing the document to be opened and read.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Apply read-only editing restrictions<br>doc.Protect(<br>    ProtectionType.AllowOnlyReading,<br>    &quot;your_password&quot;<br>)<br><br>doc.SaveToFile(&quot;restricted_report.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>Other supported protection types can allow comments, tracked revisions, or form filling.</p><p>Editing restrictions are different from encryption. They control permitted editing behavior in compatible Word applications but should not be considered sufficient protection for highly sensitive document content.</p><h3>Part 9: Handle Shapes, WordArt, and OLE Objects</h3><p>Word documents can also contain shapes, decorative text, and embedded files. These elements can be useful for highlighting information, designing document headings, or including supporting files directly in a report.</p><h4>Insert Shapes</h4><p>Shapes such as rectangles, arrows, and callouts can help organize information visually. You can add a shape using the AppendShape() method and customize its size, fill color, and border.</p><p>For example, the following code inserts a rounded rectangle into an existing Word document.</p><pre>from spire.doc import *<br>from spire.doc.common import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Add a paragraph for the shape<br>paragraph = doc.Sections[0].AddParagraph()<br><br># Insert a rounded rectangle<br>shape = paragraph.AppendShape(120, 65, ShapeType.RoundRectangle)<br><br># Set the fill and border styles<br>shape.FillColor = Color.get_YellowGreen()<br>shape.StrokeColor = Color.get_Gray()<br>shape.LineStyle = ShapeLineStyle.Single<br>shape.StrokeWeight = 1<br><br>doc.SaveToFile(&quot;report_with_shape.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>You can replace ShapeType.RoundRectangle with other supported types, such as ShapeType.Rectangle, ShapeType.Triangle, or ShapeType.Arrow.</p><p>This can be helpful when adding visual markers, labels, or simple diagram elements to reports and other documents.</p><h4>Insert WordArt</h4><p>WordArt allows you to create decorative text with visual effects such as curves and transformations. It can be useful for document titles, certificates, or other elements that need to stand out.</p><p>To insert WordArt, you can create a text-based shape and assign its content through the WordArt.Text property.</p><pre>from spire.doc import *<br>from spire.doc.common import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Add a paragraph for WordArt<br>paragraph = doc.Sections[0].AddParagraph()<br><br># Create a curved text shape<br>shape = paragraph.AppendShape(220, 100, ShapeType.TextCurve)<br><br># Set the WordArt text<br>shape.WordArt.Text = &quot;Quarterly Review&quot;<br><br># Apply colors<br>shape.FillColor = Color.get_AliceBlue()<br>shape.StrokeColor = Color.get_DarkBlue()<br><br>doc.SaveToFile(&quot;report_with_wordart.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>The ShapeType.TextCurve option creates a curved text effect. Other text-related shape types can be used to produce different visual styles.</p><p>Unlike ordinary paragraph formatting, WordArt treats the text as a graphical element, allowing it to take on more decorative shapes.</p><h4>Embed an OLE Object</h4><p>OLE (<a href="https://support.microsoft.com/en-gb/word/linked-objects-and-embedded-objects">Object Linking and Embedding</a>) allows you to include files from other applications inside a Word document. For example, you can embed an Excel spreadsheet containing supporting calculations or a PowerPoint presentation related to a report.</p><p>The following code embeds an Excel workbook and displays a custom icon representing the attached file.</p><pre>from spire.doc import *<br><br>doc = Document()<br>doc.LoadFromFile(&quot;report.docx&quot;)<br><br># Add a paragraph for the embedded file<br>paragraph = doc.Sections[0].AddParagraph()<br>paragraph.AppendText(&quot;Budget Spreadsheet: &quot;)<br><br># Load an image to represent the OLE object<br>picture = DocPicture(doc)<br>picture.LoadImage(&quot;excel_icon.png&quot;)<br>picture.Width = 50<br>picture.Height = 50<br><br># Embed an Excel workbook<br>paragraph.AppendOleObject(<br>    &quot;Budget.xlsx&quot;,<br>    picture,<br>    OleObjectType.ExcelWorksheet<br>)<br><br>doc.SaveToFile(&quot;report_with_ole.docx&quot;, FileFormat.Docx)<br>doc.Close()</pre><p>This embeds the Excel workbook into the Word document rather than simply inserting a screenshot of its contents.</p><p>You can also embed other supported file types, such as PDFs and PowerPoint presentations, by using the corresponding OleObjectType.</p><p>OLE objects are useful when related files need to be packaged together with a Word report. However, opening or editing the embedded content may require a compatible application on the recipient’s computer.</p><h3>Practical Tips for Editing Word Documents with Python</h3><p>Before using these techniques in production, there are a few things worth considering.</p><ul><li><strong>Preserve the original document.</strong> Save edited files under new names, especially when you’re modifying complex documents or processing many files at once.</li><li><strong>Understand the document hierarchy.</strong> Word content can appear inside sections, tables, headers, footers, and other containers. A script that searches only the main paragraph collection may miss content stored elsewhere.</li><li><strong>Avoid unnecessary content replacement.</strong> Assigning new text to an entire paragraph or cell may remove existing inline formatting or embedded elements. Use more targeted operations when preserving formatting is important.</li><li><strong>Be cautious when changing page layout.</strong> Word pagination depends on fonts, margins, section settings, and content. Changes that look minor in code can affect how text, tables, and images flow across pages.</li><li><strong>Test with representative documents.</strong> Simple DOCX files are relatively straightforward to edit, but documents with nested tables, floating images, content controls, or complex numbering may require additional handling.</li></ul><h3>Conclusion</h3><p>Editing Word documents with Python goes beyond simple text replacement.</p><p>In this article, we’ve explored how to edit document content and formatting, work with images, tables, shapes, and embedded objects, adjust page layouts and document properties, merge and split files, and handle elements such as bookmarks, watermarks, and forms.</p><p>By combining these techniques, you can automate repetitive document updates and build more consistent workflows for maintaining reports, templates, and other Word files.</p><h3>Final Words</h3><p><em>Thank you for taking the time to read our article. If you found it helpful or enjoyable, feel free to clap for it. We really appreciate your support!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10f43148a86d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Convert PowerPoint (PPT or PPTX) to Markdown in Python]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-convert-powerpoint-pptx-to-markdown-in-python-1b4d2ea8de81?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b4d2ea8de81</guid>
            <category><![CDATA[slide-to-markdown]]></category>
            <category><![CDATA[powerpoint-to-md]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[markdown-to-pptx]]></category>
            <category><![CDATA[powerpoint-to-markdown]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 08:33:26 GMT</pubDate>
            <atom:updated>2026-09-29T08:35:01.585Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to convert an entire PowerPoint presentation, a single slide, or a selected range of slides to Markdown format using Python.</em></p><figure><img alt="Convert PowerPoint to Markdown in Python" src="https://cdn-images-1.medium.com/max/650/1*YxGyhO8Muz8rCUWKgkkCDA.png" /></figure><p>PowerPoint presentations are widely used for business reports, technical training, project reviews, and educational materials. However, when presentation content needs to be reused in documentation, websites, knowledge bases, or version-controlled projects, Markdown is often a more practical format.</p><p>Unlike PowerPoint files, Markdown files are lightweight, easy to edit, and supported by many developer tools and content platforms. Converting PowerPoint to Markdown allows you to reuse slide content and integrate presentations into existing documentation workflows without manually copying and formatting each slide.</p><p>In this article, we’ll show you how to convert PowerPoint presentations to Markdown using Python. We will cover three common scenarios:</p><ul><li>Convert an entire PowerPoint presentation to Markdown</li><li>Convert a specific slide to Markdown</li><li>Convert a range of slides into a separate Markdown document</li></ul><h3>Why Convert PowerPoint to Markdown?</h3><p>Markdown is widely used for technical documentation, online publishing, and knowledge management because of its simplicity and portability.</p><p>Converting PowerPoint files to Markdown can be useful when you need to:</p><ul><li>Publish presentation content as documentation.</li><li>Store presentation materials in Git repositories.</li><li>Convert training slides into readable articles.</li><li>Migrate existing presentation content into a knowledge base.</li><li>Process PowerPoint files automatically in a document workflow.</li></ul><p>This is especially useful when presentation content needs to be maintained alongside source code, project documents, or other text-based resources.</p><h3>Install the Required Package</h3><p>To convert PowerPoint presentations to Markdown in Python, this article uses <a href="https://www.e-iceblue.com/Introduce/presentation-for-python.html">Spire.Presentation for Python</a>. It provides APIs for creating, reading, modifying, and converting .ppt and .pptx files without requiring Microsoft PowerPoint to be installed.</p><p>You can install the package from PyPI by running the following pip command in your terminal:</p><pre>pip install Spire.Presentation</pre><h3>Convert a PowerPoint Presentation to Markdown in Python</h3><p>To convert a complete PowerPoint presentation to Markdown, load the PPTX file and save it in Markdown format. The basic workflow is as follows:</p><ol><li>Create a <strong><em>Presentation</em></strong> object.</li><li>Load the PowerPoint file using <strong><em>Presentation.LoadFromFile()</em></strong>.</li><li>Save the presentation as a Markdown file using <strong><em>Presentation.SaveToFile()</em></strong>.</li></ol><p>The following example demonstrates how to convert an entire PowerPoint presentation to Markdown:</p><pre>from spire.presentation import Presentation, FileFormat<br><br># Input PowerPoint file<br>inputFile = &quot;Sample.pptx&quot;<br><br># Output Markdown file<br>outputFile = &quot;PresentationToMarkdown.md&quot;<br><br># Create a Presentation object<br>presentation = Presentation()<br><br># Load the PowerPoint presentation<br>presentation.LoadFromFile(inputFile)<br><br># Convert PowerPoint to Markdown<br>presentation.SaveToFile(outputFile, FileFormat.Markdown)<br><br># Release resources<br>presentation.Dispose()</pre><p>The same approach can be applied to both .pptx and .ppt formats.</p><h3>Convert a Specific PowerPoint Slide to Markdown in Python</h3><p>Sometimes, converting the entire presentation is unnecessary. You may only need one slide, such as a summary page, a product overview, or a specific section from a larger presentation.</p><p>In this case, you can directly access the required slide and save it as a Markdown file using the <strong><em>ISlide.SaveToFile()</em></strong> method.</p><p>The following Python example converts the second slide of a presentation to Markdown:</p><pre>from spire.presentation import Presentation, FileFormat<br><br># Input PowerPoint file<br>inputFile = &quot;Sample.pptx&quot;<br><br># Output Markdown file<br>outputFile = &quot;SlideToMarkdown.md&quot;<br><br># Create a Presentation object<br>presentation = Presentation()<br><br># Load the PowerPoint presentation<br>presentation.LoadFromFile(inputFile)<br><br># Get the second slide<br>slide = presentation.Slides[1]<br><br># Convert the slide to Markdown<br>slide.SaveToFile(outputFile, FileFormat.Markdown)<br><br># Release resources<br>presentation.Dispose()</pre><p>The slide index here starts from 0, so <em>Slides[1]</em> represents the second slide.</p><h3>Convert a Range of Slides to Markdown in Python</h3><p>In real projects, you may not always need to convert the entire presentation or just one slide. A common requirement is exporting a specific section, such as slides 2–5 of a large presentation.</p><p>To achieve this, you can create a new presentation, copy the required slides into it, and then save the new presentation as Markdown. This approach keeps the original presentation unchanged while allowing you to export only the required content.</p><p>The following example converts slides 2 through 5 into a separate Markdown file:</p><pre>from spire.presentation import Presentation, FileFormat<br><br># Input PowerPoint file<br>inputFile = &quot;Sample.pptx&quot;<br><br># Output Markdown file<br>outputFile = &quot;SelectedSlides.md&quot;<br><br># Slide range to convert (1-based index)<br>startSlide = 2<br>endSlide = 5<br><br># Load the source presentation<br>sourcePresentation = Presentation()<br>sourcePresentation.LoadFromFile(inputFile)<br><br># Get total slide count<br>totalSlides = sourcePresentation.Slides.Count<br><br># Validate slide range<br>if startSlide &lt; 1 or endSlide &gt; totalSlides or startSlide &gt; endSlide:<br>    raise ValueError(&quot;Invalid slide range.&quot;)<br><br># Create a new presentation<br>newPresentation = Presentation()<br><br># Remove the default slide<br>newPresentation.Slides.RemoveAt(0)<br><br># Copy selected slides<br>for i in range(startSlide - 1, endSlide):<br>    newPresentation.Slides.Append(sourcePresentation.Slides[i])<br><br># Convert selected slides to Markdown<br>newPresentation.SaveToFile(outputFile, FileFormat.Markdown)<br><br># Release resources<br>sourcePresentation.Dispose()<br>newPresentation.Dispose()</pre><p>In this example, <em>startSlide</em> and <em>endSlide</em> use one-based slide numbering for readability, while the underlying slide collection uses zero-based indexing. The code therefore subtracts 1 from <em>startSlide</em> when accessing slides.</p><h3>Considerations Before Converting PowerPoint to Markdown</h3><p>PowerPoint and Markdown store content in different ways. While text-based elements usually convert smoothly, some presentation features may need additional adjustment after conversion.</p><p><strong>Text Content</strong></p><p>Titles, paragraphs, and bullet lists are typically preserved well because Markdown provides native support for structured text. However, complex text formatting, such as custom fonts, colors, or positioning, may not be fully retained.</p><p><strong>Images and Graphics</strong></p><p>Images, shapes, diagrams, and other visual elements may require separate handling after conversion. Check whether images are embedded correctly and whether their placement meets your requirements in the Markdown output.</p><p><strong>Complex Layouts</strong></p><p>PowerPoint allows precise placement of objects on a slide, while Markdown follows a linear document structure. Slides with complex arrangements, overlapping objects, or custom designs may need manual refinement after conversion.</p><p><strong>Tables and Charts</strong></p><p>Simple tables are usually easier to represent because Markdown supports tabular structures directly. However, tables with complex formatting or merged cells may require additional adjustment. Charts and other data visualizations may need to be converted into images or reformatted depending on the target Markdown platform.</p><h3>Conclusion</h3><p>Converting PowerPoint presentations to Markdown with Python allows you to transform slide-based content into a more structured and editable format.</p><p>Whether you are migrating documentation, publishing presentation content online, or building an automated processing workflow, Python-based PowerPoint-to-Markdown conversion provides a flexible way to reuse existing presentations.</p><h3>Frequently Asked Questions</h3><h4>Can PowerPoint be converted to Markdown without Microsoft PowerPoint?</h4><p>Yes. PowerPoint files can be converted to Markdown using Python-based PowerPoint processing APIs without requiring Microsoft PowerPoint to be installed on the system.</p><h4>Can I convert only one slide from a PowerPoint presentation?</h4><p>Yes. You can select a specific slide from a presentation and save it as a separate Markdown file.</p><h4>Can I convert multiple selected slides instead of the whole presentation?</h4><p>Yes. You can copy the required slides to a new presentation, and then save the new presentation to Markdown.</p><h4>Does Markdown preserve the original PowerPoint layout?</h4><p>No. Markdown preserves structured content such as text and lists, but it does not maintain PowerPoint’s fixed slide layout. Presentations with complex designs, overlapping objects, or custom positioning may require manual adjustment.</p><h4>Can PowerPoint animations and transitions be converted to Markdown?</h4><p>No. Markdown is designed for text-based content and does not support PowerPoint-specific features such as animations, transitions, or interactive effects.</p><h3>See Also</h3><ul><li><a href="https://medium.com/@alice.yang_10652/convert-powerpoint-to-video-in-python-without-microsoft-powerpoint-installed-44c57795a15a">Convert PowerPoint to Video in Python (Without Microsoft PowerPoint Installed)</a></li><li><a href="https://medium.com/@alice.yang_10652/add-animations-to-powerpoint-in-python-entrance-exit-motion-path-more-d9312a0ff7fc?source=list---------1-------b7b8a58ce0c8------------------------------">Add Animations to PowerPoint in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/encrypt-protect-sign-powerpoint-presentations-in-python-29aa1e0f3b24">Encrypt, Protect &amp; Sign PowerPoint Presentations in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/convert-png-jpg-and-svg-images-to-powerpoint-in-python-a-comprehensive-guide-cbe1dff6f5d6">Convert PNG, JPG, and SVG Images to PowerPoint in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/how-to-create-powerpoint-charts-with-python-column-pie-funnel-waterfall-excel-data-098b33e739e6">How to Create PowerPoint Charts with Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b4d2ea8de81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Dynamically Fill Word Templates with Python]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-dynamically-fill-word-templates-with-python-e7b39620abdd?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7b39620abdd</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fill-word-template]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Thu, 24 Sep 2026 08:15:34 GMT</pubDate>
            <atom:updated>2026-09-24T08:15:34.450Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="How to Dynamically Fill Word Templates with Python" src="https://cdn-images-1.medium.com/max/625/1*mitrgOpWu7ZUIvUeDPKZxw.png" /><figcaption>How to Dynamically Fill Word Templates with Python</figcaption></figure><p>Many business documents have a fixed layout while their content changes for each generated file. For example, invoices, contracts, reports, and certificates usually keep the same formatting, while customer information, dates, amounts, and record details need to be updated.</p><p>Instead of creating every document from scratch, developers can prepare a Word template and populate it with data during document generation.</p><p>In this article, we will demonstrate how to fill Word templates with Python by replacing placeholders, populating Mail Merge fields, updating bookmarks, and creating tables with dynamic data.</p><h3>Environment Setup</h3><p>To fill and manipulate Word templates in Python, we need a library that can work with Word files programmatically. Here, we’ll use <a href="https://www.e-iceblue.com/Introduce/doc-for-python.html">Spire.Doc for Python</a>, which supports creating, reading, and modifying .doc and .docx documents, including working with text, tables, Mail Merge fields, bookmarks, and other document elements.</p><p>Before proceeding, install the library from <a href="https://pypi.org/project/spire-doc/">PyPI</a> using pip:</p><pre>pip install spire.doc</pre><h3>Prepare the Word Template</h3><p>Before writing the code, create a Word template and mark the parts that need to be populated dynamically. Depending on the document structure, you can use placeholders, Mail Merge fields, or bookmarks to mark the locations that need to be updated.</p><h4>Placeholder Template</h4><p>A placeholder template uses normal text as markers inside the document. For example:</p><pre>Customer Name: {{CustomerName}}<br>Company Name: {{CompanyName}}<br>Invoice Number: {{InvoiceNumber}}<br>Invoice Date: {{InvoiceDate}}<br>Total Amount: {{TotalAmount}}</pre><p>During document generation, Python searches for these markers and replaces them with actual values.</p><h4>Mail Merge Template</h4><p>Mail Merge uses Word’s built-in merge fields instead of plain text placeholders. You can insert merge fields in Microsoft Word through:</p><p><strong>Mailings → Insert Merge Field</strong></p><p>The template contains fields such as:</p><pre>«CustomerName»<br>«InvoiceNumber»<br>«TotalAmount»</pre><p>The application provides values for these fields during the merge operation.</p><h4>Bookmark Template</h4><p>Bookmarks define named locations inside a Word document. For example, create bookmarks named:</p><pre>ContractNumber<br>CustomerName<br>EffectiveDate</pre><p>Unlike placeholders, bookmarks do not depend on visible text. They identify a specific position in the document that can be accessed and updated by name.</p><h3>Replace Placeholder Values in Word Template with Python</h3><p>Placeholder replacement works by locating predefined markers in a Word document and replacing them with actual values.</p><p>The <strong>Document.Replace()</strong> method can be used for this purpose. When a template contains multiple placeholders, storing the replacement values in a dictionary keeps the code easier to maintain.</p><p>The following Python example fills an invoice template by replacing placeholder text:</p><pre>from spire.doc import Document, FileFormat<br><br># Load Word template<br>document = Document()<br>document.LoadFromFile(&quot;Invoice_Template.docx&quot;)<br><br># Business data<br>invoice_data = {<br>    &quot;CustomerName&quot;: &quot;John Smith&quot;,<br>    &quot;CompanyName&quot;: &quot;ABC Technologies&quot;,<br>    &quot;InvoiceNumber&quot;: &quot;INV-2026-001&quot;,<br>    &quot;InvoiceDate&quot;: &quot;September 24, 2026&quot;,<br>    &quot;TotalAmount&quot;: &quot;$2,500&quot;<br>}<br><br># Generate placeholder-value mappings<br>replacement_data = {<br>    f&quot;{{{{{key}}}}}&quot;: value<br>    for key, value in invoice_data.items()<br>}<br><br># Replace placeholders<br>for placeholder, value in replacement_data.items():<br>    document.Replace(placeholder, value, True, True)<br><br># Save generated document<br>document.SaveToFile(&quot;Invoice.docx&quot;, FileFormat.Docx)<br><br>document.Close()</pre><p>The placeholder names in the Word document must exactly match the keys defined in Python. If a placeholder is renamed in the template, the corresponding data mapping should also be updated.</p><h3>Fill Word Templates Using Mail Merge in Python</h3><p>Mail Merge uses fields defined in the Word template instead of searching for visible text.</p><p>The <strong>MailMerge.Execute()</strong> method fills these fields based on the field names and values provided by the application.</p><p>A common use case is generating multiple documents from the same template. For example, a system can create separate invoices for different customers from a list of records.</p><pre>from spire.doc import Document, FileFormat<br><br># Word template<br>template_file = &quot;Customer_Invoice_Template.docx&quot;<br><br># Data source<br>customers = [<br>    {<br>        &quot;CustomerName&quot;: &quot;Alice Brown&quot;,<br>        &quot;InvoiceNumber&quot;: &quot;INV-001&quot;,<br>        &quot;TotalAmount&quot;: &quot;$800&quot;<br>    },<br>    {<br>        &quot;CustomerName&quot;: &quot;David Lee&quot;,<br>        &quot;InvoiceNumber&quot;: &quot;INV-002&quot;,<br>        &quot;TotalAmount&quot;: &quot;$1200&quot;<br>    }<br>]<br><br># Generate documents<br>for customer in customers:<br><br>    document = Document()<br><br>    # Load template<br>    document.LoadFromFile(template_file)<br><br>    # Get field names and values<br>    field_names = list(customer.keys())<br>    field_values = list(customer.values())<br><br>    # Execute Mail Merge<br>    document.MailMerge.Execute(field_names, field_values)<br><br>    # Save document<br>    output_file = f&quot;{customer[&#39;InvoiceNumber&#39;]}.docx&quot;<br><br>    document.SaveToFile(output_file, FileFormat.Docx)<br><br>    document.Close()</pre><p>The field names passed to <strong>Execute()</strong> must match the merge fields created in the Word template.</p><p>For batch generation, the values can be loaded from a database, Excel file, CSV file, or another structured data source before executing Mail Merge.</p><h3>Replace Bookmark Content in Word Template with Python</h3><p>Bookmarks provide named locations inside a Word document. They do not rely on visible text matching. Instead, the application navigates to a bookmark by name and replaces its content directly.</p><p>Spire.Doc provides the <strong>BookmarksNavigator</strong> class for working with bookmarks. After locating a bookmark with <strong>BookmarksNavigator.MoveToBookmark()</strong>, you can replace its content using <strong>BookmarksNavigator.ReplaceBookmarkContent()</strong>.</p><p>The following example replaces multiple bookmarks in a contract template.</p><pre>from spire.doc import Document, FileFormat, BookmarksNavigator<br><br># Load Word template<br>document = Document()<br>document.LoadFromFile(&quot;Contract_Template.docx&quot;)<br><br># Contract data<br>contract_data = {<br>    &quot;ContractNumber&quot;: &quot;CT-2026-001&quot;,<br>    &quot;CustomerName&quot;: &quot;ABC Corporation&quot;,<br>    &quot;EffectiveDate&quot;: &quot;September 24, 2026&quot;<br>}<br><br># Create bookmark navigator<br>bookmarkNavigator = BookmarksNavigator(document)<br><br># Replace bookmark content<br>for bookmark_name, value in contract_data.items():<br><br>    bookmarkNavigator.MoveToBookmark(bookmark_name)<br><br>    bookmarkNavigator.ReplaceBookmarkContent(value, True)<br><br># Save generated document<br>document.SaveToFile(&quot;Contract.docx&quot;, FileFormat.Docx)<br><br>document.Close()</pre><p>The bookmark name used in Python must match the bookmark created in Word.</p><p>Bookmarks are useful when working with existing templates where the document layout has already been defined and should remain unchanged.</p><h3>Create and Fill Tables with Dynamic Data in Word with Python</h3><p>Many Word documents contain tables where the number of records changes depending on the data source.</p><p>For example, a sales report may contain different numbers of products each month. Instead of creating a fixed table manually, you can generate the table based on the data length.</p><p>The following example creates a sales report table dynamically.</p><pre>from spire.doc import Document, FileFormat<br><br># Create a Word document<br>document = Document()<br><br># Add a section<br>section = document.AddSection()<br><br># Create a table<br>table = section.AddTable(True)<br><br># Report data<br>sales_data = [<br>    [&quot;Product&quot;, &quot;Quantity&quot;, &quot;Revenue&quot;],<br>    [&quot;Laptop&quot;, &quot;12&quot;, &quot;$24000&quot;],<br>    [&quot;Monitor&quot;, &quot;8&quot;, &quot;$8000&quot;],<br>    [&quot;Keyboard&quot;, &quot;15&quot;, &quot;$1500&quot;]<br>]<br><br># Create table structure<br>table.ResetCells(len(sales_data), len(sales_data[0]))<br><br># Fill table cells<br>for row_index, row_data in enumerate(sales_data):<br><br>    for column_index, value in enumerate(row_data):<br><br>        table.Rows[row_index].Cells[column_index].Paragraphs[0].Text = value<br><br># Save document<br>document.SaveToFile(&quot;Sales_Report.docx&quot;, FileFormat.Docx)<br><br>document.Close()</pre><p>Creating tables dynamically allows the document to adapt to different amounts of data without manually changing the Word template.</p><p>This approach is useful for invoices, reports, statements, and other documents where the number of records is not fixed.</p><h3>Wrap Up</h3><p>Filling Word templates with Python makes it easier to generate customized documents while keeping the original document layout and formatting.</p><p>This article explained how to replace placeholder values, populate Mail Merge fields, update bookmark content, and create tables with dynamic data in Word documents.</p><p>With these methods, you can generate Word files from different data sources while keeping the template design separate from the document generation logic.</p><h3>See More Related Topics</h3><ul><li><a href="https://medium.com/@alice.yang_10652/perform-mail-merge-in-word-with-python-a-comprehensive-guide-6698341fecbc?source=list---------26-------e4065ed63edb------------------------------">Perform Mail Merge in Word with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/replace-bookmark-content-in-word-with-python-d58980894174?source=list---------37-------e4065ed63edb------------------------------">Replace Bookmark Content in Word with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/insert-or-delete-bookmarks-in-word-documents-with-python-ad0f5d2c7b63?source=list---------38-------e4065ed63edb------------------------------">Insert or Delete Bookmarks in Word Documents with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/create-or-extract-tables-in-word-with-python-98b2c5f6d9e5?source=list---------39-------e4065ed63edb------------------------------">Create or Extract Tables in Word with Python</a></li><li><a href="https://medium.com/@alice.yang_10652/create-and-customize-charts-in-word-using-python-a-comprehensive-guide-4c86ce262f78?source=list---------18-------e4065ed63edb------------------------------">Create and Customize Charts in Word Using Python</a></li></ul><h3>Final Words</h3><p><em>Thank you for taking the time to read our article. If you found it helpful or enjoyable, feel free to clap for it. We really appreciate your support!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7b39620abdd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Hide or Remove Formulas in Excel with Python]]></title>
            <link>https://medium.com/@alice.yang_10652/how-to-hide-or-remove-formulas-in-excel-with-python-a4e83090519f?source=rss-ab67334728f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4e83090519f</guid>
            <category><![CDATA[remove-formula]]></category>
            <category><![CDATA[hide-formula]]></category>
            <category><![CDATA[protect-formula]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[excel]]></category>
            <dc:creator><![CDATA[Alice Yang]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 10:21:50 GMT</pubDate>
            <atom:updated>2026-09-21T02:20:58.263Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to hide Excel formulas from view or remove them while keeping the calculated values using Python, without Microsoft Excel installed.</em></p><figure><img alt="Hide or Remove Formulas in Excel with Python" src="https://cdn-images-1.medium.com/max/650/1*DcT5jymNHYcytpSYxXyO5g.jpeg" /><figcaption>Hide or Remove Formulas in Excel with Python</figcaption></figure><p>Excel formulas are useful for automating calculations, but they are not always meant to be visible. When sharing workbooks with clients, teammates, or external systems, you may need to hide formulas to protect business logic or remove them completely to keep only the final results.</p><p>Using Python, you can automate these tasks without opening Microsoft Excel, making it easier to process multiple workbooks or prepare files for distribution.</p><p>In this article, we will demonstrate how to hide or remove formulas in Excel with Python.</p><h3>Hide Formulas vs. Remove Formulas</h3><p>Hiding formulas and removing formulas solve different problems. The right choice depends on whether you still need the workbook to perform calculations after sharing.</p><pre>+--------------------------------------+-------------------------------+-------------------+<br>| Feature                              | Hide Formulas                 | Remove Formulas   |<br>+--------------------------------------+-------------------------------+-------------------+<br>| Formula remains in the workbook      | Yes                           | No                |<br>+--------------------------------------+-------------------------------+-------------------+<br>| Values update when source data       | Yes                           | No                |<br>| changes                              |                               |                   |<br>+--------------------------------------+-------------------------------+-------------------+<br>| Worksheet protection required        | Yes                           | No                |<br>+--------------------------------------+-------------------------------+-------------------+<br>| Reversible                           | Yes, after unprotecting the   | No                |<br>|                                      | worksheet                     |                   |<br>+--------------------------------------+-------------------------------+-------------------+</pre><h3>Project Setup</h3><p>To manipulate Excel formulas programmatically in Python, we will use Spire.XLS for Python. It provides APIs for reading, editing, and saving Excel workbooks, allowing you to handle formula-related operations without relying on Microsoft Excel.</p><p>Before running the examples, install the required package from PyPI:</p><pre>pip install Spire.XLS</pre><h3>Method 1: Hide Formulas in Excel with Python</h3><p>Hiding formulas does not delete them from the workbook. The formulas remain active and continue calculating normally, but users cannot view them in the formula bar when selecting protected cells. This approach is useful when you need to share a workbook while keeping the calculation logic hidden.</p><p>In Spire.XLS, formulas can be hidden by setting the <strong>IsFormulaHidden</strong> property to True and then protecting the worksheet.</p><p>The following example hides formulas in the used range of the first worksheet:</p><pre>from spire.xls import *<br>from spire.xls.common import *<br><br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;Sample.xlsx&quot;)<br><br>sheet = workbook.Worksheets[0]<br><br># Hide formulas in the used range<br>sheet.AllocatedRange.IsFormulaHidden = True<br><br># Protect the worksheet<br>sheet.Protect(&quot;123456&quot;)<br><br>workbook.SaveToFile(<br>    &quot;HideFormulas.xlsx&quot;,<br>    ExcelVersion.Version2016<br>)<br><br>workbook.Dispose()</pre><p>After protection is enabled, users can still see the calculated results, but the underlying formulas are no longer displayed.</p><h4>Keep Specific Cells Editable After Hiding Formulas</h4><p>Worksheet protection locks cells by default. If your workbook contains input areas that users still need to update, unlock those cells before protecting the worksheet.</p><p>The following code hides formulas while keeping B2:C20 editable:</p><pre>sheet.AllocatedRange.IsFormulaHidden = True<br><br># Keep the input range editable<br>sheet.Range[&quot;B2:C20&quot;].Style.Locked = False<br><br>sheet.Protect(&quot;123456&quot;)</pre><p>Alternatively, you can define editable ranges explicitly:</p><pre>sheet.AddAllowEditRange(&quot;InputRange&quot;, sheet.Range[&quot;B2:C20&quot;])<br>sheet.Protect(&quot;123456&quot;)</pre><h4>Hide Formulas in a Specific Cell Range</h4><p>If only certain cells contain formulas that need to be protected, apply IsFormulaHidden directly to that range instead of the entire worksheet:</p><pre>sheet.Range[&quot;D2:D20&quot;].IsFormulaHidden = True<br>sheet.Protect(&quot;123456&quot;)</pre><p>This keeps the hidden-formula setting limited to the selected cells.</p><h3>Method 2: Remove Formulas and Keep Calculated Values in Excel with Python</h3><p>Unlike hiding formulas, removing formulas permanently deletes the calculation logic from the workbook. The cells keep their current displayed values, but they will no longer update when related data changes. This method is useful when creating final reports, exporting data, or sharing files where the original formulas should not be included.</p><p>In Spire.XLS, you can convert formulas into static values by reading the calculated result first, clearing the formula, and writing the value back to the same cell.</p><p>The following example converts all formula cells in a workbook into static values:</p><pre>from spire.xls import *<br>from spire.xls.common import *<br><br>workbook = Workbook()<br>workbook.LoadFromFile(&quot;Sample.xlsx&quot;)<br><br>for sheet in workbook.Worksheets:<br>    for cell in sheet.AllocatedRange:<br>        if cell.HasFormula:<br><br>            # Get the calculated result<br>            value = cell.FormulaValue<br><br>            # Remove the formula<br>            cell.Clear(ExcelClearOptions.ClearContent)<br><br>            # Write the result as a static value<br>            cell.Value2 = value<br><br>workbook.SaveToFile(<br>    &quot;RemoveFormulas.xlsx&quot;,<br>    ExcelVersion.Version2016<br>)<br><br>workbook.Dispose()</pre><p>In this code, cell.FormulaValue retrieves the calculated result of the current cell. cell.Clear() clears the cell content, including both data and formula. cell.Value2 writes the calculated values back to the cell.</p><p><strong>Tip:</strong> If your script changes source data before removing formulas, recalculate the workbook first:</p><pre>workbook.CalculateAllValue()</pre><p>This ensures that the converted values reflect the latest calculations.</p><h3>Conclusion</h3><p>This article showed how to hide or remove formulas in Excel using Python. Whether you need to keep formulas active while preventing them from being viewed, or convert formula cells into static values before sharing a workbook, you can now handle both operations programmatically without requiring Microsoft Excel to be installed.</p><h3>See Related Topics</h3><ul><li><a href="https://python.plainenglish.io/read-edit-calculate-excel-formulas-in-python-no-excel-needed-fe1d63dfab96">Read, Edit &amp; Calculate Excel Formulas in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/7-ways-to-protect-or-encrypt-excel-files-in-python-5a01a8e55c9e">7 Ways to Protect or Encrypt Excel Files in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/5-openpyxl-alternatives-for-excel-automation-in-python-a4834c9a03c0?source=user_profile_page---------15-------------ab67334728f3------------------------">5 Openpyxl Alternatives for Excel Automation in Python</a></li><li><a href="https://medium.com/@alice.yang_10652/how-to-convert-excel-xls-or-xlsx-to-json-in-python-255869be68b2?source=user_profile_page---------12-------------ab67334728f3------------------------">How to Convert Excel XLS or XLSX to JSON in Python</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4e83090519f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>