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 小时前
胖喵必快 (pmbs): btrfs 自动快照工具 (每分钟快照)
linux·rust
ljf88382 小时前
Java导出复杂excel,自定义excel导出
java·开发语言·excel
tebukaopu1483 小时前
json文件转excel
json·excel
shizidushu3 小时前
How to work with merged cells in Excel with `openpyxl` in Python?
python·microsoft·excel·openpyxl
钢门狂鸭9 小时前
关于rust的crates.io
开发语言·后端·rust
编码浪子9 小时前
趣味学RUST基础篇(异步)
服务器·rust·负载均衡
勇敢牛牛_14 小时前
使用Rust实现服务配置/注册中心
开发语言·后端·rust·注册中心·配置中心
浪费笔墨17 小时前
Rail开发日志_9
rust
Eiceblue1 天前
使用 C# 设置 Excel 单元格格式
开发语言·后端·c#·.net·excel
小孔龙1 天前
01.Kotlin Serialization - 基础用法
kotlin·json