pycharm实现上传excel生成word

下载需要的依赖包

python 复制代码
pip install openpyxl python-docx flask

main.py文件

python 复制代码
from flask import Flask, request, render_template
from openpyxl import load_workbook
from docx import Document

app = Flask(__name__, template_folder='templates')


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/upload', methods=['POST'])
def upload():
    if 'file' not in request.files:
        return "No file part"

    file = request.files['file']

    if file.filename == '':
        return "No selected file"

    if file:
        excel_data = read_excel(file)
        generate_word(excel_data)
        return "Word file generated successfully"


def read_excel(file):
    workbook = load_workbook(file)
    sheet = workbook.active
    excel_data = [list(row) for row in sheet.iter_rows(values_only=True)]
    return excel_data


def generate_word(excel_data):
    document = Document()

    table = document.add_table(rows=1, cols=len(excel_data[0]))
    for i, header in enumerate(excel_data[0]):
        table.cell(0, i).text = str(header)

    for row_data in excel_data[1:]:
        row_cells = table.add_row().cells
        for i, cell_value in enumerate(row_data):
            row_cells[i].text = str(cell_value)

    document.save('output.docx')


if __name__ == '__main__':
    app.run(debug=True)

template文件夹下index.html文件

python 复制代码
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel to Word</title>
</head>
<body>
    <form method="POST" enctype="multipart/form-data" action="/upload">
        <input type="file" name="file" accept=".xlsx, .xls">
        <button type="submit">Generate Word</button>
    </form>
</body>
</html>
相关推荐
Q_Q51100828517 小时前
python+django/flask+vue农业电商服务系统
spring boot·python·pycharm·django·flask
thinkpad123456789018 小时前
ubuntu22.04+miniconda+ros2的坑(1)
pycharm·anaconda·ros2
来鸟 鸣间18 小时前
excel快速填充
excel
葡萄城技术团队21 小时前
Excel 文件到底是怎么坏掉的?深入 OOXML 底层原理讲解修复策略
android·java·excel
程序边界1 天前
AI实战狂飙!Excel图表制作彻底解放双手:从数据清洗到智能预测全攻略
人工智能·excel
唐古乌梁海1 天前
【PyCharm】PyCharm 常用技巧与快捷键总结
ide·python·pycharm
CodeCraft Studio1 天前
Excel处理控件Aspose.Cells教程:使用C#在Excel中创建漏斗图
ui·c#·excel·aspose·excel开发·excel漏斗图·漏斗图
secondyoung1 天前
WPS宏使用:一键批量调整图片与表格格式
经验分享·word·lua·markdown·wps·vb
wtsolutions1 天前
WPS另存为JSON,WPS导出JSON, WPS表格转换成JSON : Excel to JSON WPS插件使用指南
json·excel·wps·插件·加载项·wtsolutions
m5655bj1 天前
Python 将 Word 文档转换为 Markdown 格式
python·c#·word