python-docx把dataframe表格添加到word文件中
python-docx把dataframe表格添加到word文件中思路較為簡單:
- 先把
dataframe
格式轉(zhuǎn)變?yōu)?code>table - 新建一個(gè)段落:
document.add_paragraph()
- 把
table
添加到這個(gè)段落下方
效果圖
示例代碼
from docx import Document, oxml import pandas as pd import numpy as np from docx.oxml.ns import qn from docx.oxml import OxmlElement import random # 設(shè)置 table 的邊框,用法與 cell 類似 def set_table_boarder(table, **kwargs): """ Set table`s border Usage: set_table_border( cell, top={"sz": 12, "val": "single", "color": "#FF0000"}, bottom={"sz": 12, "color": "#00FF00", "val": "single"}, left={"sz": 24, "val": "dashed"}, right={"sz": 12, "val": "dashed"}, ) """ borders = OxmlElement('w:tblBorders') for tag in ('bottom', 'top', 'left', 'right', 'insideV', 'insideH'): edge_data = kwargs.get(tag) if edge_data: any_border = OxmlElement(f'w:{tag}') for key in ["sz", "val", "color", "space", "shadow"]: if key in edge_data: any_border.set(qn(f'w:{key}'), str(edge_data[key])) borders.append(any_border) table._tbl.tblPr.append(borders) return table def set_table_singleBoard(table): """為表格添加邊框""" return set_table_boarder( table, top={"sz": 4, "val": "single", "color": "#000000"}, bottom={"sz": 4, "val": "single", "color": "#000000"}, left={"sz": 4, "val": "single", "color": "#000000"}, right={"sz": 4, "val": "single", "color": "#000000"}, insideV={"sz": 4, "val": "single", "color": "#000000"}, insideH={"sz": 4, "val": "single", "color": "#000000"} ) def convert_df_to_table(document, dataframe: pd.DataFrame, index_list=None, column_list=None): """把table轉(zhuǎn)為dataframe :param document: 文檔對(duì)象 :param dataframe: dataframe格式數(shù)據(jù) :param index_list: 最左邊一列顯示的內(nèi)容 :param column_list: (第一行)列名稱需要顯示的內(nèi)容 """ rows = dataframe.shape[0] cols = dataframe.shape[1] if index_list is not None: cols += 1 if column_list is not None: rows += 1 table = document.add_table(rows=rows, cols=cols) row_i = 0 col_i = 0 if index_list is not None: raise if column_list is not None: hdr_cells = table.rows[row_i].cells for _col_i, _v in enumerate(column_list): hdr_cells[_col_i].text = str(_v) row_i += 1 for _i, series_info in enumerate(dataframe.iterrows()): series = series_info[1] hdr_cells = table.rows[row_i + _i].cells for _c_i, _cell_value in enumerate(series): hdr_cells[col_i + _c_i].text = str(_cell_value) return table def main(): # 1. 把要插入的數(shù)據(jù)調(diào)整為dataframe格式 dataframe = pd.DataFrame({ "列1": [round(random.random(), 2) for _ in range(3)], "列2": [round(random.random(), 2) for _ in range(3)], "列3": [round(random.random(), 2) for _ in range(3)], }) document = Document() # 2. 插入表格 table = convert_df_to_table(document, dataframe, column_list=dataframe.columns.tolist()) table = set_table_singleBoard(table) # 表格添加邊框 base_paragraphs = document.add_paragraph("下面插入表格:") base_paragraphs._p.addnext(table._tbl) # 3. 保存修改后的結(jié)果 document.save('測(cè)試_添加表格.docx') # 保存后導(dǎo)出 if __name__ == '__main__': main()
上述代碼會(huì)得到如下效果圖:
到此這篇關(guān)于python-docx把dataframe表格添加到word文件中的文章就介紹到這了,更多相關(guān)python docx把表格添加到word內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Anaconda+vscode+pytorch環(huán)境搭建過程詳解
這篇文章主要介紹了Anaconda+vscode+pytorch環(huán)境搭建過程詳解,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-05-05解決Keras中Embedding層masking與Concatenate層不可調(diào)和的問題
這篇文章主要介紹了解決Keras中Embedding層masking與Concatenate層不可調(diào)和的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-06-06Django 實(shí)現(xiàn) Websocket 廣播、點(diǎn)對(duì)點(diǎn)發(fā)送消息的代碼
這篇文章主要介紹了Django 實(shí)現(xiàn) Websocket 廣播、點(diǎn)對(duì)點(diǎn)發(fā)送消息,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06使用Python實(shí)現(xiàn)繪制地圖的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)繪制地圖相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01Python動(dòng)態(tài)導(dǎo)入模塊的方法實(shí)例分析
這篇文章主要介紹了Python動(dòng)態(tài)導(dǎo)入模塊的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Python動(dòng)態(tài)導(dǎo)入系統(tǒng)模塊、自定義模塊以及模塊列表的相關(guān)操作技巧,需要的朋友可以參考下2018-06-06Python如何優(yōu)雅的實(shí)現(xiàn)自增枚舉類
枚舉類型在編程中扮演著重要的角色,它們?yōu)樽兞抠x予了更加清晰的含義,然而,在Python中,實(shí)現(xiàn)自增的枚舉類并非直接而簡單的任務(wù),本文將深入討論如何通過不同的方式優(yōu)雅地實(shí)現(xiàn)自增的枚舉類,需要的朋友可以參考下2023-12-12