帮我写一个具有在线编辑 CSV文件功能,并且有新增数据的功能的web网站
要创建一个可以在线编辑和新增 CSV 文件数据的 Web 应用程序,我们可以使用 Flask 作为开发框架,并结合 Pandas 来处理 CSV 文件的数据操作。下面的示例会展示如何实现一个简单的 Web 应用程序,使用户可以查看、添加和编辑 CSV 文件中的数据。
app.py
from flask import Flask, render_template, request, redirect, url_for
import pandas as pd
app = Flask(__name__)
CSV_FILE = 'data.csv'
@app.route('/')
def index():
df = pd.read_csv(CSV_FILE)
return render_template('index.html', data=df.to_dict(orient='records'))
@app.route('/add', methods=['GET', 'POST'])
def add_entry():
if request.method == 'POST':
name = request.form.get('name')
age = request.form.get('age')
email = request.form.get('email')
df = pd.read_csv(CSV_FILE)
new_row = pd.DataFrame({'Name': [name], 'Age': [age], 'Email': [email]})
df = pd.concat([df, new_row], ignore_index=True)
df.to_csv(CSV_FILE, index=False)
return redirect(url_for('index'))
return render_template('add.html')
@app.route('/edit/<int:index>', methods=['GET', 'POST'])
def edit_entry(index):
df = pd.read_csv(CSV_FILE)
if request.method == 'POST':
df.at[index, 'Name'] = request.form.get('name')
df.at[index, 'Age'] = request.form.get('age')
df.at[index, 'Email'] = request.form.get('email')
df.to_csv(CSV_FILE, index=False)
return redirect(url_for('index'))
entry = df.loc[index].to_dict()
return render_template('edit.html', entry=entry, index=index)
if __name__ == '__main__':
app.run(debug=True)
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSV Editor</title>
</head>
<body>
<h1>CSV Data</h1>
<a href="{{ url_for('add_entry') }}">Add New Entry</a>
<table border="1">
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Actions</th>
</tr>
{% for row in data %}
<tr>
<td>{{ row['Name'] }}</td>
<td>{{ row['Age'] }}</td>
<td>{{ row['Email'] }}</td>
<td><a href="{{ url_for('edit_entry', index=loop.index0) }}">Edit</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
edit.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Entry</title>
</head>
<body>
<h1>Edit Entry</h1>
<form method="POST">
Name: <input type="text" name="name" value="{{ entry['Name'] }}" required><br>
Age: <input type="number" name="age" value="{{ entry['Age'] }}" required><br>
Email: <input type="email" name="email" value="{{ entry['Email'] }}" required><br>
<input type="submit" value="Save">
</form>
<a href="{{ url_for('index') }}">Back to CSV Data</a>
</body>
</html>
add.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Entry</title>
</head>
<body>
<h1>Add New Entry</h1>
<form method="POST">
Name: <input type="text" name="name" required><br>
Age: <input type="number" name="age" required><br>
Email: <input type="email" name="email" required><br>
<input type="submit" value="Add">
</form>
<a href="{{ url_for('index') }}">Back to CSV Data</a>
</body>
</html>
data.csv
Name,Email,Phone,Age
John Doe,john@example.com1,111-222-3333,-1.0
Jane Smith,jane@example.com,222-333-4444,2.0
但是风格1,chaoren399@126.com,,4.0
欢迎来撩 : 汇总all