一、rust代码
将json文件写入到 excel中。(保持json :key原始顺序)
rust
use indexmap::IndexMap;
use serde::Deserialize;
use serde_json::{Value, from_str};
use std::error::Error;
use std::io::{self, Write};
use std::path::{Path};
use rust_xlsxwriter::{Workbook, Format, RowNum};
use std::fs;
#[derive(Debug, Deserialize)]
struct DataItem {
#[serde(flatten)]
data: IndexMap<String, Value>,
}
fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().collect();
if args.len() < 3 {
writeln!(io::stderr(), "Usage: {} <json_file> <excel_file>", args[0]).unwrap();
std::process::exit(1);
}
let json_path = &args[1];
let excel_file_path = &args[2];
// 检查输入文件是否存在
if !Path::new(json_path).exists() {
return Err("输入文件不存在".into());
}
// 读取并解析JSON
let json_str = fs::read_to_string(json_path)
.map_err(|e| format!("读取JSON文件失败: {}", e))?;
let data_items: Vec<DataItem> = from_str(&json_str)
.map_err(|e| format!("解析JSON失败: {}", e))?;
// 创建Excel文件
convert_json_to_excel(&data_items, excel_file_path)?;
println!("Excel文件已生成: {}", excel_file_path);
Ok(())
}
fn convert_json_to_excel(data_items: &[DataItem], output_path: &str) -> Result<(), Box<dyn Error>> {
// 创建一个新的工作簿
let mut workbook = Workbook::new();
// 添加一个工作表
let mut sheet = workbook.add_worksheet();
// 创建标题格式
let header_format = Format::new()
.set_bold()
.set_align(rust_xlsxwriter::FormatAlign::Center)
.set_border(rust_xlsxwriter::FormatBorder::Thin);
// 创建数据格式
let mut data_format = Format::new()
.set_border(rust_xlsxwriter::FormatBorder::Thin)
.set_align(rust_xlsxwriter::FormatAlign::Left);
if data_items.is_empty() {
return Err("JSON数组为空".into());
}
// 获取第一个对象的键值对,保持原始顺序
let first_item = &data_items[0];
let ordered_keys: Vec<String> = first_item.data.keys().cloned().collect();
// 写入表头
for (col, key) in ordered_keys.iter().enumerate() {
sheet.write_string_with_format(0, col as u16, key,&header_format)?;
}
// 写入数据
for (row, item) in data_items.iter().enumerate() {
for (col, key) in ordered_keys.iter().enumerate() {
if let Some(value) = item.data.get(key) {
let cell_value = match value {
Value::Null => "null".to_string(),
Value::Bool(b) => b.to_string(),
Value::Number(n) => n.to_string(),
Value::String(s) => s.clone(),
Value::Array(a) => serde_json::to_string(a).unwrap_or_else(|_| "[]".to_string()),
Value::Object(o) => serde_json::to_string(o).unwrap_or_else(|_| "{}".to_string()),
};
sheet.write_string_with_format((row + 1) as u16 as RowNum, col as u16, &cell_value,&data_format)?;
}
}
}
// 调整列宽
for col in 0..ordered_keys.len() {
sheet.set_column_width(col as u16, 20)?;
}
// 保存工作簿
workbook.save(output_path)?;
Ok(())
}
二、json 示例
[
{
"id": 1,
"name": "张三",
"age": 28,
"email": "zhangsan@example.com"
},
{
"id": 2,
"name": "李四",
"age": 34,
"email": "lisi@example.com"
},
{
"id": 3,
"name": "王五",
"age": 22,
"email": "wangwu@example.com"
},
{
"id": 4,
"name": "赵六",
"age": 45,
"email": "zhaoliu@example.com"
},
{
"id": 5,
"name": "孙七",
"age": 31,
"email": "sunqi@example.com"
}
]