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>
相关推荐
赵广陆19 小时前
Jupyter和PyCharm完整集成
ide·jupyter·pycharm
xiaopai94521 小时前
工程项目管理系统选型:WPS/Excel为何难以替代专业系统的数据关联逻辑
excel·wps·项目管理系统·建米软件
灵析表格1 天前
Excel连接MySQL的函数化革命:灵析表格MySQL函数族业务应用分析
数据库·mysql·adb·excel·wps·灵析表格·excel公式盒子
许彰午1 天前
在PowerBuilder里手写Excel导出——OLE控制Excel的完整方案
excel
admin0052 天前
进销存软件与Excel的边界:什么时候该从Excel升级到专业软件
excel·企业管理·财务管理·进销存管理
Ai-_Man2 天前
豆包智能体内容批量导出:哪些该存、存成什么、怎么存v
人工智能·ai·小程序·word
灵析表格2 天前
json_ObjectToKV 函数深度研究报告
json·excel·wps·灵析表格·excel公式盒子
二进制杯莫停2 天前
Pycharm直接使用uv管理项目
ide·pycharm·uv
weixin_416660072 天前
解决方案:DeepSeek不支持直接导出Word
word
观远数据2 天前
Excel、自研、还是换BI?产品VP拆解三条数据分析路线的隐性成本
大数据·数据分析·excel