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>
相关推荐
沟通QQ:48773927813 分钟前
Apollo之em - planner算法深度剖析:从路径规划到公式推导
pycharm
Aries·Zhao15 小时前
Python小白学习之环境安装
python·pycharm·visual studio code
q***547518 小时前
解决no main manifest attribute错误
ide·python·pycharm
癫狂的兔子20 小时前
【Office】【Excel】常用函数公式总结
excel
星川皆无恙20 小时前
大数据爬虫可视化分析:基于Python的豆瓣书籍可视化分析系统的设计与实现
大数据·爬虫·python·架构·pycharm·django
艾莉丝努力练剑1 天前
【Python基础:语法第二课】Python 流程控制详解:条件语句 + 循环语句 + 人生重开模拟器实战
人工智能·爬虫·python·pycharm
毛飞龙1 天前
Excel迷你图:在单元格中嵌入趋势洞察
excel·迷你图·sparklines
Tatalaluola1 天前
Unity使用EPPlus读取写入表格
unity·c#·游戏引擎·excel
VBAMatrix1 天前
新一代邮件合并!按Word模板批量生成个性化文档
word·办公自动化·邮件合并·审计·报告工具·批量生成合同
帮帮志1 天前
安装了多个不同版本的pycharm,新安装的pycharm打不开
ide·python·pycharm