使用Python實現(xiàn)將Excel表格插入到Word文檔中
在日常辦公場景中,通過Python腳本自動化整合Excel數(shù)據(jù)與Word文檔,能夠?qū)崿F(xiàn)表格的智能遷移,滿足不同場景下數(shù)據(jù)呈現(xiàn)的專業(yè)性要求。直接提取表格內(nèi)容插入Word適用于需要快速傳遞核心數(shù)據(jù)的場景,確保信息精準(zhǔn)直達(dá);完整復(fù)制表格樣式及格式則能保留原數(shù)據(jù)可視化效果,匹配正式報告對排版美觀的嚴(yán)苛標(biāo)準(zhǔn);而將表格作為OLE對象嵌入則兼顧了文檔的動態(tài)更新能力,當(dāng)源數(shù)據(jù)發(fā)生變更時,用戶可通過雙擊對象直接調(diào)取Excel進(jìn)行編輯,這種交互式設(shè)計特別適用于需要長期維護(hù)的協(xié)作文件。
本文將介紹如何使用Python通過以上三種方式將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文檔
我們可以通過直接讀取Excel工作表數(shù)據(jù),然后在Word文檔中創(chuàng)建表格并插入讀取的數(shù)據(jù),來實現(xiàn)Excel表格到Word文檔的插入。
以下是操作步驟:
1.加載 Excel 文件
- 創(chuàng)建 Workbook 實例并使用 LoadFromFile() 讀取 Excel 文件。
- 通過 Worksheets.get_Item(0) 獲取第一個工作表。
- 使用 AllocatedRange 獲取已使用的單元格范圍。
2.創(chuàng)建 Word 文檔并添加表格
- 創(chuàng)建 Document 實例,并使用 AddSection() 添加節(jié)。
- 使用 AddTable() 添加表格。
3.復(fù)制 Excel 的表頭到 Word
- 使用 AddRow() 添加表頭行。
- 通過 AddCell().AddParagraph().AppendText() 填充表頭文本。
4.復(fù)制 Excel 的數(shù)據(jù)行到 Word
- 遍歷 Excel 的數(shù)據(jù)行,使用 AddRow() 添加數(shù)據(jù)行。
- 通過 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) # 自動調(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文檔
我們也可以使用庫中提供的類、屬性和方法來復(fù)制Excel數(shù)據(jù)到Word文檔的同時,將單元格格式及文本格式一起復(fù)制到Word文檔中,從而實現(xiàn)高還原度地插入Excel表格到Word文檔。我們需要使用庫中提供的組件來新建方法實現(xiàn)上述操作。以下是操作步驟:
1.加載 Excel 文件
- 創(chuàng)建 Workbook 實例,并使用 LoadFromFile() 讀取 Excel 文件。
- 獲取第一個工作表 sheet。
2.創(chuàng)建 Word 文檔并設(shè)置頁面方向
- 創(chuàng)建 Document 實例,使用 AddSection() 添加節(jié)。
- 設(shè)置頁面方向為橫向:section.PageSetup.Orientation = PageOrientation.Landscape。
3.創(chuàng)建 Word 表格
- 使用 AddTable(True) 創(chuàng)建表格。
- 通過 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)。
- 獲取每個單元格的數(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è)置水平對齊方式 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è)置垂直對齊方式 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") # 獲取第一個工作表 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對象嵌入Word文檔
我們還可以直接以O(shè)LE對象形式將Excel工作表嵌入到Word文檔中,從而實現(xiàn)在Word文檔中展示表格的同時,使表格擁有Excel的高級功能。在使用代碼嵌入Excel工作表到Word文檔時,需要先將Excel工作表保存為圖像應(yīng)用于Word文檔中OLE對象的展示。當(dāng)表格在Word文檔中編輯或更新后,表格展示會自動更新為最新的數(shù)據(jù)。
以下是操作步驟:
1.定義文件路徑
- 定義 Excel 文件路徑 excel_path 和輸出 Word 文件路徑 output_doc_path。
- 定義圖像文件路徑 image_path。
2.創(chuàng)建 Word 文檔并設(shè)置頁面方向
- 創(chuàng)建 Document 實例,使用 AddSection() 添加節(jié)。
- 設(shè)置頁面方向為橫向:section.PageSetup.Orientation = PageOrientation.Landscape。
- 使用 AddParagraph() 添加段落。
3.載入 Excel 文件并獲取工作表
- 創(chuàng)建 Workbook 實例,并使用 LoadFromFile() 讀取 Excel 文件。
- 獲取第一個工作表 sheet。
4.將 Excel 表格轉(zhuǎn)換為圖像并保存
使用 sheet.ToImage() 方法將工作表轉(zhuǎn)換為圖像,并保存為 image_path。
5.創(chuàng)建并加載工作表圖像
創(chuàng)建 DocPicture 實例,并使用 LoadImage() 加載工作表圖像。
6.將 OLE 對象(Excel 工作表)插入到 Word 文檔
- 使用 paragraph.AppendOleObject() 插入 Excel 工作表作為 OLE 對象,并將類型設(shè)置為 OleObjectType.ExcelWorksheet。
- 設(shè)置 OLE 對象不顯示為圖標(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文檔并配置頁面方向 with Document() as doc: section = doc.AddSection() section.PageSetup.Orientation = PageOrientation.Landscape paragraph = section.AddParagraph() # 載入Excel文件并獲取第一個工作表 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對象,并加載工作表圖像 pic = DocPicture(doc) pic.LoadImage(image_path) # 將OLE對象(Excel工作表)插入到Word文檔 ole = paragraph.AppendOleObject(excel_path, pic, OleObjectType.ExcelWorksheet) # 設(shè)置不顯示OLE對象為圖標(biāo) ole.DisplayAsIcon = False # 保存Word文檔 doc.SaveToFile(output_doc_path, FileFormat.Docx2019)
結(jié)果
以上就是使用Python實現(xiàn)將Excel表格插入到Word文檔中的詳細(xì)內(nèi)容,更多關(guān)于Python Excel插入Word的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python通過get,post方式發(fā)送http請求和接收http響應(yīng)的方法
這篇文章主要介紹了python通過get,post方式發(fā)送http請求和接收http響應(yīng)的方法,涉及Python使用urllib模塊與urllib2模塊實現(xiàn)get與post發(fā)送數(shù)據(jù)的相關(guān)技巧,需要的朋友可以參考下2015-05-05Python?Web開發(fā)通信協(xié)議WSGI?uWSGI?uwsgi使用對比全面介紹
這篇文章主要為大家介紹了Python?Web開發(fā)通信協(xié)議WSGI?uWSGI?uwsgi使用對比全面介紹,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12python的input,print,eval函數(shù)概述
這篇文章主要為大家概述了python的input,print,eval函數(shù),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-01-01淺析Python與Mongodb數(shù)據(jù)庫之間的操作方法
這篇文章主要介紹了Python與Mongodb數(shù)據(jù)庫之間的操作,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-07-07