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>
相关推荐
进阶的猿猴3 小时前
easyExcel实现单元格合并
java·excel
黄色茶杯5 小时前
解决WPS的word文件嵌入EXCEL无法双击打开
word·excel·wps
艾莉丝努力练剑8 小时前
【自动化测试实战篇】Web自动化测试实战:从用例编写到报告生成
前端·人工智能·爬虫·python·pycharm·自动化·测试
gc_229915 小时前
学习C#调用OpenXml操作word文档的基本用法(7:Style类分析-5)
学习·word·openxml
YDS82917 小时前
苍穹外卖 —— 数据统计和使用Apache_POI库导出Excel报表
java·spring boot·后端·excel
云和数据.ChenGuang21 小时前
pycharm怎么将背景换成白色
ide·python·pycharm
achi01021 小时前
Ubuntu 24.04 一站式 Flask 生产部署:pyenv + PyCharm + Gunicorn + Nginx + systemd
pycharm·flask·systemd·gunicorn·pyenv·ubuntu 24.04·生产部署
办公解码器1 天前
Excel工作表打开一次后自动销毁文件,回收站中都找不到
数据库·excel
mudtools1 天前
.NET驾驭Excel之力:工作簿与工作表操作基础
c#·.net·excel
mudtools1 天前
.NET驾驭Excel之力:单元格与区域操作详解
c#·.net·excel