informationsea / xlsxwriter-rs

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

How to create a cell with a time value? #26

Closed manfredlotz closed 1 year ago

manfredlotz commented 2 years ago

I want to create a cell with a time value so that I have for example

In Libreoffice in Format Cells I would see

Creating the format sems easy

    let datetime_format = workbook.add_format()
         .set_num_format("hh:mm");

But I have no idea how to add a cell with a value, say 14:45h.

jmcnamara commented 1 year ago

I want to create a cell with a time value so that I have for example

You need to create a xlsxwriter::DateTime object and set the year/month/day parts to 0. Like this:

use xlsxwriter::{DateTime, Workbook};

fn main() -> Result<(), xlsxwriter::XlsxError> {
    let workbook = Workbook::new("datetime.xlsx");
    let mut worksheet = workbook.add_worksheet(None)?;

    let time_format = workbook.add_format().set_num_format("hh:mm");

    worksheet.write_datetime(
        0,
        0,
        &DateTime::new(0, 0, 0, 17, 00, 0.0),
        Some(&time_format),
    )?;

    workbook.close()
}

Output:

screenshot

manfredlotz commented 1 year ago

Thanks a lot. Working fine.

Only one small thing.

Instead of

let workbook = Workbook::new("datetime.xlsx");

it must be

let workbook = Workbook::new("datetime.xlsx")?;