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>
相关推荐
元Y亨H13 小时前
Pandas 解析 Excel 导致的内存溢出(MemoryError)
python·excel
一棵星18 小时前
内网 MySQL 表结构一键导出 Word 文档:直连 + Agent 双模式实战
数据库·mysql·word
姜小二18 小时前
QAxObject实现读写excel
嵌入式硬件·excel
E_ICEBLUE20 小时前
Python 拆分 Excel 文件:使用 Spire.XLS 实现按工作表、行、列和条件拆分
python·excel
蓝创工坊Blue Foundry21 小时前
批量提取图片中的数字:怎样整理成一张可核对的 Excel
python·ai·ocr·excel·paddlepaddle
bug嘛我经常写21 小时前
如何批量删除word文档中存在的无用样式
经验分享·python·word
Am-Chestnuts1 天前
Kimi长回答批量导出Word:DS随心转实践
word
曹牧1 天前
Word:更改列表级别
word
噢,我明白了2 天前
java中Excel的导入和导出(EasyExcel)
java·开发语言·excel
REST_30272 天前
告别Excel孤岛:一款任务链路可视化工具带来的真实改变
大数据·微服务·云计算·编辑器·excel·动态规划