การสร้างไฟล์ word ด้วยภาษา python

ตอบกระทู้

รูปแสดงอารมณ์
:icon_plusone: :like: :plusone: :gfb: :-D :) :( :-o 8O :? 8) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :wink: :!: :?: :idea: :arrow: :| :mrgreen: :angry: :baa: :biggrin:
รูปแสดงอารมณ์อื่นๆ

BBCode เปิด
[img] เปิด
[url] เปิด
[Smile icon] เปิด

กระทู้แนะนำ
   

มุมมองที่ขยายได้ กระทู้แนะนำ: การสร้างไฟล์ word ด้วยภาษา python

การสร้างไฟล์ word ด้วยภาษา python

โดย kritsadak » 24/12/2018 6:41 pm

ในบทความนี้ มาเรียนรู้การเขียนภาษา python โดยการสร้างไฟล์ word ขึ้นมา พร้อมกับใส่ข้อมูลหรือเนื้อหาลงไป

ทำกาติดตั้ง library docx ซึ่งจะมีคำสั่งติดตั้ง python-docx ดังนี้

โค้ด: เลือกทั้งหมด

pip3 install python-docx
มักจะใช้กับ python3 **หาก error เกี่ยวกับ version ให้ใช้ (pip3 install --pre python-docx) แทน

โค้ด: เลือกทั้งหมด

from docx import Document				# Library ของ docx ที่ใช้
from docx.shared import Inches, Cm			# Library ของ docx เป็นหน่วยนิ้ว และเซนติเมตร
from docx.shared import Pt
document = Document()
name = "Yourname Lastname"				# สร้างชื่อตัวแปรในรูปแบบ String
print ("create WORD.....")
FIRSTLINE = document.add_paragraph(name)		# โค้ดส่วนของการเพิ่มข้อมูลลงใน word
paragraph_format = FIRSTLINE.paragraph_format	
FIRSTLINE.style = 'Heading 2'				# สร้าง style(รูปแบบตัวอักษร) ให้กับข้อมูล
filename = ('word.docx') 				# ชื่อไฟล์ที่ต้องการจะบันทึก
filepath = r'C:/Users/ksdkd/Desktop/'+filename		# ที่อยู่ของไฟล์ที่ต้องการจะบันทึก
document.save(filepath)				# บันทึกไฟล์ word

ข้างบน