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>
相关推荐
统计学小王子28 分钟前
数学建模国赛倒计时5天——《软件工具(Excel)——快捷键总结》
数学建模·excel
2601_9639067841 分钟前
网页版 Excel 合并工具
excel·软件需求
疯狂小猫咪8 小时前
中小培训机构教务数字化踩坑复盘|从 Excel 过渡到教务系统经验总结
小程序·excel
开开心心_Every15 小时前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel
智途 Tech19 小时前
2026年分析多个Excel、CSV和网页数据的AI工具清单:Tabbit 浏览器多源引用
大数据·人工智能·excel
ltqvibe21 小时前
AI问数、找IT取数、自己导Excel,三条路怎么选
人工智能·excel·数据报表·智能问数·ai问数·本体语义·取数
ZnS_oscar21 小时前
不用下载字体,获得仿宋字体
windows·word
ISBN图书1 天前
ISBN 批量查询怎么做?用 Excel 一次补全书名、作者和出版社信息
excel·isbn·图书数据
Irene19911 天前
获取 Excel 填充色的十六进制颜色值:取色器 + 手动转 RGB
excel·wps
SunnyDays10111 天前
如何使用 Python 从 Word 文档中提取图片
python·word