人生就是不斷學習,調整與更新持續前進。

Python小程式 excel轉換到word v1

 

使用Mac OS 安裝環境


brew install python3
python3 -m venv myenv

source myenv/bin/activate

pip install openpyxl
pip install python-docx
pip install qrcode pillow

 

excel_to_word.py:


import openpyxl
from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import qrcode
from io import BytesIO

def excel_to_word_with_qrcode(excel_file, word_file):
    workbook = openpyxl.load_workbook(excel_file)
    sheet = workbook.active

    document = Document()

    title = document.add_heading('Excel 資料匯出報告', 0)
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER

    table = document.add_table(rows=1, cols=sheet.max_column)
    table.style = 'Table Grid'

    header_cells = table.rows[0].cells
    for i, cell in enumerate(sheet[1]):
        header_cells[i].text = str(cell.value)

    for row in sheet.iter_rows(min_row=2):
        row_cells = table.add_row().cells

        for i, cell in enumerate(row):
            row_cells[i].text = str(cell.value if cell.value is not None else "")

            if i == len(row) - 1 and "QR Code" in str(sheet[1][i].value):
                qr_data = str(row[0].value) if row[0].value else "Empty"

                qr = qrcode.QRCode(
                    version=1,
                    error_correction=qrcode.constants.ERROR_CORRECT_L,
                    box_size=10,
                    border=4,
                )
                qr.add_data(qr_data)
                qr.make(fit=True)

                img = qr.make_image(fill_color="black", back_color="white")

                buffer = BytesIO()
                img.save(buffer)
                buffer.seek(0)
                
                row_cells[i].text = ""

                p = row_cells[i].add_paragraph()
                run = p.add_run()
                run.add_picture(buffer, width=Inches(1))
                
    if sheet.max_row <= 1:
        document.add_paragraph("示例 QR Code:")
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data("範例數據")
        qr.make(fit=True)

        img = qr.make_image(fill_color="black", back_color="white")

        buffer = BytesIO()
        img.save(buffer)
        buffer.seek(0)

        document.add_picture(buffer, width=Inches(2))

    document.save(word_file)
    print(f"已成功將 {excel_file} 的資料轉換到 {word_file},並添加 QR Code")

if __name__ == "__main__":
    excel_to_word_with_qrcode("python_excel.xlsx", "excel_to_word_with_qrcode.docx")