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>
相关推荐
昵称暂无123 分钟前
通过 C# 复制 Word 文档、指定段落、指定节
开发语言·c#·word
梦因you而美1 小时前
Python win32com 复制Excel sheet优化:覆盖替换而非删除重建,彻底解决公式报错
python·excel·win32com·python自动化·批量复制sheet表
asdzx673 小时前
使用 C# 将 Excel 转换成高质量 JPG
开发语言·c#·excel
城数派3 小时前
2014-2025年全国监测站点的逐月空气质量数据(15个指标\Excel\Shp格式)
arcgis·信息可视化·数据分析·excel
开开心心就好1 天前
支持自定义名单的实用随机抽签工具
windows·计算机视觉·计算机外设·excel·散列表·启发式算法·csdn开发云
STRUGGLE_xlf1 天前
AI大模型生成表格粘贴到 Word 后出现双线边框的原因与解决方案
word
weixin_416660071 天前
2026 年 AI 对话转 Word 工具分析:Pandoc、Typora、aitoword 怎么选
人工智能·word
李昊哲小课1 天前
Python办公自动化教程 - 第2章 单元格样式魔法 - 让表格变得美观专业
开发语言·python·excel·openpyxl
Cephas、1 天前
Pycharm 使用手册
pycharm