python docx文件轉html頁面
文章連結: ofollow,noindex" target="_blank">https://mp.weixin.qq.com/s/uMb2ziRS1NJ1GXIjofeANg
說到word文件轉html的,網上一搜一大把,各種線上word轉html頁面,使用起來也方便。但是在實際專案中要使用的話,需要自己開發,這裡就提供一個簡單的方法。
字尾 .doc 和 .docx 都是word文件,doc是word2003以及之前版本儲存的文件,docx是word2007、word2010等儲存的新型文件,本質都是屬於文字排版的檔案。 注意 這裡提供的方法暫時是針對docx的。
這裡使用 pydocx
的庫,安裝 pip3 install pydocx
,可以直接對docx檔案進行處理,簡單粗暴, PyDocX.to_html("**.docx")
,返回值就是轉換後的html的原始碼,然後再通過寫檔案,寫到html檔案裡面。
from pydocx import PyDocX html = PyDocX.to_html("test.docx") f = open("test.html", 'w', encoding="utf-8") f.write(html) f.close()
這裡對檔案的處理都是當前資料夾下面的,得到的html檔案可以直接開啟檢視,通過對html檢視,可以發現文字轉換成了P標籤,圖片使用base64 的方式顯示的。
這裡是對本地的檔案進行處理,進一步部署到伺服器上,我使用的是Django的專案,前端頁面通過form 表單進行上傳docx 檔案。
<form method="post" enctype="multipart/form-data"> <input type="file" name="file" accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document"> </form>
<input>
type屬性定為file, accept="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
篩選docx 的檔案。
使用地址: https://www.manjiexiang.cn/blog/wordtohtml
這裡上傳的檔案是docx格式的word文件,針對doc 的文件,可以手動改成docx字尾名,進行上傳使用。 嘗試用程式碼轉換成docx,window平臺下有相應的庫,ubantu 暫時無果,歡迎碼友提供解決方法。
介紹下window平臺下的程式碼轉換方法, pip3 install pypiwin32
安裝這個庫,裡面有win32com,將doc文件轉成docx 的。
from win32com import client word = client.Dispatch("Word.Application") doc = word.Documents.Open("D:\\***\\**.doc") //絕對路徑 doc檔案 doc.SaveAs("D:\\***\\**.docx",16) //儲存的docx 檔案,絕對路徑 doc.Close() word.Quit()
歡迎關注我的個人部落格: https://www.manjiexiang.cn/
更多精彩歡迎關注微信號:春風十里不如認識你
一起學習,一起進步,歡迎上車,有問題隨時聯絡,一起解決!!!