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>
相关推荐
询问QQ6882388622 分钟前
深入剖析10/100Mbps 10BASE - T ETHERENT - PHY以太网项目
pycharm
测试人社区-小明1 小时前
AI在金融软件测试中的实践
人工智能·测试工具·金融·pycharm·机器人·github·量子计算
jcsx1 小时前
pycharm下新建一个项目并加入svn
svn·pycharm
YuanYWRS1 小时前
办公基础:实现PDF中表单不改变格式的情况下转成excel
pdf·excel
肖恭伟1 小时前
Pycharm历史community版本下载
linux·ubuntu·pycharm·下载·community
艾莉丝努力练剑2 小时前
【Python基础:语法第五课】Python字典高效使用指南:避开KeyError,掌握遍历与增删改查精髓
大数据·运维·人工智能·python·安全·pycharm
Data_agent3 小时前
Python高效实现Excel与TXT文本文件数据转换指南
开发语言·python·excel
米芝鱼1 天前
Unity读取Excel转换为二进制数据文件与自定义数据读写
游戏·unity·游戏引擎·excel·urp
用户298698530141 天前
如何在 C# 中创建、读取和更新 Excel 文档
后端·c#·excel
艾上编程1 天前
第一章——办公自动化之Excel批量合并工具:Python助力高效办公
开发语言·python·excel