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_5469372713 小时前
Word _ WPS 通用公文排版助手,支持标题、正文一键规范,发文机关、函线、装订线、公章、页码等常用部件一键解决
word·wps
橙露15 小时前
Python 办公自动化:批量处理 Excel/Word/PPT 实战教程
python·word·excel
开开心心_Every16 小时前
系统清理工具清理缓存日志,启动卸载管理
运维·服务器·网络·数学建模·电脑·excel·抽象代数
开开心心就好2 天前
免费音频转文字工具,绿色版离线多模型可用
人工智能·windows·计算机视觉·计算机外设·ocr·excel·语音识别
fengyehongWorld2 天前
Excel 计算两次请求之间耗费的毫秒数
excel
lpfasd1232 天前
Tauri vs Electron:高质量Word/PDF导出效果深度对比
electron·pdf·word
funnycoffee1232 天前
EXCEL利用REPT显示比例
excel·rept
开开心心就好3 天前
实用系统备份还原,小巧免PE备份快镜像小
windows·计算机视觉·pdf·计算机外设·迭代器模式·excel·桥接模式
骆驼爱记录3 天前
WPS文档标题一键加形状
自动化·word·excel·wps·新人首发
闪电橘子4 天前
Pycharm运行程序报错 Process finished with exit code -1066598273 (0xC06D007F)
ide·python·pycharm·cuda