use rust_xlsxwriter::{cell_range, Chart, ExcelDateTime, Format, Formula, Workbook, XlsxError};
fn main() -> Result<(), XlsxError> {
let expenses = vec![
("Rent", 2000, "2022-09-01"),
("Gas", 200, "2022-09-05"),
("Food", 500, "2022-09-21"),
("Gym", 100, "2022-09-28"),
];
let mut workbook = Workbook::new();
let bold = Format::new().set_bold();
let money_format = Format::new().set_num_format("$#,##0");
let date_format = Format::new().set_num_format("d mmm yyyy");
let worksheet = workbook.add_worksheet();
worksheet.write_with_format(0, 0, "Item", &bold)?;
worksheet.write_with_format(0, 1, "Cost", &bold)?;
worksheet.write_with_format(0, 2, "Date", &bold)?;
worksheet.set_column_width(2, 15)?;
let mut row = 1;
for expense in &expenses {
worksheet.write(row, 0, expense.0)?;
worksheet.write_with_format(row, 1, expense.1, &money_format)?;
let date = ExcelDateTime::parse_from_str(expense.2)?;
worksheet.write_with_format(row, 2, &date, &date_format)?;
row += 1;
}
let first_row = 1; let last_row = first_row + (expenses.len() as u32) - 1;
let item_col = 0;
let cost_col = 1;
worksheet.write_with_format(row, 0, "Total", &bold)?;
let range = cell_range(first_row, cost_col, last_row, cost_col);
let formula = format!("=SUM({range})");
worksheet.write_with_format(row, 1, Formula::new(formula), &money_format)?;
let mut chart = Chart::new_pie();
chart
.add_series()
.set_categories(("Sheet1", first_row, item_col, last_row, item_col))
.set_values(("Sheet1", first_row, cost_col, last_row, cost_col));
worksheet.insert_chart(1, 4, &chart)?;
workbook.save("tutorial5.xlsx")?;
Ok(())
}