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>
相关推荐
_清风来叙10 小时前
【软件】Word软件不支持显示emoji表情包如何解决
电脑·word
daphne odera�11 小时前
PyCharm 中 Codex 插件启动失败:unknown variant default 的解决方法
python·chatgpt·pycharm
得闲喝茶14 小时前
跨表数据匹配——VLOOKUP、XLOOKUP
大数据·数据库·笔记·信息可视化·数据分析·excel
CallmeFoureyes17 小时前
使用 C# 提取 Word 文档中的表格数据
开发语言·c#·word
丑小鸭是白天鹅20 小时前
Android 打包jar
android·pycharm·jar
HAPPY酷1 天前
【ROS2】16G 内存笔记本跑 ROS2 仿真?VMware 虚拟机“保姆级”配置指南 (R9 7940HX + RTX 4060)
java·linux·ide·windows·pycharm
AI刀刀2 天前
豆包智能体对话导出后,如何构建长期归档与高效检索体系?
android·人工智能·word·excel·ai导出鸭
Jazz_z2 天前
通过 Java 实现 Word 转 TXT
java·c#·word
ZX0X学习中2 天前
一句话让 AI 生成 Excel 多文件合并工具:码道 CLI 实战
人工智能·excel·ai编程·华为云码道
HAPPY酷2 天前
【ROS2】PyCharm 启动 Gazebo 仿真报错?从配置 Shell 到修复路径的全流程复盘
ide·chrome·pycharm