使用 IRONXL FOR PYTHON 從 Excel 數據生成 Word 文檔於 Python 中 Curtis Chau 更新日期:6月 22, 2025 Download IronXL pip 下載 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article Generating Word templates from Excel spreadsheets using Python offers numerous benefits that can significantly enhance efficiency, accuracy, and presentation in various professional and personal contexts. By leveraging automation, customization, and data integrity, professionals can ensure their Word documents are effective communication tools that convey essential information clearly and accurately. One such library that can convert Microsoft Excel to Microsoft Word is the IronXL Python package from Iron Software and the python-docx library. This article will examine the steps required to generate Word documents from Excel files. How to Generate Word Document from Excel Data in Python Create a Python file named excelToWord.py. Install the IronXL and python-docx packages. Create or add an Excel file to the project folder. Read Excel documents using IronXL. Create a Word document and insert Excel data using python-docx. What is IronXL? IronXL for Python is a robust library developed by Iron Software that allows developers to create, read, and edit Excel files (XLS, XLSX, and CSV) in Python projects. Here are some key features and benefits of using IronXL: Key Features No Excel Dependency: IronXL does not require installing Microsoft Excel on your server, making it ideal for server environments without Excel. Intuitive API: IronXL provides a natural and intuitive API for working with Excel files, making it easy to integrate into your Python projects. Support for Multiple Formats: IronXL supports various Excel file formats, including XLS, XLSX, CSV, and TSV. Cell Styling: You can style cells with different fonts, sizes, backgrounds, borders, and number formats. Formula Handling: IronXL can work with Excel formulas and re-calculate them whenever a sheet is edited. Cross-Platform Compatibility: IronXL works on Windows, macOS, Linux, Docker, Azure, and AWS. What is python-docx python-docx is a Python library that creates, modifies, and works with Microsoft Word documents such as .docx files. It provides a simple API to interact with Word documents, allowing you to perform tasks such as adding text, formatting, inserting tables and images, and more. Key Features 1. Creating Documents You can generate Word documents from scratch and add content, including paragraphs, tables, headings, and more. This package can also be used to edit individual documents. 2. Text Manipulation Add and modify paragraphs of text. Format text (e.g., bold, italic, underline, etc.) using "runs" (parts of text with different styles within a paragraph). Add and style headings of various levels. 3. Adding Tables Create tables with a specified number of rows and columns. Access and modify individual cells in a table. 4. Lists Create bulleted or numbered lists with predefined styles. 5. Working with Styles Apply predefined styles like "Heading 1", "Normal", etc. You can also define and apply custom styles to paragraphs or text. 6. Inserting Images Insert images into the document at specific locations. You can resize images by specifying their width and height. Prerequisites Before we dive into the code, ensure that you have the following prerequisites: Python Installed: Make sure you have Python installed on your machine. You can download it from the official Python website. IronXL Installed: You need to install the IronXL package. You can do this using pip. python-docx Installed: You need to install the python-docx package. You can do this using pip. Excel File: Create a sample Excel file with data. Step 1: Create a Python File Named excelToWord.py Open your favorite IDE like Visual Studio Code and create a file called excelToWord.py. Step 2: Add IronXL and python-docx Packages Use Pip to install the IronXL and python-docx packages. pip install IronXL python-docx pip install IronXL python-docx SHELL Step 3: Create or Add an Excel File to the Project Folder Copy the sample Excel file to your code folder. The file contains the below data. Step 4: Read the Excel Document Using IronXL Using IronXL, load the Excel document and read all the cells using the code below. import ironxl # Import Document class from python-docx to work with Word documents from docx import Document # Set the License Key for IronXL (replace 'your license' with your actual license key) ironxl.License.LicenseKey = "your license" # Load the Excel workbook and select the first worksheet workbook = ironxl.WorkBook.Load("sample.xlsx") sheet = workbook.WorkSheets[0] # Read data from the Excel sheet data = [] # Iterate through rows and columns in the Excel sheet for row in range(0, len(sheet.Rows)): row_data = [] for col in range(0, len(sheet.Columns)): cell_value = sheet.GetCellAt(row, col) print(cell_value) # Print each cell value row_data.append(cell_value) data.append(row_data) import ironxl # Import Document class from python-docx to work with Word documents from docx import Document # Set the License Key for IronXL (replace 'your license' with your actual license key) ironxl.License.LicenseKey = "your license" # Load the Excel workbook and select the first worksheet workbook = ironxl.WorkBook.Load("sample.xlsx") sheet = workbook.WorkSheets[0] # Read data from the Excel sheet data = [] # Iterate through rows and columns in the Excel sheet for row in range(0, len(sheet.Rows)): row_data = [] for col in range(0, len(sheet.Columns)): cell_value = sheet.GetCellAt(row, col) print(cell_value) # Print each cell value row_data.append(cell_value) data.append(row_data) PYTHON Step 5: Create a Word Document and Insert Excel Data Using python-docx The Word document generation process involves creating a Word document and inserting data that was read from the Excel file. # Create a new Word document doc = Document() # Add a title to the Word document doc.add_heading('Excel Data Export Using Python Docx', 0) # Create a table with headers (first row of Excel data) table = doc.add_table(rows=1, cols=len(data[0])) hdr_cells = table.rows[0].cells # Populate header cells with data for i, header in enumerate(data[0]): hdr_cells[i].text = str(header) # Populate table with data from Excel for row in data[1:]: row_cells = table.add_row().cells for i, cell in enumerate(row): row_cells[i].text = str(cell) # Save the generated Word document doc.save("sample.docx") # Create a new Word document doc = Document() # Add a title to the Word document doc.add_heading('Excel Data Export Using Python Docx', 0) # Create a table with headers (first row of Excel data) table = doc.add_table(rows=1, cols=len(data[0])) hdr_cells = table.rows[0].cells # Populate header cells with data for i, header in enumerate(data[0]): hdr_cells[i].text = str(header) # Populate table with data from Excel for row in data[1:]: row_cells = table.add_row().cells for i, cell in enumerate(row): row_cells[i].text = str(cell) # Save the generated Word document doc.save("sample.docx") PYTHON Complete Code for Generating Word Documents # Import required libraries import ironxl from docx import Document # Set the License Key for IronXL ironxl.License.LicenseKey = "your license" # Load the Excel workbook workbook = ironxl.WorkBook.Load("sample.xlsx") sheet = workbook.WorkSheets[0] # Read data from the Excel sheet data = [] # Iterate through rows and columns in the Excel sheet for row in range(0, len(sheet.Rows)): row_data = [] for col in range(0, len(sheet.Columns)): cell_value = sheet.GetCellAt(row, col) print(cell_value) # Print each cell value row_data.append(cell_value) data.append(row_data) # Document generation process # Create a new Word document doc = Document() # Add a title to the Word document doc.add_heading('Excel Data Export Using Python Docx', 0) # Create a table in the Word document table = doc.add_table(rows=1, cols=len(data[0])) hdr_cells = table.rows[0].cells for i, header in enumerate(data[0]): hdr_cells[i].text = str(header) # Add header cells for row in data[1:]: row_cells = table.add_row().cells for i, cell in enumerate(row): row_cells[i].text = str(cell) # Save the Word document doc.save("sample.docx") # Import required libraries import ironxl from docx import Document # Set the License Key for IronXL ironxl.License.LicenseKey = "your license" # Load the Excel workbook workbook = ironxl.WorkBook.Load("sample.xlsx") sheet = workbook.WorkSheets[0] # Read data from the Excel sheet data = [] # Iterate through rows and columns in the Excel sheet for row in range(0, len(sheet.Rows)): row_data = [] for col in range(0, len(sheet.Columns)): cell_value = sheet.GetCellAt(row, col) print(cell_value) # Print each cell value row_data.append(cell_value) data.append(row_data) # Document generation process # Create a new Word document doc = Document() # Add a title to the Word document doc.add_heading('Excel Data Export Using Python Docx', 0) # Create a table in the Word document table = doc.add_table(rows=1, cols=len(data[0])) hdr_cells = table.rows[0].cells for i, header in enumerate(data[0]): hdr_cells[i].text = str(header) # Add header cells for row in data[1:]: row_cells = table.add_row().cells for i, cell in enumerate(row): row_cells[i].text = str(cell) # Save the Word document doc.save("sample.docx") PYTHON Code Explanation This Python script performs two main tasks. 1. Reading Data from an Excel File Using IronXL The script begins by setting up a license for the IronXL library, which is used for handling Excel files in Python. It then loads an Excel file (sample.xlsx) and selects the first worksheet from the file. The script reads the data from the worksheet, iterating through all rows and columns. It collects the values from each cell in a 2D list (data), where each row in the Excel sheet corresponds to a sublist within the data. The values of the cells are printed to the console as they are read. 2. Creating a Word Document Using python-docx A new Word document is created using the python-docx library. The script adds a title ("Excel Data Export Using Python Docx") at the top of the document using a heading. It then creates a table in the document, where the first row of the table contains the headers from the first row of the Excel sheet, and subsequent rows contain the corresponding data from the Excel file. Finally, the Word document is saved as sample.docx. The script reads data from an Excel file (sample.xlsx), processes it, and exports the data into a table in a new Word document (sample.docx). The first row of the Excel sheet is used as table headers, and each row of data from the Excel sheet is added to the Word document as a row in the table. Output Word File IronXL License (Trial Available) IronXL works on a valid license file attached to the code. Users can easily get a trial license from the license page. To use the license, place the license key somewhere in the code as below before using the IronXL library. ironxl.License.LicenseKey = "Your License Key" ironxl.License.LicenseKey = "Your License Key" PYTHON Conclusion The sample code demonstrates an effective way to read data from an Excel file using IronXL and then export that data into a Word document using python-docx. The process involves two main steps: Extracting Data from Excel: The script loads an Excel file and extracts the data from its first worksheet. It iterates through the rows and columns to collect cell values into a list, which can easily be manipulated or saved. Creating and Populating a Word Document: Using the python-docx library, the script creates a new Word document, adds a title, and formats the extracted Excel data into a table in the Word document. It automatically places the first row of Excel data as headers and the remaining rows as table data. This approach allows for seamless data transfer from Excel to Word, which can be useful for tasks such as report generation, data exports, or document automation. The combination of IronXL for Excel handling and python-docx for Word document creation provides a powerful solution for working with these file formats in Python. 常見問題解答 我如何使用 Python 將 Excel 資料轉換為 Word 文件? 您可以使用 IronXL 中的函式庫來閱讀和處理 Excel 檔案,然後使用 python-docx 函式庫來建立和填充 Word 文件,以便使用 Python 將 Excel 資料轉換為 Word 文件。 使用 IronXL 和 python-docx 的優點是什麼? IronXL 和 python-docx 的結合允許 Excel 到 Word 文件轉換的無縫整合和自動化。IronXL 提供功能,如在不需要 Microsoft Excel 的情況下讀取和編輯 Excel 檔案,而 python-docx 則提供簡單的 API 來操作 Word 文件。 如何在未安裝 Microsoft Excel 的情況下在 Python 中讀取 Excel 文件? 您可以使用 IronXL 函式庫在 Python 中讀取 Excel 文件,而無需安裝 Microsoft Excel。IronXL 允許您載入 Excel 檔案並以程式方式存取其數據。 創建 Word 文件以 Excel 資料的流程是什麼? 該過程涉及使用 IronXL 從 Excel 文件讀取資料,然後使用 python-docx 建立一個 Word 文件,將 Excel 資料插入表格或文本塊中。 IronXL 能夠處理多種 Excel 文件格式嗎? 是的,IronXL 支援多種 Excel 檔案格式,如 XLS、XLSX 和 CSV,提供了處理不同類型 Excel 檔案的靈活性。 如何在我的 Python 環境中安裝 IronXL 和 python-docx? 您可以使用 pip 命令在您的 Python 環境中安裝 IronXL 和 python-docx:pip install IronXL python-docx。 自動化 Excel 到 Word 文件轉換的好處是什麼? 自動化 Excel 到 Word 文件轉換可以通過減少手動操作、減少錯誤並允許文檔間的一致格式和數據完整性來提高效率、精確性和展示效果。 如何使用 IronXL 設計 Excel 單元格? IronXL 提供設計 Excel 單元格的功能,使您可以自定義單元格外觀,如設置字體、顏色和邊框,這可以在將數據傳輸到 Word 前用於格式化。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 6月 22, 2025 如何在 Python 中讀取具有多個工作表的 Excel 文件 在這篇文章中,我們將探討如何使用 IronXL for Python 讀取多個 Excel 工作表,包括那些具有多個工作表的文件。 閱讀更多 更新日期 6月 22, 2025 在不需要 Pandas 的情況下,使用 Python 讀取 Excel 文件(無需 Interop) 處理 Microsoft Excel 時,pandas 是首先想到的庫,但還有其他強大的庫如 IronXL,提供性能和速度。 閱讀更多 更新日期 6月 22, 2025 如何使用 Python 將圖片插入 Excel 這篇文章將指導您使用 IronXL 在 Python 中將圖像插入 Excel 的過程。 閱讀更多 如何在 Python 中創建 Excel 文件如何在 Python 中從 Excel 文...
更新日期 6月 22, 2025 如何在 Python 中讀取具有多個工作表的 Excel 文件 在這篇文章中,我們將探討如何使用 IronXL for Python 讀取多個 Excel 工作表,包括那些具有多個工作表的文件。 閱讀更多
更新日期 6月 22, 2025 在不需要 Pandas 的情況下,使用 Python 讀取 Excel 文件(無需 Interop) 處理 Microsoft Excel 時,pandas 是首先想到的庫,但還有其他強大的庫如 IronXL,提供性能和速度。 閱讀更多