下载需要的依赖包
pip install openpyxl python-docx flask
main.py文件
from flask import Flask, request, render_template
from openpyxl import load_workbook
from docx import Documentapp = 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.activeexcel_data = [list(row) for row in sheet.iter_rows(values_only=True)]return excel_datadef 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().cellsfor 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文件
<!-- 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>