Writing a Python Pandas DataFrame to Word document

后端 未结 2 1393
暖寄归人
暖寄归人 2020-12-04 20:10

I\'m working on creating a Python generated report that uses Pandas DataFrames. Currently I am using the DataFrame.to_string() method. However this writes to th

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 20:53

    def doctable(data, tabletitle, pathfile):
        from docx import Document
        import pandas as pd
        document = Document()
        data = pd.DataFrame(data)  # My input data is in the 2D list form
        document.add_heading(tabletitle)
        table = document.add_table(rows=(data.shape[0]), cols=data.shape[1])  # First row are table headers!
        for i, column in enumerate(data) :
            for row in range(data.shape[0]) :
                table.cell(row, i).text = str(data[column][row])
        document.save(pathfile)
    

提交回复
热议问题