将此csv作为表导入docx时,如何将列标题与每列中的值对齐?
import numpy as np
import pandas as pd
df = pd.DataFrame({
'Target':['Targetttt','Targetttttttttttttttttt'],
'Something': ['2.037','2.099'],
'Something_long': ['3.123','4.123'],
'Something _even_longer': ['1.123','1.234']
})
df
df.to_csv(r"C:Userscristword_automationSummary_templateTABLE.csv", sep='t', encoding='utf-8', index = False)
import docx
import csv
doc = docx.Document()
with open('TABLE.csv', newline='') as f:
csv_reader = csv.reader(f)
csv_headers = next(csv_reader)
csv_cols = len(csv_headers)
table = doc.add_table(rows=2, cols=csv_cols)
hdr_cells = table.rows[0].cells
for i in range(csv_cols):
hdr_cells[i].text = csv_headers[i]
for row in csv_reader:
row_cells = table.add_row().cells
for i in range(csv_cols):
row_cells[i].text = row[i]
doc.add_page_break()
doc.save("data.docx")
数据帧如下所示:
Target Something Something_long Something _even_longer
0 Targetttt 2.037 3.123 1.123
1 Targetttttttttttt 2.099 4.123 1.234
当将csv导出为word时,表将失去其格式,并且由于每个值的字符长度不同,列中的值不再在每列中对齐。
对于每个单元格,只需按照您想要的方式对齐其第一段:
from docx.enum.text import WD_ALIGN_PARAGRAPH
cell.paragraphs[0].paragraph_format.alignment = WD_ALIGN_PARAGRAPH.LEFT
# --- or .RIGHT or .CENTER if you like ---
您可能希望以不同的方式对齐不同的单元格块,例如,您可能希望行标题左对齐,这在表格布局中是典型的。
实用程序功能可能很方便:
def align_cell(cell, alignment):
for p in cell.paragraphs:
p.paragraph_format.alignment = alignment
这样你就可以直接拨打:
align_cell(cell, WD_ALIGN_PARAGRAPH.RIGHT)
它稍微紧凑一些。