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>
相关推荐
2301_803538955 小时前
Java读取Word图片的两种实用方法
java·开发语言·word
gc_22997 小时前
学习C#调用OpenXml操作word文档的基本用法(36:学习特殊符号类-1)
word·openxml·run
SunnyDays10118 小时前
Python操作Excel批注:从基础添加到高级自定义的完整指南
开发语言·python·excel
Eiceblue10 小时前
Python 操作 Excel:数据分组、分类汇总与取消分组全解
开发语言·python·excel
城数派11 小时前
2026年500米分辨率DEM地形数据(全球/全国/分省/分市)
数据库·arcgis·信息可视化·数据分析·excel
SunnyDays101112 小时前
Python 操作 Excel 超链接:添加网页、文件、工作表和图片链接
python·excel
专注VB编程开发20年15 小时前
我制作excel工作簿的选项卡,发给deep seek, 昨天修改了一天
前端·vue.js·excel
m沐沐15 小时前
【机器学习】聚类算法-K-means聚类
人工智能·python·算法·机器学习·pycharm·kmeans·聚类
gc_229916 小时前
学习C#调用OpenXml操作word文档的基本用法(37:学习复杂字段相关类)
word·openxml·复杂字段
请为小H留灯1 天前
IDEA / PyCharm 如何实现“一个项目一个窗口”?多项目并行开发设置
java·pycharm·intellij-idea·实战项目