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>
相关推荐
缺点内向21 分钟前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
徐小夕@趣谈前端3 小时前
拒绝重复造轮子?我们偏偏花365天,用Vue3写了款AI协同的Word编辑器
人工智能·编辑器·word
kingwebo'sZone5 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
科技D人生8 小时前
Vue.js 学习总结(20)—— Vue-Office 实战:word、pdf、excel、ppt 多种文档的在线预览
vue.js·word·vue-pdf·stylesheet·docx-preview·vue-office
寻梦csdn1 天前
pycharm+miniconda兼容问题
ide·python·pycharm·conda
weixin_416660071 天前
技术分析:豆包生成带公式文案导出Word乱码的底层机理
人工智能·word·豆包
骆驼爱记录1 天前
Word样式库不显示的8种修复方法
word·wps·新人首发
苍煜1 天前
超简单 poi-tl 学习博客:从0到1掌握Word生成(无需模板+模板填充)
学习·word
请为小H留灯1 天前
Word论文 封面、目录、页码设置步骤!(2026详细版教程)
毕业设计·word·论文格式
JMchen1231 天前
AI编程范式转移:深度解析人机协同编码的实战进阶与未来架构
人工智能·经验分享·python·深度学习·架构·pycharm·ai编程