Writing a Python Pandas DataFrame to Word document

后端 未结 2 1391
暖寄归人
暖寄归人 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:40

    You can write the table straight into a .docx file using the python-docx library.

    If you are using the Conda or installed Python using Anaconda, you can run the command from the command line:

    conda install python-docx --channel conda-forge
    

    Or to pip install from the command line:

    pip install python-docx
    

    After that is installed, we can use it to open the file, add a table, and then populate the table's cell text with the data frame data.

    import docx
    import pandas as pd
    
    # i am not sure how you are getting your data, but you said it is a
    # pandas data frame
    df = pd.DataFrame(data)
    
    # open an existing document
    doc = docx.Document('./test.docx')
    
    # add a table to the end and create a reference variable
    # extra row is so we can add the header row
    t = doc.add_table(df.shape[0]+1, df.shape[1])
    
    # add the header rows.
    for j in range(df.shape[-1]):
        t.cell(0,j).text = df.columns[j]
    
    # add the rest of the data frame
    for i in range(df.shape[0]):
        for j in range(df.shape[-1]):
            t.cell(i+1,j).text = str(df.values[i,j])
    
    # save the doc
    doc.save('./test.docx')
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题