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>
相关推荐
brian003111 小时前
word插件,像wps一样双击放大图片
word·wps·双击放大图片
小白今天也很酷12 小时前
MCXN947更新板载DAP_Link固件的方法
c语言·python·单片机·ubuntu·excel·1024程序员节
DFT计算杂谈21 小时前
LaTeX 格式公式复制至 Word 并快捷转换操作
word
weixin_416660071 天前
千问回答转 Word 后,表格和公式是真能编辑,还是看起来像?
word·markdown·千问
ratel️1 天前
小墨析 · Office Agent 日常办公不烧心
python·langchain·word·excel·fastapi·js·ppt
Logic1011 天前
没有TextSplit函数的老版本也能拆分单元格的内容
excel·拆分数据·excel技巧·数据拆分·拆分单元格·textsplit·旧版excel
2601_967987371 天前
你们都用Python实现了哪些自动化办公?
python·excel·自动化办公·1024程序员节·学习资料·跨平台操作
城数派1 天前
1901-2025年中国省/市/县三级逐月平均气温数据Excel+Shp格式
excel
MetaEnchanter1 天前
PDF 转 Word:只改其中几页,不用整份重新整理
pdf·word
qq_366086222 天前
idea项目重新启动时报错找不到jar
pycharm·intellij-idea·jar