问题
I have a CSV
file like the following one:
user,password,company
Administrator, 123456, test_company
test_user1, abcdf, test_company1
test_user2, 789, test_company2
This should be a table with user
, password
and company
as headers.
How can I write this structure as a table in a docx
file using python?
回答1:
import docx
import csv
doc = docx.Document()
with open('csv.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")
Output:
回答2:
There must be a better solution, but well. You need pandoc on your computer.
Suppose your csv is in tt.csv
. You can do:
df = pd.read_csv('tt.csv', header=None)
df.to_latex('tt.tex', index=False, header=False)
subprocess.run(['pandoc', '-s', '-f' ,'latex', 'tt.tex', '-o', 'tt.docx'])
That's it.
来源:https://stackoverflow.com/questions/48828954/how-to-write-a-csv-table-to-docx-using-python