【问题标题】:How do I add formatted values from a Style Object into a Word document table using the docx module?如何使用 docx 模块将样式对象中的格式化值添加到 Word 文档表中?
【发布时间】:2021-03-04 18:08:32
【问题描述】:

我通过使用 pandas 和 Python .docx 模块的数据框中的数据在 Word 文档中添加表格。我希望数据值以我应用于数据框的格式样式出现在 Word 文档表中。某些列具有带逗号分隔符 {:,} 的数字格式,而某些列具有百分比格式 {:.2%}。

但是,在我将格式样式添加到数据框后,数据框变成了 Style 对象。然后,我无法将 Style 对象中的值添加到 Word 中的表中。

如何将格式样式应用于数据框中的值,以便它们在 Word 文档表中显示为样式?

import pandas as pd
import docx
import openpyxl 
  
# initialize list of lists 
data = [[150000, 100000,.14565], [250000, 200000,.16334]]
  
# Create the pandas DataFrame 
df = pd.DataFrame(data, columns = ['Revenues', 'Expenditures', 'Surplus']) 

# Apply style to pandas DataFrame 
df = df.style.format({"Revenues": "${:20,.0f}","Expenditures": "${:20,.0f}","Surplus": "{:.2%}"})

# Create the Word Document
doc = docx.Document('hello.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])
        
doc.save('hello_python_output.docx')


【问题讨论】:

    标签: pandas dataframe number-formatting python-docx


    【解决方案1】:

    而不是使用 style 对象(主要用于在 HTML 中呈现数据框)。您可以将这些转换直接应用于数据框(从而使每一列成为stringobject dtype)并将这些字符串值写入您的word 文档。您可以通过transform 方法应用您的格式:

    conversions = {
        "Revenues": "${:20,.0f}",
        "Expenditures": "${:20,.0f}",
        "Surplus": "{:.2%}"
    }
    
    new_df = df.transform({k: v.format for k, v in conversions.items()})
    
    print(new_df)
                    Revenues           Expenditures Surplus
    0  $             150,000  $             100,000  14.56%
    1  $             250,000  $             200,000  16.33%
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多