pub struct ExcelWriter<W>
where W: Write,
{ /* private fields */ }
Expand description

ExcelWriter implements the Polars [SerWriter] trait to serialize a dataframe to an Excel Xlsx file.

ExcelWriter provides a simple interface for writing to an Excel file similar to Polars [CsvWriter].

For a more configurable dataframe to Excel serializer see PolarsXlsxWriter which is also part of this crate.

ExcelWriter uses PolarsXlsxWriter to do the Excel serialization which in turn uses the rust_xlsxwriter crate.

§Examples

An example of writing a Polar Rust dataframe to an Excel file.

use polars::prelude::*;
use chrono::prelude::*;

fn main() {
    // Create a sample dataframe for the example.
    let mut df: DataFrame = df!(
        "String" => &["North", "South", "East", "West"],
        "Integer" => &[1, 2, 3, 4],
        "Float" => &[4.0, 5.0, 6.0, 7.0],
        "Time" => &[
            NaiveTime::from_hms_milli_opt(2, 59, 3, 456).unwrap(),
            NaiveTime::from_hms_milli_opt(2, 59, 3, 456).unwrap(),
            NaiveTime::from_hms_milli_opt(2, 59, 3, 456).unwrap(),
            NaiveTime::from_hms_milli_opt(2, 59, 3, 456).unwrap(),
            ],
        "Date" => &[
            NaiveDate::from_ymd_opt(2022, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap(),
            NaiveDate::from_ymd_opt(2022, 1, 3).unwrap(),
            NaiveDate::from_ymd_opt(2022, 1, 4).unwrap(),
            ],
        "Datetime" => &[
            NaiveDate::from_ymd_opt(2022, 1, 1).unwrap().and_hms_opt(1, 0, 0).unwrap(),
            NaiveDate::from_ymd_opt(2022, 1, 2).unwrap().and_hms_opt(2, 0, 0).unwrap(),
            NaiveDate::from_ymd_opt(2022, 1, 3).unwrap().and_hms_opt(3, 0, 0).unwrap(),
            NaiveDate::from_ymd_opt(2022, 1, 4).unwrap().and_hms_opt(4, 0, 0).unwrap(),
        ],
    )
    .unwrap();

    example(&mut df).unwrap();
}

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .finish(df)
}

Output file:

Implementations§

source§

impl<W> ExcelWriter<W>
where W: Write,

source

pub fn has_header(self, has_header: bool) -> Self

Turn on/off the dataframe header in the exported Excel file.

Turn on/off the dataframe header row in the Excel table. It is on by default.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This demonstrates saving the dataframe with a header (which is the default).

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .has_header(true)
        .finish(df)
}

Output file:

If we set has_header() to false we can output the dataframe from the previous example without the header row:

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .has_header(false)
        .finish(df)
}

Output file:

source

pub fn with_time_format(self, format: impl Into<Format>) -> Self

Set the Excel number format for time values.

Datetimes in Excel are stored as f64 floats with a format used to display them. The default time format used by this library is hh:mm:ss;@. This method can be used to specify an alternative user defined format.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This example demonstrates how to change the default format for Polars time types.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_time_format("hh:mm")
        .finish(df)
}

Output file:

source

pub fn with_date_format(self, format: impl Into<Format>) -> Self

Set the Excel number format for date values.

Datetimes in Excel are stored as f64 floats with a format used to display them. The default date format used by this library is yyyy-mm-dd;@. This method can be used to specify an alternative user defined format.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This example demonstrates how to change the default format for Polars date types.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_date_format("mmm d yyyy")
        .finish(df)
}

Output file:

source

pub fn with_datetime_format(self, format: impl Into<Format>) -> Self

Set the Excel number format for datetime values.

Datetimes in Excel are stored as f64 floats with a format used to display them. The default datetime format used by this library is yyyy-mm-dd hh:mm:ss. This method can be used to specify an alternative user defined format.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This example demonstrates how to change the default format for Polars datetime types.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_datetime_format("hh::mm - mmm d yyyy")
        .finish(df)
}

Output file:

source

pub fn with_float_format(self, format: impl Into<Format>) -> Self

Set the Excel number format for floats.

Set the Excel number format for f32/f64 float types using an Excel number format string. These format strings can be obtained from the Format Cells -> Number dialog in Excel.

See the Number Format Categories section and subsequent Number Format sections in the rust_xlsxwriter documentation.

Note, the numeric values aren’t truncated in Excel, this option just controls the display of the number.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This demonstrates setting an Excel number format for floats.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_float_format("#,##0.00")
        .finish(df)
}

Output file:

source

pub fn with_float_precision(self, precision: usize) -> Self

Set the Excel number precision for floats.

Set the number precision of all floats exported from the dataframe to Excel. The precision is converted to an Excel number format (see with_float_format() above), so for example 3 is converted to the Excel format 0.000.

The precision should be in the Excel range 1-30.

Note, the numeric values aren’t truncated in Excel, this option just controls the display of the number.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This example demonstrates how to set the precision of the float output. Setting the precision to 3 is equivalent to an Excel number format of 0.000.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_float_precision(3)
        .finish(df)
}

Output file:

source

pub fn with_null_value(self, null_value: impl Into<String>) -> Self

Replace Null values in the exported dataframe with string values.

By default Null values in a dataframe aren’t exported to Excel and will appear as empty cells. If you wish you can specify a string such as “Null”, “NULL” or “N/A” as an alternative.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This demonstrates setting a value for Null values in the dataframe. The default is to write them as blank cells.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_null_value("Null")
        .finish(df)
}

Output file:

source

pub fn with_autofit(self) -> Self

Simulate autofit for columns in the dataframe output.

Use a simulated autofit to adjust dataframe columns to the maximum string or number widths.

There are several limitations to this autofit method, see the rust_xlsxwriter docs on worksheet.autofit() for details.

§Examples

An example of writing a Polar Rust dataframe to an Excel file. This example demonstrates autofitting column widths in the output worksheet.

use polars_excel_writer::ExcelWriter;

fn example(df: &mut DataFrame) -> PolarsResult<()> {
    let mut file = std::fs::File::create("dataframe.xlsx").unwrap();

    ExcelWriter::new(&mut file)
        .with_autofit()
        .finish(df)
}

Output file:

Trait Implementations§

source§

impl<W> SerWriter<W> for ExcelWriter<W>
where W: Write + Seek + Send,

source§

fn new(buffer: W) -> Self

source§

fn finish(&mut self, df: &mut DataFrame) -> PolarsResult<()>

Auto Trait Implementations§

§

impl<W> !RefUnwindSafe for ExcelWriter<W>

§

impl<W> Send for ExcelWriter<W>
where W: Send,

§

impl<W> !Sync for ExcelWriter<W>

§

impl<W> Unpin for ExcelWriter<W>
where W: Unpin,

§

impl<W> !UnwindSafe for ExcelWriter<W>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V