本文目錄一覽:
python中如何將word表格內的內容進行替換
在使用word中的一個自然段,就是一個paragraph,最簡單的方式如下命令獲得全部的段落,這是一個可迭代的類型,類似於數組方式。就可以直接獲得文章中的第一段第一段的全部文字內容,如果我們連貫起來代碼如下獲得run其實也是非常簡單的如下命令python-docx這個包,不僅可以讀出paragraph的內容,還可以往裡面寫。可以使用add_paragraph()方法來添加內容。如下命令代碼每一個屬性都可以查看它的類型,這個類型一般在docx中是個枚舉類型的常量,放在docx.enum.text這個頭文件中。
python輸出word內容
程序導出word文檔的方法
將web/html內容導出為world文檔,再java中有很多解決方案,比如使用Jacob、Apache POI、Java2Word、iText等各種方式,以及使用freemarker這樣的模板引擎這樣的方式。php中也有一些相應的方法,但在python中將web/html內容生成world文檔的方法是很少的。其中最不好解決的就是如何將使用js代碼異步獲取填充的數據,圖片導出到word文檔中。
1. unoconv
功能:
1.支持將本地html文檔轉換為docx格式的文檔,所以需要先將網頁中的html文件保存到本地,再調用unoconv進行轉換。轉換效果也不錯,使用方法非常簡單。
\# 安裝
sudo apt-get install unoconv
\# 使用
unoconv -f pdf *.odt
unoconv -f doc *.odt
unoconv -f html *.odt
缺點:
1.只能對靜態html進行轉換,對於頁面中有使用ajax異步獲取數據的地方也不能轉換(主要是要保證從web頁面保存下來的html文件中有數據)。
2.只能對html進行轉換,如果頁面中有使用echarts,highcharts等js代碼生成的圖片,是無法將這些圖片轉換到word文檔中;
3.生成的word文檔內容格式不容易控制。
2. python-docx
功能:
1.python-docx是一個可以讀寫word文檔的python庫。
使用方法:
1.獲取網頁中的數據,使用python手動排版添加到word文檔中。
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading(‘Document Title’, 0)
p = document.add_paragraph(‘A plain paragraph having some ‘)
p.add_run(‘bold’).bold = True
p.add_run(‘ and some ‘)
p.add_run(‘italic.’).italic = True
document.add_heading(‘Heading, level 1’, level=1)
document.add_paragraph(‘Intense quote’, style=’IntenseQuote’)
document.add_paragraph(
‘first item in unordered list’, style=’ListBullet’
)
document.add_paragraph(
‘first item in ordered list’, style=’ListNumber’
)
document.add_picture(‘monty-truth.png’, width=Inches(1.25))
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = ‘Qty’
hdr_cells[1].text = ‘Id’
hdr_cells[2].text = ‘Desc’
for item in recordset:
row_cells = table.add_row().cells
row_cells[0].text = str(item.qty)
row_cells[1].text = str(item.id)
row_cells[2].text = item.desc
document.add_page_break()
document.save(‘demo.docx’)
from docx import Document
from docx.shared import Inches
document = Document()
for row in range(9):
t = document.add_table(rows=1,cols=1,style = ‘Table Grid’)
t.autofit = False #很重要!
w = float(row) / 2.0
t.columns[0].width = Inches(w)
document.save(‘table-step.docx’)
缺點:
1.功能非常弱。有很多限制比如不支持模板等,只能生成簡單格式的word文檔。
程序導出PDF文檔方法
1.pdfkit
功能:
1.wkhtmltopdf主要用於HTML生成PDF。
2.pdfkit是基於wkhtmltopdf的python封裝,支持URL,本地文件,文本內容到PDF的轉換,其最終還是調用wkhtmltopdf命令。是目前接觸到的python生成pdf效果較好的。
優點:
1.wkhtmltopdf:利用webkit內核將HTML轉為PDF
webkit是一個高效、開源的瀏覽器內核,包括Chrome和Safari在內的瀏覽器都使用了這個內核。Chrome打印當前網頁的功能,其中有一個選項就是直接“保存為 PDF”。
2.wkhtmltopdf使用webkit內核的PDF渲染引擎來將HTML頁面轉換為PDF。高保真,轉換質量很好,且使用非常簡單。
使用方法:
\# 安裝
pip install pdfkit
\# 使用
import pdfkit
pdfkit.from_url(”, ‘out.pdf’)
pdfkit.from_file(‘test.html’, ‘out.pdf’)
pdfkit.from_string(‘Hello!’, ‘out.pdf’)
缺點:
1.對使用echarts,highcharts這樣的js代碼生成的圖標無法轉換為pdf(因為它的功能主要是將html轉換為pdf,而不是將js轉換為pdf)。對於純靜態頁面的轉換效果還是不錯的。
2.其他
其他生成pdf的插件還有:weasyprint,reportlab,PyPDF2等,經簡單試驗都不如pdfkit效果好,且有些用法複雜。
word文字替換批處理之python
媳婦有無數word文檔要替換,百度後發現沒有現成的方法。
google後沒有太合適的。抄抄寫寫弄個python腳本換目錄下所有word內容,共勉之。
import os
from docx import Document
# 放了一些docx 文件
files_dict ={
“/home/test/a/醫療器械臨床試驗第一版-設計/”: “/home/test/a/醫療器械臨床試驗第一版-設計/”,
“/home/test/a/醫療器械臨床試驗第一版-管理制度/”: “/home/test/a/醫療器械臨床試驗第一版-管理制度/”,
“/home/test/a/醫療器械臨床試驗第一版-SOP/”: “/home/test/a/醫療器械臨床試驗第一版-SOP/”,
“/home/test/a/目錄/”: “/home/test/a/目錄/”
}
replace_dict = {
“XXGNK”:”XZDXGWK”,
“心血管專業”: “心臟大血管外科”,
“心血管”:”心臟大血管外科”,
}
def check_and_change(document, replace_dict):
“””
遍歷word中的所有 paragraphs,在每一段中發現含有key 的內容,就替換為 value 。
(key 和 value 都是replace_dict中的鍵值對。)
“””
for para in document.paragraphs:
for i in range(len(para.runs)):
for key, value in replace_dict.items():
if key in para.runs[i].text:
print(key+”–“+value)
para.runs[i].text = para.runs[i].text.replace(key, value)
for table in document.tables:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
for i in range(len(para.runs)):
for key, value in replace_dict.items():
if key in para.runs[i].text:
print(key+”–“+value)
para.runs[i].text = para.runs[i].text.replace(key, value)
return document
def main():
for old_file_path, new_file_path in files_dict.items():
for name in os.listdir(old_file_path):
print(name)
old_file = old_file_path + name
new_file = new_file_path + name
if old_file.split(“.”)[1] == ‘docx’:
document = Document(old_file)
document = check_and_change(document, replace_dict)
document.save(new_file)
print(“^”*30)
if __name__ == ‘__main__’:
main()
python讀取word文檔內容
import fnmatch, os, sys, win32com.client
readpath=r’D:\123′
wordapp = win32com.client.gencache.EnsureDispatch(“Word.Application”)
try:
for path, dirs, files in os.walk(readpath):
for filename in files:
if not fnmatch.fnmatch(filename, ‘*.docx’):continue
doc = os.path.abspath(os.path.join(path,filename))
print ‘processing %s…’ % doc
wordapp.Documents.Open(doc)
docastext = doc[:-4] + ‘txt’
wordapp.ActiveDocument.SaveAs(docastext,FileFormat=win32com.client.constants.wdFormatText)
wordapp.ActiveDocument.Close()
finally:
wordapp.Quit()
print ‘end’
f=open(r’d:\123\test.txt’,’r’)
for line in f.readlines():
print line.decode(‘gbk’)
f.close()
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/298026.html