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>
相关推荐
珞瑜·3 分钟前
Windows版Word如何启用保存时自动删除个人信息
word
Dylan~~~3 分钟前
Excel MCP Server:用自然语言操控 Excel,开启“对话式电子表格“新时代
excel·ai编程
catoop34 分钟前
Excel 实战技巧:利用 OFFSET 统计 “标识行” 下方的数值总和
excel
chushiyunen1 小时前
pycharm实现skills示例
windows·python·pycharm
DS随心转插件2 小时前
ChatGPT或Gemini如何生成word文档
人工智能·ai·chatgpt·word·deepseek·ds随心转
SHolmes18541 天前
Excel 公式解析:按条件去重计数
excel
用户298698530141 天前
告别手动复制:.NET 将网页数据一键导出为 Excel
后端·html·excel
竹林8181 天前
从零到精通:用 Python openpyxl 批量处理 Excel,彻底告别重复劳动
python·excel
白狐_7981 天前
【疑难杂症】Word 惊现“数字 7 消失术”:特定字体 GBK 编码下的渲染陷阱排查
word
shughui2 天前
Miniconda下载、安装、关联配置 PyCharm(2026最新图文教程)
ide·python·pycharm·miniconda