使用Python實(shí)現(xiàn)將Excel表格插入到Word文檔中
在日常辦公場(chǎng)景中,通過(guò)Python腳本自動(dòng)化整合Excel數(shù)據(jù)與Word文檔,能夠?qū)崿F(xiàn)表格的智能遷移,滿(mǎn)足不同場(chǎng)景下數(shù)據(jù)呈現(xiàn)的專(zhuān)業(yè)性要求。直接提取表格內(nèi)容插入Word適用于需要快速傳遞核心數(shù)據(jù)的場(chǎng)景,確保信息精準(zhǔn)直達(dá);完整復(fù)制表格樣式及格式則能保留原數(shù)據(jù)可視化效果,匹配正式報(bào)告對(duì)排版美觀的嚴(yán)苛標(biāo)準(zhǔn);而將表格作為OLE對(duì)象嵌入則兼顧了文檔的動(dòng)態(tài)更新能力,當(dāng)源數(shù)據(jù)發(fā)生變更時(shí),用戶(hù)可通過(guò)雙擊對(duì)象直接調(diào)取Excel進(jìn)行編輯,這種交互式設(shè)計(jì)特別適用于需要長(zhǎng)期維護(hù)的協(xié)作文件。
本文將介紹如何使用Python通過(guò)以上三種方式將Excel表格插入到Word文檔中。
本文所使用的Word文檔操作方法需要用到Free Spire.Doc for Python(PyPI:pip install spire.doc.free),讀取Excel工作表數(shù)據(jù)需要用到Free Spire.XLS for Python(PyPI:pip install spire.xls.free)。
提取Excel工作表數(shù)據(jù)插入Word文檔
我們可以通過(guò)直接讀取Excel工作表數(shù)據(jù),然后在Word文檔中創(chuàng)建表格并插入讀取的數(shù)據(jù),來(lái)實(shí)現(xiàn)Excel表格到Word文檔的插入。
以下是操作步驟:
1.加載 Excel 文件
- 創(chuàng)建 Workbook 實(shí)例并使用 LoadFromFile() 讀取 Excel 文件。
- 通過(guò) Worksheets.get_Item(0) 獲取第一個(gè)工作表。
- 使用 AllocatedRange 獲取已使用的單元格范圍。
2.創(chuàng)建 Word 文檔并添加表格
- 創(chuàng)建 Document 實(shí)例,并使用 AddSection() 添加節(jié)。
- 使用 AddTable() 添加表格。
3.復(fù)制 Excel 的表頭到 Word
- 使用 AddRow() 添加表頭行。
- 通過(guò) AddCell().AddParagraph().AppendText() 填充表頭文本。
4.復(fù)制 Excel 的數(shù)據(jù)行到 Word
- 遍歷 Excel 的數(shù)據(jù)行,使用 AddRow() 添加數(shù)據(jù)行。
- 通過(guò) Cells.get_Item(col).AddParagraph().AppendText() 填充單元格內(nèi)容。
- 如果單元格包含公式,則使用 FormulaValue,否則使用 Value。
5.調(diào)整表格樣式并保存 Word 文檔
- 使用 AutoFit(AutoFitBehaviorType.AutoFitToWindow) 讓表格適應(yīng)窗口。
- 使用 ApplyStyle(DefaultTableStyle.GridTable1LightAccent6) 設(shè)置表格樣式。
- 使用 SaveToFile(path, FileFormat.Docx2019) 保存 Word 文檔。
代碼示例:
from spire.doc import Document, AutoFitBehaviorType, FileFormat, DefaultTableStyle
from spire.xls import Workbook
# 指定Excel文件路徑與輸出Word文檔路徑
excel_file = "Sample.xlsx"
word_file = "output/ExcelDataToWord.docx"
# 讀取 Excel
with Workbook() as workbook:
workbook.LoadFromFile(excel_file)
worksheet = workbook.Worksheets.get_Item(0)
allocated_range = worksheet.AllocatedRange
# 創(chuàng)建 Word 文檔
with Document() as doc:
section = doc.AddSection()
table = section.AddTable()
# 添加表頭行
header_row = table.AddRow()
for col in range(allocated_range.ColumnCount):
cell = header_row.AddCell()
paragraph = cell.AddParagraph()
paragraph.AppendText(allocated_range.get_Item(1, col + 1).Text)
# 添加數(shù)據(jù)行
for row in range(1, allocated_range.RowCount):
data_row = table.AddRow()
for col in range(allocated_range.ColumnCount):
cell = data_row.Cells.get_Item(col)
paragraph = cell.AddParagraph()
cell_value = allocated_range.get_Item(row + 1, col + 1)
text = cell_value.FormulaValue if cell_value.HasFormula else cell_value.Value
paragraph.AppendText(text)
# 自動(dòng)調(diào)整表格并應(yīng)用樣式
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
table.ApplyStyle(DefaultTableStyle.GridTable1LightAccent6)
# 保存 Word 文檔
doc.SaveToFile(word_file, FileFormat.Docx2019)
結(jié)果

復(fù)制Excel工作表數(shù)據(jù)及格式插入Word文檔
我們也可以使用庫(kù)中提供的類(lèi)、屬性和方法來(lái)復(fù)制Excel數(shù)據(jù)到Word文檔的同時(shí),將單元格格式及文本格式一起復(fù)制到Word文檔中,從而實(shí)現(xiàn)高還原度地插入Excel表格到Word文檔。我們需要使用庫(kù)中提供的組件來(lái)新建方法實(shí)現(xiàn)上述操作。以下是操作步驟:
1.加載 Excel 文件
- 創(chuàng)建 Workbook 實(shí)例,并使用 LoadFromFile() 讀取 Excel 文件。
- 獲取第一個(gè)工作表 sheet。
2.創(chuàng)建 Word 文檔并設(shè)置頁(yè)面方向
- 創(chuàng)建 Document 實(shí)例,使用 AddSection() 添加節(jié)。
- 設(shè)置頁(yè)面方向?yàn)闄M向:section.PageSetup.Orientation = PageOrientation.Landscape。
3.創(chuàng)建 Word 表格
- 使用 AddTable(True) 創(chuàng)建表格。
- 通過(guò) ResetCells(sheet.LastRow, sheet.LastColumn) 設(shè)置表格的行數(shù)和列數(shù)。
4.執(zhí)行合并單元格操作
使用 merge_cells(sheet, table) 方法,遍歷 Excel 中的合并單元格,并在 Word 中執(zhí)行相應(yīng)的合并操作。
5.復(fù)制 Excel 數(shù)據(jù)和樣式到 Word 表格
- 遍歷 Excel 表格的每一行和每一列,設(shè)置每行的高度:table.Rows[r - 1].Height = float(sheet.Rows[r - 1].RowHeight)。
- 獲取每個(gè)單元格的數(shù)據(jù)和樣式,使用 AddParagraph().AppendText() 方法將數(shù)據(jù)復(fù)制到 Word 表格中。
- 調(diào)用 copy_style(text_range, x_cell, w_cell) 方法,復(fù)制 Excel 單元格的樣式到 Word 單元格。
6.保存 Word 文檔
使用 SaveToFile("output/CopyExcelDataStyleToWord.docx", FileFormat.Docx2019) 保存 Word 文件。
7.釋放資源
調(diào)用 doc.Dispose() 和 workbook.Dispose() 釋放資源。
代碼示例
from spire.xls import *
from spire.doc import *
def merge_cells(sheet, table):
"""根據(jù) Excel 中的合并單元格信息,在 Word 表格中執(zhí)行相應(yīng)的合并操作。"""
if not sheet.HasMergedCells:
return
for cell_range in sheet.MergedCells:
start_row, start_col = cell_range.Row, cell_range.Column
row_count, col_count = cell_range.RowCount, cell_range.ColumnCount
# 處理水平合并
if col_count > 1:
for row in range(start_row, start_row + row_count):
table.ApplyHorizontalMerge(row - 1, start_col - 1, start_col - 1 + col_count - 1)
# 處理垂直合并
if row_count > 1:
table.ApplyVerticalMerge(start_col - 1, start_row - 1, start_row - 1 + row_count - 1)
def copy_style(text_range, excel_cell, word_cell):
"""將 Excel 單元格的樣式復(fù)制到 Word 單元格。"""
font = excel_cell.Style.Font
text_range.CharacterFormat.TextColor = Color.FromRgb(font.Color.R, font.Color.G, font.Color.B)
text_range.CharacterFormat.FontSize = float(font.Size)
text_range.CharacterFormat.FontName = font.FontName
text_range.CharacterFormat.Bold = font.IsBold
text_range.CharacterFormat.Italic = font.IsItalic
# 設(shè)置單元格背景色
if excel_cell.Style.FillPattern != ExcelPatternType.none:
word_cell.CellFormat.BackColor = Color.FromRgb(excel_cell.Style.Color.R, excel_cell.Style.Color.G,
excel_cell.Style.Color.B)
# 設(shè)置水平對(duì)齊方式
align_map = {
HorizontalAlignType.Left: HorizontalAlignment.Left,
HorizontalAlignType.Center: HorizontalAlignment.Center,
HorizontalAlignType.Right: HorizontalAlignment.Right
}
if excel_cell.HorizontalAlignment in align_map:
text_range.OwnerParagraph.Format.HorizontalAlignment = align_map[excel_cell.HorizontalAlignment]
# 設(shè)置垂直對(duì)齊方式
valign_map = {
VerticalAlignType.Top: VerticalAlignment.Top,
VerticalAlignType.Center: VerticalAlignment.Middle,
VerticalAlignType.Bottom: VerticalAlignment.Bottom
}
if excel_cell.VerticalAlignment in valign_map:
word_cell.CellFormat.VerticalAlignment = valign_map[excel_cell.VerticalAlignment]
# 加載 Excel 文件
workbook = Workbook()
workbook.LoadFromFile("Sample.xlsx")
# 獲取第一個(gè)工作表
sheet = workbook.Worksheets[0]
# 創(chuàng)建 Word 文檔
doc = Document()
section = doc.AddSection()
section.PageSetup.Orientation = PageOrientation.Landscape
# 創(chuàng)建 Word 表格
table = section.AddTable(True)
table.ResetCells(sheet.LastRow, sheet.LastColumn)
# 執(zhí)行合并單元格
merge_cells(sheet, table)
# 復(fù)制 Excel 數(shù)據(jù)和樣式到 Word 表格
for r in range(1, sheet.LastRow + 1):
table.Rows[r - 1].Height = float(sheet.Rows[r - 1].RowHeight)
for c in range(1, sheet.LastColumn + 1):
x_cell = sheet.Range[r, c]
w_cell = table.Rows[r - 1].Cells[c - 1]
# 添加文本并復(fù)制樣式
text_range = w_cell.AddParagraph().AppendText(x_cell.NumberText)
copy_style(text_range, x_cell, w_cell)
# 保存 Word 文檔
doc.SaveToFile("output/CopyExcelDataStyleToWord.docx", FileFormat.Docx2019)
doc.Dispose()
workbook.Dispose()
結(jié)果

將Excel工作表作為OLE對(duì)象嵌入Word文檔
我們還可以直接以O(shè)LE對(duì)象形式將Excel工作表嵌入到Word文檔中,從而實(shí)現(xiàn)在Word文檔中展示表格的同時(shí),使表格擁有Excel的高級(jí)功能。在使用代碼嵌入Excel工作表到Word文檔時(shí),需要先將Excel工作表保存為圖像應(yīng)用于Word文檔中OLE對(duì)象的展示。當(dāng)表格在Word文檔中編輯或更新后,表格展示會(huì)自動(dòng)更新為最新的數(shù)據(jù)。
以下是操作步驟:
1.定義文件路徑
- 定義 Excel 文件路徑 excel_path 和輸出 Word 文件路徑 output_doc_path。
- 定義圖像文件路徑 image_path。
2.創(chuàng)建 Word 文檔并設(shè)置頁(yè)面方向
- 創(chuàng)建 Document 實(shí)例,使用 AddSection() 添加節(jié)。
- 設(shè)置頁(yè)面方向?yàn)闄M向:section.PageSetup.Orientation = PageOrientation.Landscape。
- 使用 AddParagraph() 添加段落。
3.載入 Excel 文件并獲取工作表
- 創(chuàng)建 Workbook 實(shí)例,并使用 LoadFromFile() 讀取 Excel 文件。
- 獲取第一個(gè)工作表 sheet。
4.將 Excel 表格轉(zhuǎn)換為圖像并保存
使用 sheet.ToImage() 方法將工作表轉(zhuǎn)換為圖像,并保存為 image_path。
5.創(chuàng)建并加載工作表圖像
創(chuàng)建 DocPicture 實(shí)例,并使用 LoadImage() 加載工作表圖像。
6.將 OLE 對(duì)象(Excel 工作表)插入到 Word 文檔
- 使用 paragraph.AppendOleObject() 插入 Excel 工作表作為 OLE 對(duì)象,并將類(lèi)型設(shè)置為 OleObjectType.ExcelWorksheet。
- 設(shè)置 OLE 對(duì)象不顯示為圖標(biāo):ole.DisplayAsIcon = False。
7.保存 Word 文檔
使用 SaveToFile(output_doc_path, FileFormat.Docx2019) 保存 Word 文件。
代碼示例
import os
from spire.doc import Document, DocPicture, FileFormat, OleObjectType, PageOrientation
from spire.xls import Workbook
# 定義文件路徑
excel_path = "Sample.xlsx"
output_doc_path = os.path.join("output", "InsertExcelOleToWord.docx")
image_path = "SheetImage.png"
# 創(chuàng)建Word文檔并配置頁(yè)面方向
with Document() as doc:
section = doc.AddSection()
section.PageSetup.Orientation = PageOrientation.Landscape
paragraph = section.AddParagraph()
# 載入Excel文件并獲取第一個(gè)工作表
with Workbook() as workbook:
workbook.LoadFromFile(excel_path)
sheet = workbook.Worksheets.get_Item(0)
# 將Excel表格轉(zhuǎn)換為圖像并保存
image_stream = sheet.ToImage(0, 0, sheet.AllocatedRange.RowCount, sheet.AllocatedRange.ColumnCount)
image_stream.Save(image_path)
# 創(chuàng)建DocPicture對(duì)象,并加載工作表圖像
pic = DocPicture(doc)
pic.LoadImage(image_path)
# 將OLE對(duì)象(Excel工作表)插入到Word文檔
ole = paragraph.AppendOleObject(excel_path, pic, OleObjectType.ExcelWorksheet)
# 設(shè)置不顯示OLE對(duì)象為圖標(biāo)
ole.DisplayAsIcon = False
# 保存Word文檔
doc.SaveToFile(output_doc_path, FileFormat.Docx2019)
結(jié)果

以上就是使用Python實(shí)現(xiàn)將Excel表格插入到Word文檔中的詳細(xì)內(nèi)容,更多關(guān)于Python Excel插入Word的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 使用python批量讀取word文檔并整理關(guān)鍵信息到excel表格的實(shí)例
- Python實(shí)現(xiàn)Word表格轉(zhuǎn)成Excel表格的示例代碼
- Python實(shí)現(xiàn)將Word表格嵌入到Excel中
- 利用Python實(shí)現(xiàn)讀取Word表格計(jì)算匯總并寫(xiě)入Excel
- Python實(shí)現(xiàn)將Excel內(nèi)容插入到Word模版中
- 使用python將CSV和Excel表格數(shù)據(jù)導(dǎo)入到Word表格
- Python實(shí)現(xiàn)快速提取Word表格并寫(xiě)入Excel
相關(guān)文章
keras實(shí)現(xiàn)VGG16方式(預(yù)測(cè)一張圖片)
這篇文章主要介紹了keras實(shí)現(xiàn)VGG16方式(預(yù)測(cè)一張圖片),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
python實(shí)現(xiàn)集中式的病毒掃描功能詳解
這篇文章主要介紹了python實(shí)現(xiàn)集中式的病毒掃描功能,結(jié)合實(shí)例形式分析了Python集中式的病毒掃描相關(guān)原理、實(shí)現(xiàn)方法與操作注意事項(xiàng),需要的朋友可以參考下2019-07-07
Python使用Dijkstra算法實(shí)現(xiàn)求解圖中最短路徑距離問(wèn)題詳解
這篇文章主要介紹了Python使用Dijkstra算法實(shí)現(xiàn)求解圖中最短路徑距離問(wèn)題,簡(jiǎn)單描述了Dijkstra算法的原理并結(jié)合具體實(shí)例形式分析了Python使用Dijkstra算法實(shí)現(xiàn)求解圖中最短路徑距離的相關(guān)步驟與操作技巧,需要的朋友可以參考下2018-05-05
如何將python代碼打包成pip包(可以pip?install)
這篇文章主要介紹了如何將python代碼打包成pip包(可以pip?install),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
在Linux中通過(guò)Python腳本訪問(wèn)mdb數(shù)據(jù)庫(kù)的方法
這篇文章主要介紹了在Linux中通過(guò)Python腳本訪問(wèn)mdb數(shù)據(jù)庫(kù)的方法,本文示例基于debian系的Linux系統(tǒng),需要的朋友可以參考下2015-05-05
python中array數(shù)組添加一行或一列數(shù)據(jù)的具體實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于python中array數(shù)組添加一行或一列數(shù)據(jù)的具體實(shí)現(xiàn),最近經(jīng)常使用到數(shù)組方法,文中通過(guò)代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09
Python面向?qū)ο蟪绦蛟O(shè)計(jì)類(lèi)的封裝與繼承用法示例
這篇文章主要介紹了Python面向?qū)ο蟪绦蛟O(shè)計(jì)類(lèi)的封裝與繼承用法,結(jié)合實(shí)例形式分析了Python面向?qū)ο蟪绦蛟O(shè)計(jì)中類(lèi)的封裝、繼承相關(guān)概念、原理、用法及操作注意事項(xiàng),需要的朋友可以參考下2019-04-04

