json转excel,读取json文件写入到excel中【rust语言】

一、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" }

相关推荐
柠檬丶抒情1 小时前
Rust no_std 裸机移植:9 条避坑与实战手册
开发语言·mongodb·rust
FAFU_kyp1 小时前
Rust 流程控制学习教程
学习·算法·rust
FAFU_kyp1 小时前
Rust 模式匹配:match 与 if let 详解
开发语言·后端·rust
SY_FC3 小时前
unaipp通过JSON.stringify传值页面JSON.parse转换报错
json
不坑老师3 小时前
小工具显出大才能——不坑盒子为教育数字化转型贡献“新方案”
microsoft·word·excel·ppt·office
骆驼爱记录3 小时前
Python程序打包全攻略
自动化·word·excel·wps·新人首发
GHL2842710905 小时前
用lingma合并俩个excel
ai·excel
小赖同学啊5 小时前
xmind用例通过excel整理方式(注意!!不是通过python解析ximind文件转化成用例)
开发语言·python·excel
wangkeyen6 小时前
如何用excel拟合两元一次函数?
excel
哈哈你是真的厉害7 小时前
React Native 鸿蒙跨平台开发:实现Excel数据表格
react native·excel·harmonyos