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>
相关推荐
cspttty2 小时前
2026秋招供应链分析师技能栈:SQL、Excel、BI与业务分析
数据库·sql·excel
愚公移山填海2 小时前
【无标题】
笔记·python·学习·pycharm
鲲穹AI种草2 小时前
Word 文稿批量规范化处理,多款 Word 批量处理工具能力客观记录
word·批量处理·页面页脚
2601_9623010115 小时前
Python环境搭建及PyCharm破解使用技巧
python·pycharm·环境搭建·避坑技巧·破解使用
SunnyDays101118 小时前
使用 Python 提取 Word 文档中的表格数据
python·word
2601_9623824321 小时前
pychram for Mac怎么把背景调成黑色 , pycharm怎么调背景颜色(pycharm怎么调背景颜色为白色)
pycharm·配置·设置·黑色主题·背景颜色
weixin_416660071 天前
DeepSeek生成的数学公式怎么导出到Word并保持可编辑?
word·deepseek
寥落半伤感1 天前
在Pycharm中一键迅速安装包及查看虚拟环境中包名的方法
ide·python·pycharm
Zzq_Fighting1 天前
Excel批量匹配数据
excel
蝶恋舞者1 天前
Word 实现「图 X」序号自动递增 和交叉引用
word