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>
相关推荐
开开心心就好12 小时前
系统重装前必备的智能驱动备份工具
windows·计算机视觉·计算机外设·excel·模块测试·csdn开发云·威胁分析
向宇it1 天前
php高性能的导出excel读写扩展——xlswriter,比传统的Spreadsheet要快很多
php·excel·xlswriter
yanweijie03171 天前
对比VLOOKUP、XLOOKUP、INDEX+MATCH三大查找函数
excel
Codiggerworld1 天前
Vim的语法:删除、复制、粘贴,像说话一样自然
编辑器·vim·excel
Pentane.1 天前
【数据分析 | 农业项目】蔬菜类商品的自动定价与补货决策 | Tableau & Excel
数据挖掘·数据分析·excel·tableau
Digitally1 天前
如何在Windows、Mac和移动设备上永久删除Word文档
windows·macos·word
happy_baymax1 天前
Simulink 端口自动生成工具 (v2.1)(EXCEL+m语言)
服务器·matlab·excel·simulink
SunnyDays10111 天前
如何使用 C# 高效实现 Excel 与 CSV 的互相转换
c#·excel·csv
热爱生活的五柒2 天前
excel的使用教程
excel
R-sz2 天前
前端直接将页面 HTML 报表导出为 Word 文档,html转word
前端·html·word