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>
相关推荐
诸神缄默不语16 小时前
如何用Python处理文件:Word导出PDF & 如何用Python从Word中提取数据:以处理简历为例
python·pdf·word
allbs19 小时前
spring boot项目excel导出功能封装——2.高级导出
spring boot·后端·excel
初九之潜龙勿用20 小时前
C# 操作Word模拟解析HTML标记输出带格式的文本
开发语言·c#·word·office
睿思达DBA_WGX1 天前
使用 Python 的第三方库 xlrd 读取 Excel 文件
python·excel
JCGKS1 天前
Go| excelize的流式迭代器
后端·golang·excel·excelize·流式读取·文件解析
裤裤兔1 天前
利用VBA批处理word 文档,使用宏对docx文件内容进行批量替换
c#·word·.net··vba·office·宏操作
gc_22992 天前
学习C#调用FreeSpire.Doc包将Word转换为html
c#·html·word·freespire.doc
G***T6912 天前
GitGraphQL案例
pycharm·perl·etl
yesyesyoucan2 天前
文本与表格格式转换助手:轻松实现TXT/CSV互转及Excel转CSV的实用工具
科技·程序人生·excel·交互·媒体
我命由我123452 天前
Excel - Excel 找回意外关闭的未保存的文档
学习·职场和发展·excel·求职招聘·职场发展·运维开发·学习方法