一、docx庫的安裝方法
? ? ? ? python創(chuàng)建word文檔需要用到docx庫,安裝命令如下:
pip install python-docx
? ? ? ? 注意,安裝的是python-docx。
二、使用方法
? ? ? ? 使用方法有很多,這里只介紹創(chuàng)建文檔并向文檔中寫入數(shù)據(jù)。
import docx
mydoc=docx.Document() # 實(shí)例化文檔對象
mydoc.add_paragraph('') # 增加一個空行
mydoc.add_paragraph('我是一個段落') # 寫入一段內(nèi)容
mydoc.save('文檔名稱.docx') # 保存文檔
三、示例
? ? ? ? 存在一個csv文件,格式如下:
? ? ? ? 現(xiàn)在需要讀取其中的username和content字段,并按照username和content一一對應(yīng),每一對username和content之間空一行,代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-851124.html
import docx
import pandas as pd
mydoc=docx.Document()
df = pd.read_csv('評論.csv')
for username, comment in zip(df['username'], df['content']):
mydoc.add_paragraph(username, style='List Bullet')
mydoc.add_paragraph(comment, style='List Bullet')
mydoc.add_paragraph('') # 增加一個空行
mydoc.save('評論.docx') # 保存文檔
? ? ? ? 注意,參數(shù)style='List Bullet'意思是每寫一段會在段前增加一個段落標(biāo)記,也就是一個小黑點(diǎn),如果不需要的話把這個參數(shù)刪掉。文章來源地址http://www.zghlxwxcb.cn/news/detail-851124.html
到了這里,關(guān)于python創(chuàng)建word文檔并向word中寫數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!