用 AI 进行“多格式转换”拯救数据搬运:订单数据处理实战 参与“微生产力革命”
在数据运营和数据库管理工作中,我们经常会接触到订单数据。 这些数据可能以 JSON 格式从 API 导出,需要转换成 Excel 分析报表,或者生成 SQL 插入语句写入数据库。
如果用传统方法,要么写 Python 脚本,要么用 Excel + 正则去处理,既耗时又容易出错。 而现在,有了 AI 大语言模型(如 豆包 ,deepseek),几分钟就能完成。
文章目录
- 用 AI 进行“多格式转换”拯救数据搬运:订单数据处理实战 参与“微生产力革命”
-
- 场景:订单 JSON 转 Excel 报表给 运营 ,打造用个实用的网站,导出 excel
- Prompt 示例
- AI 输出
- 结果
-
- 1. 解析 JSON 数据
- 2. 数据扁平化(Flatten Data)
- 3. 构建 DataFrame(使用 Pandas)
- 4. 导出 Excel 文件
- 打造一个简单的网站
-
- 给到提示词
- 交给 trae cn 自动生成
- 展示部分代码 app.py
- 展示部分代码 index.html
- 如果出现不兼容的情况
- 结果
- 最后readme.md JSON订单数据处理
-
- 项目概述
- 功能特点
- 技术栈
- 项目结构
- 安装步骤
- 使用方法
- 示例数据
- 注意事项
- 常见问题
- 价值总结
场景:订单 JSON 转 Excel 报表给 运营 ,打造用个实用的网站,导出 excel
传统做法? 写 Python 脚本、用 Excel+正则处理,甚至手动复制粘贴。 —— 这些方法不仅耗时,而且极容易出错。
现在的做法? 借助 AI 大语言模型(如 豆包、DeepSeek,trae ),几分钟就能完成从“JSON → Excel”乃至“自动化网站处理和编写代码 ”的全流程。
假设我们有这样一份订单 JSON 数据(部分展示):
[
{
"order_id": "SO20250809001",
"customer": {"name": "张三", "phone": "13800000001"},
"items": [
{"product": "iPhone 15 Pro", "price": 8999, "qty": 1},
{"product": "AirPods Pro 2", "price": 1899, "qty": 1}
],
"total": 10898,
"order_date": "2025-08-08"
},
{
"order_id": "SO20250809002",
"customer": {"name": "李四", "phone": "13800000002"},
"items": [
{"product": "MacBook Air M3", "price": 9999, "qty": 1}
],
"total": 9999,
"order_date": "2025-08-08"
}
]
Prompt 示例
请将以下订单 JSON 转换为 Excel 表格格式,列顺序为:
订单号、客户姓名、手机号、商品名称、单价、数量、订单总金额、下单日期。
如果一笔订单包含多个商品,请在 Excel 中拆成多行。
AI 输出
结果
然后选择复制
他是执行步骤如下
1. 解析 JSON 数据
读取 JSON 数据,将其转换为 Python 可操作的对象(如 list 或 dict)。 检查 JSON 结构,确保 order_id、customer、items、total、order_date 等字段正确。
2. 数据扁平化(Flatten Data)
由于一个订单可能包含多个商品(items 数组),需要拆分成多行: 遍历每个订单(order)。 对于每个订单,遍历其 items 列表,为每个商品创建一行记录。 每行记录包含: 订单信息(order_id、customer、total、order_date)。 商品信息(product、price、qty)。
3. 构建 DataFrame(使用 Pandas)
使用 pandas.DataFrame 存储数据,便于导出 Excel。 列顺序按需求排列: 订单号、客户姓名、手机号、商品名称、单价、数量、订单总金额、下单日期。
4. 导出 Excel 文件
使用 pandas.to_excel() 方法,将 DataFrame 保存为 .xlsx 文件。 可调整格式(如列宽、表头样式)以优化可读性。
打造一个简单的网站
我们 用字节 trae ,已经安装 python, 听说阿里人 ,60%都用 ai 写代码了。
给到提示词
写一个 python web 程序
程序名称JOSN订单数据处理
主要功能 复制 订单的json 格式,然后在页面导出 excel 文件
需要有个功能点 1.json 格式检查按钮,如果格式正确就 导入excel
json 代码如下
[
{
"order_id": "SO20250809001",
"customer": {"name": "张三", "phone": "13800000001"},
"items": [
{"product": "iPhone 15 Pro", "price": 8999, "qty": 1},
{"product": "AirPods Pro 2", "price": 1899, "qty": 1}
],
"total": 10898,
"order_date": "2025-08-08"
},
{
"order_id": "SO20250809002",
"customer": {"name": "李四", "phone": "13800000002"},
"items": [
{"product": "MacBook Air M3", "price": 9999, "qty": 1}
],
"total": 9999,
"order_date": "2025-08-08"
}
]
执行步骤如下
### 1. 解析 JSON 数据
读取 JSON 数据,将其转换为 Python 可操作的对象(如 list 或 dict)。
检查 JSON 结构,确保 order_id、customer、items、total、order_date 等字段正确。
### 2. 数据扁平化(Flatten Data)
由于一个订单可能包含多个商品(items 数组),需要拆分成多行:
遍历每个订单(order)。
对于每个订单,遍历其 items 列表,为每个商品创建一行记录。
每行记录包含:
订单信息(order_id、customer、total、order_date)。
商品信息(product、price、qty)。
### 3. 构建 DataFrame(使用 Pandas)
使用 pandas.DataFrame 存储数据,便于导出 Excel。
列顺序按需求排列:
订单号、客户姓名、手机号、商品名称、单价、数量、订单总金额、下单日期。
### 4. 导出 Excel 文件
使用 pandas.to_excel() 方法,将 DataFrame 保存为 .xlsx 文件。
可调整格式(如列宽、表头样式)以优化可读性。
### 5. 完成后请测试一下 ,并优化用户体验。
创建项目目录 , d:\\python\\ json_tr
交给 trae cn 自动生成
生成 requirements.txt
Flask==2.3.3
pandas==2.1.0
openpyxl==3.1.2
展示部分代码 app.py
rom flask import Flask, render_template, request, jsonify, send_file
import json
import pandas as pd
from io import BytesIO
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/validate_json', methods=['POST'])
def validate_json():
try:
data = request.json.get('json_data')
if not data:
return jsonify({'status': 'error', 'message': '请输入JSON数据'})
# 尝试解析JSON
json_obj = json.loads(data)
# 检查JSON结构
if not isinstance(json_obj, list):
return jsonify({'status': 'error', 'message': 'JSON必须是数组格式'})
required_fields = ['order_id', 'customer', 'items', 'total', 'order_date']
for idx, order in enumerate(json_obj):
if not isinstance(order, dict):
return jsonify({'status': 'error', 'message': f'第{idx+1}个订单不是对象格式'})
for field in required_fields:
if field not in order:
return jsonify({'status': 'error', 'message': f'第{idx+1}个订单缺少必要字段: {field}'})
# 检查customer结构
if not isinstance(order['customer'], dict) or 'name' not in order['customer'] or 'phone' not in order['customer']:
return jsonify({'status': 'error', 'message': f'第{idx+1}个订单的customer字段格式不正确'})
# 检查items结构
if not isinstance(order['items'], list):
return jsonify({'status': 'error', 'message': f'第{idx+1}个订单的items必须是数组'})
for item_idx, item in enumerate(order['items']):
if not isinstance(item, dict) or 'product' not in item or 'price' not in item or 'qty' not in item:
return jsonify({'status': 'error', 'message': f'第{idx+1}个订单的第{item_idx+1}个商品格式不正确'})
return jsonify({'status': 'success', 'message': 'JSON格式正确'})
except json.JSONDecodeError as e:
return jsonify({'status': 'error', 'message': f'JSON解析错误: {str(e)}'})
except Exception as e:
return jsonify({'status': 'error', 'message': f'发生错误: {str(e)}'})
@app.route('/export_excel', methods=['POST'])
def export_excel():
try:
data = request.json.get('json_data')
json_obj = json.loads(data)
# 数据扁平化
flattened_data = []
for order in json_obj:
order_id = order['order_id']
customer_name = order['customer']['name']
customer_phone = order['customer']['phone']
total = order['total']
order_date = order['order_date']
for item in order['items']:
product = item['product']
price = item['price']
qty = item['qty']
flattened_data.append({
'订单号': order_id,
'客户姓名': customer_name,
'手机号': customer_phone,
'商品名称': product,
'单价': price,
'数量': qty,
'订单总金额': total,
'下单日期': order_date
})
# 构建DataFrame
df = pd.DataFrame(flattened_data)
# 导出Excel
output = BytesIO()
with pd.ExcelWriter(output, engine='openpyxl') as writer:
df.to_excel(writer, index=False, sheet_name='订单数据')
# 优化格式
worksheet = writer.sheets['订单数据']
for column_cells in worksheet.columns:
length = max(len(str(cell.value)) for cell in column_cells)
worksheet.column_dimensions[column_cells[0].column_letter].width = length + 2
output.seek(0)
return send_file(output, as_attachment=True, download_name='订单数据.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
except Exception as e:
return jsonify({'status': 'error', 'message': f'导出Excel失败: {str(e)}'})
if __name__ == '__main__':
app.run(debug=True)
展示部分代码 index.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON订单数据处理</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<div class="container">
<h1>JSON订单数据处理</h1>
<div class="input-section">
<label for="json-input">请输入订单JSON数据:</label>
<textarea id="json-input" placeholder='[
{
"order_id": "SO20250809001",
"customer": {"name": "张三", "phone": "13800000001"},
"items": [
{"product": "iPhone 15 Pro", "price": 8999, "qty": 1},
{"product": "AirPods Pro 2", "price": 1899, "qty": 1}
],
"total": 10898,
"order_date": "2025-08-08"
}
]'></textarea>
<div class="buttons">
<button id="validate-btn">检查JSON格式</button>
<button id="export-btn" disabled>导出Excel</button>
</div>
<div id="message" class="message"></div>
</div>
</div>
<script>
document.getElementById('validate-btn').addEventListener('click', function() {
const jsonInput = document.getElementById('json-input').value;
const messageEl = document.getElementById('message');
const exportBtn = document.getElementById('export-btn');
if (!jsonInput.trim()) {
messageEl.textContent = '请输入JSON数据';
messageEl.className = 'message error';
exportBtn.disabled = true;
return;
}
fetch('/validate_json', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({json_data: jsonInput})
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
messageEl.textContent = data.message;
messageEl.className = 'message success';
exportBtn.disabled = false;
} else {
messageEl.textContent = data.message;
messageEl.className = 'message error';
exportBtn.disabled = true;
}
})
.catch(error => {
messageEl.textContent = '请求失败: ' + error;
messageEl.className = 'message error';
exportBtn.disabled = true;
});
});
document.getElementById('export-btn').addEventListener('click', function() {
const jsonInput = document.getElementById('json-input').value;
const messageEl = document.getElementById('message');
fetch('/export_excel', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({json_data: jsonInput})
})
.then(response => {
if (!response.ok) {
return response.json().then(data => {
throw new Error(data.message || '导出失败');
});
}
return response.blob();
})
.then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = '订单数据.xlsx';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
messageEl.textContent = 'Excel导出成功';
messageEl.className = 'message success';
})
.catch(error => {
messageEl.textContent = '导出失败: ' + error.message;
messageEl.className = 'message error';
});
});
</script>
</body>
</html>
如果出现不兼容的情况
执行下面代码
结果
导出后的格式
最后readme.md JSON订单数据处理
项目概述
这是一个基于Flask的Python Web应用,用于处理JSON格式的订单数据并导出为Excel文件。应用提供了JSON格式验证、数据扁平化和Excel导出功能,方便用户快速处理和分析订单数据。
功能特点
- JSON格式验证:检查输入的JSON数据是否合法
- 数据扁平化:将嵌套的JSON数据结构扁平化为表格形式
- Excel导出:将处理后的数据导出为Excel文件
- 友好的Web界面:简单直观的用户界面,易于操作
技术栈
- 后端:Python 3.8+, Flask
- 数据处理:Pandas, NumPy
- 前端:HTML, CSS, JavaScript
项目结构
d:\\python\\json_tr\\
├── app.py # 主应用文件
├── templates\\ # HTML模板
│ └── index.html # 主页面
├── static\\ # 静态文件
│ └── style.css # 样式表
├── requirements.txt # 依赖包列表
└── README.md # 项目说明文档
安装步骤
克隆或下载项目到本地
切换到项目目录: cd d:\\python\\json_tr
创建并激活虚拟环境(可选但推荐):python -m venv venv
.\\venv\\Scripts\\activate
安装依赖包: pip install -r requirements.txt
使用方法
运行应用: python app.py
在浏览器中访问: http://127.0.0.1:5000
在文本框中输入JSON格式的订单数据
点击"检查JSON格式"按钮验证数据
验证通过后,点击"导出Excel"按钮下载Excel文件
示例数据
[
{
"order_id": "SO20250809001",
"customer": {"name": "张三", "phone":
"13800000001"},
"items": [
{"product": "iPhone 15 Pro", "price": 8999,
"qty": 1},
{"product": "AirPods Pro 2", "price": 1899,
"qty": 1}
],
"total": 10898,
"order_date": "2025-08-08"
}
]
注意事项
- 确保Python版本为3.8或更高
- 如遇到依赖兼容性问题(如numpy和pandas版本不兼容),请尝试升级或安装特定版本
- 调试模式下,修改代码后应用会自动重启
常见问题
运行应用时提示缺少依赖包? 请确保已安装所有依赖: pip install -r requirements.txt
Excel导出失败? 请检查输入的JSON格式是否正确,确保数据结构符合要求
Python环境变量问题? 确保Python已添加到系统环境变量,或使用绝对路径运行Python 如果您需要其他特定内容的复制,请明确说明具体是哪部分内容(如代码文件、错误信息等),我会尽力帮您获取。
价值总结
节省时间:几分钟搞定以前要半天的工作 减少错误:格式校验 + 自动化处理 降低门槛:运营同事也能直接使用 微生产力革命:从“手动搬运”到“一键转换” 一句话:AI 不是取代你,而是帮你用更短的时间,做更高价值的事。
评论前必须登录!
注册