html轉word


html轉word

將web/html內容導出為world文檔,再java中有很多解決方案,比如使用Jacob、Apache POI、Java2Word、iText等各種方式,以及使用freemarker這樣的模板引擎這樣的方式。php中也有一些相應的方法,但在python中將web/html內容生成world文檔的方法是很少的。其中最不好解決的就是如何將使用js代碼異步獲取填充的數據,圖片導出到word文檔中。

unoconv

  • 優缺點

功能

1.支持將本地html文檔轉換為docx格式的文檔,所以需要先將網頁中的html文件保存到本地,再調用unoconv進行轉換。轉換效果也不錯,使用方法非常簡單。

缺點

1.只能對靜態html進行轉換,對於頁面中有使用ajax異步獲取數據的地方也不能轉換(主要是要保證從web頁面保存下來的html文件中有數據)。
2.只能對html進行轉換,如果頁面中有使用echarts,highcharts等js代碼生成的圖片,是無法將這些圖片轉換到word文檔中;
3.生成的word文檔內容格式不容易控制。
  • 使用
# 安裝
sudo apt-get install unoconv
# 使用
unoconv -f pdf *.odt
unoconv -f doc *.odt
unoconv -f html *.odt

python-docx

  • 優缺點

功能

1.python-docx是一個可以讀寫word文檔的python庫。

缺點

1.功能非常弱。有很多限制比如不支持模板等,只能生成簡單格式的word文檔。

  • 使用方法

獲取網頁中的數據,使用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')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM