jmcnamara / rust_xlsxwriter

A Rust library for creating Excel XLSX files.
https://crates.io/crates/rust_xlsxwriter
Apache License 2.0
250 stars 23 forks source link

Bug: `Result<T, E>` serialization not working #74

Closed lucatrv closed 6 months ago

lucatrv commented 6 months ago

Current behavior

The attached code reproduces this issue, only the headers are saved to the xlsx file while all fields are empty.

This issue was initially reported here.

Expected behavior

The saved xlsx file should contain two rows with values underneath the headers row.

Sample code to reproduce

use rust_xlsxwriter::{Format, FormatBorder, Workbook, XlsxError};
use serde::{Serialize, Deserialize};

fn main() -> Result<(), XlsxError> {
    let mut workbook = Workbook::new();

    // Add a worksheet to the workbook.
    let worksheet = workbook.add_worksheet();

    // Add some formats to use with the serialization data.
    let header_format = Format::new()
        .set_bold()
        .set_border(FormatBorder::Thin)
        .set_background_color("C6E0B4");

    // Create a serializable struct.
    #[derive(Deserialize, Serialize)]
    #[serde(rename_all = "PascalCase")]
    struct Student<'a> {
        name: &'a str,
        age: Result<f64, String>,
        id: Result<f64, String>,
    }

    let students = [
        Student {
            name: "Aoife",
            age: Ok(1.0),
            id: Err(String::from("564351")),
        },
        Student {
            name: "Caoimhe",
            age: Err(String::new()),
            id: Ok(443287.0),
        },
    ];

    // Set up the start location and headers of the data to be serialized.
    worksheet.deserialize_headers_with_format::<Student>(1, 3, &header_format)?;

    // Serialize the data.
    worksheet.serialize(&students)?;

    // Save the file.
    workbook.save("serialize.xlsx")?;

    Ok(())
}


### Environment

- `rust_xlsxwriter` version: 0.61.0

### Any other information

_No response_
jmcnamara commented 6 months ago

Fixed on main with a test. Here is the output from your sample program with the fix:

screenshot

The green triangle is a standard Excel warning about a number stored as text.