将 Python 数据帧写入具有特定格式的 Word/Excel 文档

Write Python Dataframe into a Word/Excel Document with Specific Formatting

嗨,我是 python 的新手,希望你们中的任何人都可以就模板问题提供建议。

我已经设法解析了一个 excel 文件,用数据制作了一个数据框(使用 xl.parse、.loc、str.contains、str.split、sort_index 等方法)并将其输出到另一个 excel 文件中,如下所示: Excel doc with dataframe

我在格式化方面遇到了困难 - 添加边框、加粗某些字符串行(不一定在 2 个不同输出文件之间的相同位置)、用颜色突出显示某些单元格等。

我有一个必须遵循的模板,就像这样(word doc):Format to replicate (word doc)

我正在考虑两种解决方法:

1) 通过 python 从头开始​​复制格式(作为 excel 或 word 文档)

2) 将输出excel文件中的原始数据用模板

写入word doc

如果有人能告诉我哪种方式更有效,还有哪些库,那就太好了,methods/functions我可以研究一下以完成工作。

谢谢!

有几种好方法可以做到这一点。我通常采用以下两种方法之一:

1) XLSX writer: This package has support for changing formatting of Excel files. So my workflow would be to export to Excel using Pandas in Python then after the data is in the Excel file I'd manipulate the formatting with XLSX. Pandas and XLSX Writer play well together as you can see from this demo

2) 对于某些工作流程,我发现我想在 Excel 中执行的 amount/type 格式设置与 XLSX Writer 一起使用是不合理的。在这些情况下,最好的办法是将您的数据放在不是 Excel 然后 link Excel 的地方。一种简单的方法是将数据转储到 CSV,然后 link 将格式良好的 Excel 文件转换为 CSV。您还可以使用 Pandas 将数据推送到数据库中,然后让 Excel 文件从数据库中提取数据。

我推荐使用 xlsxwriter。您可以使用如下代码添加边框:

import xlsxwriter

# left
begcol = 2 # skip first col
endcol = ws.UsedRange.Columns.Count
begrow = 2 # skip first row
endrow = ws.UsedRange.Rows.Count

ws.Range(ws.Cells(begrow, begcol), 
         ws.Cells(endrow, endcol)).Borders(7).LineStyle = 1 # continuous
ws.Range(ws.Cells(begrow, begcol), 
         ws.Cells(endrow, endcol)).Borders(7).Weight = 2 # thin

你可以这样加粗一行:

# bold last row
ws.Range(ws.Cells(endrow, begcol),
         ws.Cells(endrow, endcol)).Font.Bold = True

您可以像这样设置单元格的背景颜色:

format = workbook.add_format()

format.set_pattern(1)  # This is optional when using a solid fill.
format.set_bg_color('green')

worksheet.write('A1', 'Ray', format)

要写入 Word 文档,您可以使用 docx with an example of how to do that here: http://pbpython.com/python-word-template.html