1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
// properties - A module for representing document properties.
//
// SPDX-License-Identifier: MIT OR Apache-2.0
//
// Copyright 2022-2023, John McNamara, jmcnamara@cpan.org
#![warn(missing_docs)]
use chrono::{DateTime, Utc};
/// The `DocProperties` struct is used to create an object to represent document
/// metadata properties.
///
/// The `DocProperties` struct is used to create an object to represent various
/// document properties for an Excel file such as the Author's name or the
/// Creation Date.
///
/// <img src="https://rustxlsxwriter.github.io/images/app_doc_properties.png">
///
/// Document Properties can be set for the "Summary" section and also for the
/// "Custom" section of the Excel document properties. See the examples below.
///
/// The `DocProperties` struct is used in conjunction with the
/// [`workbook.set_properties()`](crate::Workbook::set_properties) method.
///
/// # Examples
///
/// An example of setting workbook document properties for a file created using
/// the `rust_xlsxwriter` library. This creates the file used to generate the
/// above image.
///
/// ```
/// # // This code is available in examples/app_doc_properties.rs
/// #
/// use rust_xlsxwriter::{DocProperties, Workbook, XlsxError};
///
/// fn main() -> Result<(), XlsxError> {
/// let mut workbook = Workbook::new();
///
/// let properties = DocProperties::new()
/// .set_title("This is an example spreadsheet")
/// .set_subject("That demonstrates document properties")
/// .set_author("A. Rust User")
/// .set_manager("J. Alfred Prufrock")
/// .set_company("Rust Solutions Inc")
/// .set_category("Sample spreadsheets")
/// .set_keywords("Sample, Example, DocProperties")
/// .set_comment("Created with Rust and rust_xlsxwriter");
///
/// workbook.set_properties(&properties);
///
/// let worksheet = workbook.add_worksheet();
///
/// worksheet.set_column_width(0, 30)?;
/// worksheet.write_string(0, 0, "See File -> Info -> Properties")?;
///
/// workbook.save("doc_properties.xlsx")?;
///
/// Ok(())
/// }
/// ```
///
/// An example of setting custom/user defined workbook document properties.
///
/// ```
/// # // This code is available in examples/doc_properties_custom.rs
/// #
/// use rust_xlsxwriter::{DocProperties, Workbook, XlsxError};
///
/// fn main() -> Result<(), XlsxError> {
/// let mut workbook = Workbook::new();
///
/// let properties = DocProperties::new()
/// .set_custom_property("Checked by", "Admin")
/// .set_custom_property("Cross check", true)
/// .set_custom_property("Department", "Finance")
/// .set_custom_property("Document number", 55301);
///
/// workbook.set_properties(&properties);
///
/// workbook.save("properties.xlsx")?;
///
/// Ok(())
/// }
/// ```
///
/// Output file:
///
/// <img
/// src="https://rustxlsxwriter.github.io/images/doc_properties_custom.png">
///
///
/// # Checksum of a saved file
///
/// A common issue that occurs with `rust_xlsxwriter`, but also with Excel, is
/// that running the same program twice doesn't generate the same file, byte for
/// byte. This can cause issues with applications that do checksumming for
/// testing purposes.
///
/// For example consider the following simple `rust_xlsxwriter` program:
///
/// ```
/// # // This code is available in examples/doc_properties_checksum1.rs
/// #
/// use rust_xlsxwriter::{Workbook, XlsxError};
///
/// fn main() -> Result<(), XlsxError> {
/// let mut workbook = Workbook::new();
/// let worksheet = workbook.add_worksheet();
///
/// worksheet.write_string(0, 0, "Hello")?;
///
/// workbook.save("properties.xlsx")?;
///
/// Ok(())
/// }
/// ```
///
/// If we run this several times, with a small delay, we will get different
/// checksums as shown below:
///
/// ```bash
/// $ cargo run --example doc_properties_checksum1
///
/// $ sum properties.xlsx
/// 62457 6 properties.xlsx
///
/// $ sleep 2
///
/// $ cargo run --example doc_properties_checksum1
///
/// $ sum properties.xlsx
/// 56692 6 properties.xlsx # Different to previous.
/// ```
///
/// This is due to a file creation datetime that is included in the file and
/// which changes each time a new file is created.
///
/// The relevant section of the `docProps/core.xml` sub-file in the xlsx format
/// looks like this:
///
///
/// ```xml
/// <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
/// <cp:coreProperties>
/// <dc:creator/>
/// <cp:lastModifiedBy/>
/// <dcterms:created xsi:type="dcterms:W3CDTF">2023-01-08T00:23:58Z</dcterms:created>
/// <dcterms:modified xsi:type="dcterms:W3CDTF">2023-01-08T00:23:58Z</dcterms:modified>
/// </cp:coreProperties>
/// ```
///
/// If required this can be avoided by setting a constant creation date in the
/// document properties metadata:
///
///
/// ```
/// # // This code is available in examples/doc_properties_checksum2.rs
/// #
/// use chrono::{TimeZone, Utc};
/// use rust_xlsxwriter::{DocProperties, Workbook, XlsxError};
///
/// fn main() -> Result<(), XlsxError> {
/// let mut workbook = Workbook::new();
///
/// // Create a file creation date for the file.
/// let date = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();
///
/// // Add it to the document metadata.
/// let properties = DocProperties::new().set_creation_datetime(&date);
/// workbook.set_properties(&properties);
///
/// let worksheet = workbook.add_worksheet();
/// worksheet.write_string(0, 0, "Hello")?;
///
/// workbook.save("properties.xlsx")?;
///
/// Ok(())
/// }
/// ```
///
/// Then we will get the same checksum for the same output every time:
///
/// ```bash
/// $ cargo run --example doc_properties_checksum2
///
/// $ sum properties.xlsx
/// 8914 6 properties.xlsx
///
/// $ sleep 2
///
/// $ cargo run --example doc_properties_checksum2
///
/// $ sum properties.xlsx
/// 8914 6 properties.xlsx # Same as previous
/// ```
///
#[derive(Clone)]
pub struct DocProperties {
pub(crate) author: String,
pub(crate) title: String,
pub(crate) comment: String,
pub(crate) company: String,
pub(crate) manager: String,
pub(crate) status: String,
pub(crate) subject: String,
pub(crate) category: String,
pub(crate) keywords: String,
pub(crate) hyperlink_base: String,
pub(crate) creation_time: DateTime<Utc>,
pub(crate) custom_properties: Vec<CustomProperty>,
}
impl Default for DocProperties {
fn default() -> Self {
Self::new()
}
}
impl DocProperties {
/// Create a new `DocProperties` struct.
pub fn new() -> DocProperties {
DocProperties {
title: String::new(),
status: String::new(),
author: String::new(),
comment: String::new(),
company: String::new(),
manager: String::new(),
subject: String::new(),
category: String::new(),
keywords: String::new(),
hyperlink_base: String::new(),
creation_time: Utc::now(),
custom_properties: vec![],
}
}
/// Set the Title field of the document properties.
///
/// Set the "Title" field of the document properties to create a title for
/// the document such as "Sales Report". See the example above.
///
/// # Arguments
///
/// * `title` - The title string property.
///
pub fn set_title(mut self, title: impl Into<String>) -> DocProperties {
self.title = title.into();
self
}
/// Set the Subject field of the document properties.
///
/// Set the "Subject" field of the document properties to indicate the
/// subject matter. See the example above.
///
/// # Arguments
///
/// * `subject` - The subject string property.
///
pub fn set_subject(mut self, subject: impl Into<String>) -> DocProperties {
self.subject = subject.into();
self
}
/// Set the Manager field of the document properties.
///
/// Set the "Manager" field of the document properties. See the example
/// above. See the example above.
///
/// # Arguments
///
/// * `manager` - The manager string property.
///
pub fn set_manager(mut self, manager: impl Into<String>) -> DocProperties {
self.manager = manager.into();
self
}
/// Set the Company field of the document properties.
///
/// Set the "Company" field of the document properties. See the example
/// above.
///
/// # Arguments
///
/// * `company` - The company string property.
///
pub fn set_company(mut self, company: impl Into<String>) -> DocProperties {
self.company = company.into();
self
}
/// Set the Category field of the document properties.
///
/// Set the "Category" field of the document properties to indicate the
/// category that the file belongs to. See the example above.
///
/// # Arguments
///
/// * `category` - The category string property.
///
pub fn set_category(mut self, category: impl Into<String>) -> DocProperties {
self.category = category.into();
self
}
/// Set the Author field of the document properties.
///
/// Set the "Author" field of the document properties. See the example
/// above.
///
/// # Arguments
///
/// * `author` - The author string property.
///
pub fn set_author(mut self, author: impl Into<String>) -> DocProperties {
self.author = author.into();
self
}
/// Set the Keywords field of the document properties.
///
/// Set the "Keywords" field of the document properties. This can be one or
/// more keywords that can be used in searches. See the example above.
///
/// # Arguments
///
/// * `keywords` - The keywords string property.
///
pub fn set_keywords(mut self, keywords: impl Into<String>) -> DocProperties {
self.keywords = keywords.into();
self
}
/// Set the Comment field of the document properties.
///
/// Set the "Comment" field of the document properties. This can be a
/// general comment or summary that you want to add to the properties. See
/// the example above.
///
/// # Arguments
///
/// * `comment` - The comment string property.
///
pub fn set_comment(mut self, comment: impl Into<String>) -> DocProperties {
self.comment = comment.into();
self
}
/// Set the Status field of the document properties.
///
/// Set the "Status" field of the document properties such as "Draft" or
/// "Final".
///
/// # Arguments
///
/// * `status` - The status string property.
///
pub fn set_status(mut self, status: impl Into<String>) -> DocProperties {
self.status = status.into();
self
}
/// Set the hyperlink base field of the document properties.
///
/// Set the "Hyperlink base" field of the document properties to have a
/// default base url.
///
/// # Arguments
///
/// * `hyperlink_base` - The hyperlink base string property.
///
pub fn set_hyperlink_base(mut self, hyperlink_base: impl Into<String>) -> DocProperties {
self.hyperlink_base = hyperlink_base.into();
self
}
/// Set the create date/time for the document.
///
/// Excel sets a date and time for every new document in UTC. The
/// `rust_xlsxwriter` library does the same. However there may be cases
/// where you wish to set a different creation time. See the example above.
///
/// # Arguments
///
/// * `datetime` - The creation date property. [`chrono::DateTime`]
///
/// [`chrono::DateTime`]:
/// https://docs.rs/chrono/latest/chrono/struct.DateTime.html
///
pub fn set_creation_datetime(mut self, create_time: &DateTime<Utc>) -> DocProperties {
self.creation_time = *create_time;
self
}
/// Set a custom document property.
///
/// Set a user defined property that will appear in the Custom section of
/// the document properties.
///
/// Excel support custom data types that are equivalent to the Rust types:
/// [`&str`], [`f64`], [`i32`] [`bool`] and `&DateTime<Utc>`
///
/// # Arguments
///
/// * `name` - The user defined name of the custom property.
/// * `value` - The value can be a [`&str`], [`f64`], [`i32`] [`bool`] or
/// `&DateTime<Utc>` type for which the `IntoCustomProperty` trait is
/// implemented.
///
/// # Examples
///
/// An example of setting custom/user defined workbook document properties.
///
/// ```
/// # // This code is available in examples/doc_properties_custom.rs
/// #
/// use rust_xlsxwriter::{DocProperties, Workbook, XlsxError};
///
/// fn main() -> Result<(), XlsxError> {
/// let mut workbook = Workbook::new();
///
/// let properties = DocProperties::new()
/// .set_custom_property("Checked by", "Admin")
/// .set_custom_property("Cross check", true)
/// .set_custom_property("Department", "Finance")
/// .set_custom_property("Document number", 55301);
///
/// workbook.set_properties(&properties);
///
/// workbook.save("properties.xlsx")?;
///
/// Ok(())
/// }
/// ```
///
/// Output file:
///
/// <img
/// src="https://rustxlsxwriter.github.io/images/doc_properties_custom.png">
///
pub fn set_custom_property<T>(mut self, name: impl Into<String>, value: T) -> DocProperties
where
T: IntoCustomProperty,
{
self.custom_properties.push(value.new_custom_property(name));
self
}
}
// -----------------------------------------------------------------------
// Helper enums/structs/functions.
// -----------------------------------------------------------------------
/// The CustomProperty struct represents data types used in Excel’s custom
/// document properties.
#[doc(hidden)]
#[derive(Clone)]
pub struct CustomProperty {
pub(crate) property_type: CustomPropertyType,
pub(crate) name: String,
pub(crate) text: String,
pub(crate) number_int: i32,
pub(crate) number_real: f64,
pub(crate) boolean: bool,
pub(crate) datetime: DateTime<Utc>,
}
impl Default for CustomProperty {
fn default() -> Self {
CustomProperty {
property_type: CustomPropertyType::Text,
name: String::new(),
text: String::new(),
number_int: 0,
number_real: 0.0,
boolean: true,
datetime: Utc::now(),
}
}
}
impl CustomProperty {
pub(crate) fn new_property_string(name: String, value: String) -> CustomProperty {
CustomProperty {
property_type: CustomPropertyType::Text,
name,
text: value,
..Default::default()
}
}
pub(crate) fn new_property_i32(name: String, value: i32) -> CustomProperty {
CustomProperty {
property_type: CustomPropertyType::Int,
name,
number_int: value,
..Default::default()
}
}
pub(crate) fn new_property_f64(name: String, value: f64) -> CustomProperty {
CustomProperty {
property_type: CustomPropertyType::Real,
name,
number_real: value,
..Default::default()
}
}
pub(crate) fn new_property_bool(name: String, value: bool) -> CustomProperty {
CustomProperty {
property_type: CustomPropertyType::Bool,
name,
boolean: value,
..Default::default()
}
}
pub(crate) fn new_property_datetime(name: String, value: &DateTime<Utc>) -> CustomProperty {
CustomProperty {
property_type: CustomPropertyType::DateTime,
name,
datetime: *value,
..Default::default()
}
}
}
#[derive(Clone)]
pub(crate) enum CustomPropertyType {
Text,
Int,
Real,
Bool,
DateTime,
}
/// Trait to map different Rust types into Excel data types used in custom document properties.
///
pub trait IntoCustomProperty {
/// Types/objects supporting this trait must be able to convert to a
/// [`CustomProperty`] struct.
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty;
}
impl IntoCustomProperty for &str {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_string(name.into(), self.into())
}
}
impl IntoCustomProperty for String {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_string(name.into(), self)
}
}
impl IntoCustomProperty for &String {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_string(name.into(), self.into())
}
}
impl IntoCustomProperty for i32 {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_i32(name.into(), self)
}
}
impl IntoCustomProperty for f64 {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_f64(name.into(), self)
}
}
impl IntoCustomProperty for bool {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_bool(name.into(), self)
}
}
impl IntoCustomProperty for &DateTime<Utc> {
fn new_custom_property(self, name: impl Into<String>) -> CustomProperty {
CustomProperty::new_property_datetime(name.into(), self)
}
}