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>
相关推荐
云只上7 小时前
前端插件使用xlsx-populate,花样配置excel内容,根据坐添加标替换excel内容,修改颜色,合并单元格...。
excel
小哥山水之间8 小时前
在 Python 中操作 Excel 文件
开发语言·python·excel
blog_wanghao9 小时前
C#: 创建Excel文件并在Excel中写入数据库中的数据
数据库·c#·excel
优联前端10 小时前
DeepSeek 接入PyCharm实现AI编程!(支持本地部署DeepSeek及官方DeepSeek接入)
javascript·pycharm·ai编程·前端开发·优联前端·deepseek
Ws_13 小时前
python和pycharm 和Anaconda的关系
开发语言·python·pycharm
Hi~晴天大圣13 小时前
Pycharm中断点使用技巧
ide·python·pycharm
游客52016 小时前
自动化办公|通过xlwings进行excel格式设置
python·自动化·excel
喝西瓜汁的兔叽Yan17 小时前
第三方库XLSX: 前端上传excel文件,并对excel文件内容做校验。
前端·excel·xlsx
lifegoesonwjl21 小时前
Python学习心得Pycharm的程序调试
开发语言·python·pycharm
S-_-Lei1 天前
linux 替换jar包中的文件
ide·python·pycharm