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>
相关推荐
我叫汪枫1 小时前
Python 办公自动化入门:玩转 Excel 与 Word
python·word·excel
E_ICEBLUE1 小时前
三步完成 Markdown 到 Word/PDF 的转换:Python 教程
python·pdf·word·markdown·格式转换
m0_528489254 小时前
Pycharm修改系统缓存路径(包含config, system, plugins, logs, remote sources等)
ide·python·pycharm·c盘
中医正骨葛大夫4 小时前
一文解决如何在Pycharm中创建cuda深度学习环境?
pytorch·深度学习·pycharm·软件安装·cuda·anaconda·配置环境
Franklin4 小时前
AI Coding 基础实践03 - Trae AI在Pycharm中的使用02 - 读取不了项目的文件问题解决
ide·python·pycharm
帮帮志4 小时前
PyCharm 开发工具 不同的模式
ide·python·pycharm
趙卋傑5 小时前
接口自动化测试
python·pycharm·pytest
缺点内向5 小时前
Java: 在 Excel 中插入、提取或删除文本框
java·开发语言·excel
傻啦嘿哟10 小时前
Python将Excel工作表转换为PDF:从入门到实战
python·pdf·excel
罗政11 小时前
WPS Excel快速进行同表内的单元格差异对比(高亮)
excel·wps