informationsea / xlsxwriter-rs

Excel file writer for Rust
https://crates.io/crates/xlsxwriter
Apache License 2.0
266 stars 47 forks source link

Copy or clone format? #12

Open ccclement opened 3 years ago

ccclement commented 3 years ago

Is it possible to copy or clone a format to avoid code repetition?

use xlsxwriter::*;

fn main() -> Result<(), xlsxwriter::XlsxError> {
    let workbook = Workbook::new("test.xlsx");

    let format1 = workbook.add_format()
        .set_font_color(FormatColor::Green)
        .set_align(FormatAlignment::CenterAcross)
        .set_align(FormatAlignment::VerticalCenter);

    let mut format2 = format1.clone();
    format2.set_font_color(FormatColor::Red);
    // OR
    let mut format3 = workbook.add_format();
    format3.copy(&format1);
    format3.set_bg_color(FormatColor::Red);

    // ...
}
jmcnamara commented 1 year ago

This may not be possible to implement since the underlying library creates Format objects via the Workbook object so the interface would have to be something like:

let mut format2 = workbook.clone(format1);

Which unfortunately isn't very Rust like.

2ndDerivative commented 1 year ago

you might be able to implement the actual attachment to the workbook via closure, which would allow Rust to treat it as a separate object. Would require a rewrite of the Format struct though, I think...

jmcnamara commented 1 year ago

Would require a rewrite of the Format struct though, I think...

Probably, and that is unlikely to happen in the C library because the workbook management/coupling design is too tight. Format cloning is supported in the pure Rust version however since I went with a decoupled design to avoid borrow/owner issues.

2ndDerivative commented 1 year ago

I just looked into it more and it seems like Format is getting detached from the workbooks in 0.6 with Format::new()! So our problem is getting solved!

2ndDerivative commented 1 year ago

I had another idea for doing this: We could try implementing Copy/Clone by attaching a Clone of the item directly to the parent workbook with a trait. That would mean not being able to clone it across workbooks tho