fast_xlsx 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0642c1f4069d2b6537757d873ed2e591ddd3c7dab25f4bd1c867fad4fe8f0ead
4
- data.tar.gz: d0b7696cc3ee573ec02821a3b210ef34ce68fb821c83666f2fa0938c8bbabc16
3
+ metadata.gz: 2c67527d71affcbc069c4b9516aeca478a50824cc102319509b4793d217794e4
4
+ data.tar.gz: e539469f97cdd27ca642e9fc64270ce4909134cb82047f187c198f4126de2c68
5
5
  SHA512:
6
- metadata.gz: 40fbd10f5ad43e8fc7a6bedccdc68cee4a324fa5ae9586dd7e9281272c6c2b1a465049c53fd67f042c9dffe00ca7c21c1512d4e1ffcbd01e2ea5ce52dc658938
7
- data.tar.gz: 5a6ca0279e195f3b109d23f0bf1afbed5680c6f6fd844aa0e30411468e1f8d7203680d30bba838cdb15b2dfac1f9c170a9b9576ed5db0650439c331fd2ff11be
6
+ metadata.gz: ee745f9fb7a1ccdbc4aca1387c675258e1878841a632739987131b8358819ab04b35a11d035174969a2e87902a6c11865e523a9172ad67f8c5f9a5848710f7b4
7
+ data.tar.gz: d3b4d68ea19941088b656cb133b07eb4b1f854bfb55ff1d1e20f03b05644b3cba4fb2062e9a9c3ead9ec6d5f464c53b169c415e1e274f8192ceefab7014c0363
data/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [1.2.0] - 2026-11-19
4
+
5
+ Upgrading is recommended: 1.1.0 and earlier are affected by the issues under Security. A chart `title:`, `x_axis:`, `y_axis:` or series `name:` written as a cell reference String (`"Sheet1!$A$1"`) now raises; pass `FastXlsx::Formula.new("Sheet1!$A$1")` instead.
6
+
7
+ ### Security
8
+
9
+ - `insert_image` raises `FastXlsx::Error` for an image that would be larger than a worksheet. The size comes from the image's own header, so a file of a few bytes could keep `save` and `to_xlsx` busy for minutes, and a `Timeout` could not interrupt it.
10
+ - Control characters (below U+0020 other than tab, newline and carriage return) now raise `ArgumentError` in worksheet names, table headers and `total_label:`, data validation titles and messages, `insert_image`'s `alt_text:`, `:text` conditional format values, `num_format:`, `font_name:`, URLs and `unprotect_range`'s `name:`. They were written into the file as is, and Excel could not open it. Cell text is not affected.
11
+ - A chart's `title:`, `x_axis:`, `y_axis:` and series `name:` are always text. A String such as `"Sheet1!A1"` or `"=(Sheet1!$A$1)"` was read as a cell reference or written as a formula; it now raises `ArgumentError`. To show a cell's content, pass a `FastXlsx::Formula`.
12
+ - A `:cell` conditional format value that starts and ends with a double quote and has another one inside (`'"x"&A2&"y"'`) is compared as that text, instead of continuing as formula text.
13
+
14
+ ### Fixed
15
+
16
+ - `write` with a Hash format, and `conditional_format` called natively, keep their own copy of the format while the value is converted. The value's `to_s` (or another thread) could push the format out of the cache of Hash formats and let it be freed before it was used. No crash was reproduced.
17
+ - Updated rust_xlsxwriter to 0.102, which doubles a double quote in a `:text` conditional format value instead of ending the rule's formula there.
18
+
19
+ ## [1.1.0] - 2026-11-03
20
+
21
+ ### Added
22
+
23
+ - `Worksheet#embed_image` places an image in a cell, where it fits the cell and moves and sizes with it (Excel 365's "Place in Cell"; older Excel shows `#VALUE!`). It takes a path or an IO like `insert_image`, plus `alt_text:` and `format:`. It raises `FastXlsx::Error` in `memory: :constant` and `:low` mode, which rust_xlsxwriter does not support for embedded images.
24
+ - `conditional_format` types `:top` and `:bottom` (`value:` count, or a percentage with `percent: true`), `:average` (`criteria: :above`, `:below`, `:above_or_equal`, `:below_or_equal`, and `std_dev: 1..3`), `:duplicate`, `:unique`, `:blank`, `:not_blank`, `:error`, `:not_error`, and `:date` (`criteria: :yesterday`, `:today`, `:tomorrow`, `:last_7_days`, `:last_week`, `:this_week`, `:next_week`, `:last_month`, `:this_month`, `:next_month`).
25
+ - `conditional_format` type `:icon_set`, with `icons:` (e.g. `:three_arrows`, `:five_boxes`; default `:three_traffic_lights`), `reverse: true` and `icons_only: true`.
26
+ - Custom colors for data bars and color scales: `type: :data_bar, color: "#63BE7B"`, and `type: :color_scale, colors: [min, max]` or `[min, mid, max]`. `colors: 2` and `3` work as before. A data bar's `color:` sets both its fill and its border.
27
+
28
+ ### Deprecated
29
+
30
+ - `colors:` on `conditional_format` `type: :data_bar` was always ignored; it now prints a warning and will raise `ArgumentError` in 2.0. Use `color:` for the bar color.
31
+
3
32
  ## [1.0.0] - 2026-10-18
4
33
 
5
34
  The first stable release, with the same API as 0.8.1. From now on fast_xlsx follows Semantic Versioning: no breaking change before 2.0, and anything to be removed first prints a deprecation warning for at least one minor release.
data/Cargo.lock CHANGED
@@ -207,9 +207,9 @@ checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
207
207
 
208
208
  [[package]]
209
209
  name = "magnus"
210
- version = "0.9.2"
210
+ version = "0.9.3"
211
211
  source = "registry+https://github.com/rust-lang/crates.io-index"
212
- checksum = "b9068710e00d21be762edca59b9c4c8946dbdb29820d4f76ad559afea07982c9"
212
+ checksum = "40ef424404d166cbb71c8b8d19c9c589c748c4547c1afa1928c5504299f6c713"
213
213
  dependencies = [
214
214
  "magnus-macros",
215
215
  "rb-sys",
@@ -353,9 +353,9 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
353
353
 
354
354
  [[package]]
355
355
  name = "rust_xlsxwriter"
356
- version = "0.100.0"
356
+ version = "0.102.0"
357
357
  source = "registry+https://github.com/rust-lang/crates.io-index"
358
- checksum = "c44904ffb6c57b148ffcc8ce3011c28bc49b97e1a8343b2d632283cd566e1393"
358
+ checksum = "6ca3d0e879a578c1313c2800ab0c6c029d38eed18098675e50341a30d32372ed"
359
359
  dependencies = [
360
360
  "tempfile",
361
361
  "zip",
data/README.md CHANGED
@@ -254,7 +254,7 @@ ws.autofilter(0..100, 0..3) # rows and columns, each an Integer or a Range
254
254
  ws.merge_range(0, 0..3, "Q3 report", title) # row 1, columns A–D
255
255
  ```
256
256
 
257
- Methods that take one cell (`write`, `write_comment`, `insert_image`, `insert_chart`, `freeze_panes`) take `(row, col)` or a reference like `"B2"`.
257
+ Methods that take one cell (`write`, `write_comment`, `insert_image`, `embed_image`, `insert_chart`, `freeze_panes`) take `(row, col)` or a reference like `"B2"`.
258
258
 
259
259
  `autofit` only sees rows still in memory, so in `:constant` / `:low` memory mode it ignores rows already written to disk; set widths with `column_width` instead.
260
260
 
@@ -315,8 +315,14 @@ ws.conditional_format(0, 1, 99, 1, type: :cell, criteria: :<, value: 0, format:
315
315
  ws.conditional_format(0, 1, 99, 1, type: :cell, criteria: :between, value: [1, 10], format: red)
316
316
  ws.conditional_format(0, 0, 99, 0, type: :text, criteria: :contains, value: "error", format: red)
317
317
  ws.conditional_format(0, 0, 99, 3, type: :formula, value: "=$D1>100", format: red)
318
- ws.conditional_format(0, 2, 99, 2, type: :data_bar)
319
- ws.conditional_format(0, 2, 99, 2, type: :color_scale) # 3-color; colors: 2 for 2-color
318
+ ws.conditional_format(0, 1, 99, 1, type: :top, value: 10, format: red) # or :bottom; percent: true for a %
319
+ ws.conditional_format(0, 1, 99, 1, type: :average, criteria: :below, std_dev: 1, format: red)
320
+ ws.conditional_format(0, 0, 99, 0, type: :duplicate, format: red)
321
+ ws.conditional_format(0, 4, 99, 4, type: :date, criteria: :last_7_days, format: red)
322
+ ws.conditional_format(0, 2, 99, 2, type: :data_bar) # or color: "#63BE7B"
323
+ ws.conditional_format(0, 2, 99, 2, type: :color_scale) # 3-color; colors: 2 for 2-color
324
+ ws.conditional_format(0, 2, 99, 2, type: :color_scale, colors: %w[#F8696B #FFEB84 #63BE7B]) # min, mid, max
325
+ ws.conditional_format(0, 2, 99, 2, type: :icon_set, icons: :three_arrows) # reverse: true, icons_only: true
320
326
  ```
321
327
 
322
328
  | `type` | `criteria` | `value` |
@@ -324,7 +330,14 @@ ws.conditional_format(0, 2, 99, 2, type: :color_scale) # 3-color; col
324
330
  | `:cell` | `:==`, `:!=`, `:>`, `:>=`, `:<`, `:<=`, `:between`, `:not_between` | number or string; `[min, max]` for the range criteria |
325
331
  | `:text` | `:contains`, `:not_contains`, `:begins_with`, `:ends_with` | string |
326
332
  | `:formula` | — | formula string, relative to the top-left cell |
333
+ | `:top`, `:bottom` | — | how many, 1–1000 (default 10); with `percent: true`, a percentage 1–100 |
334
+ | `:average` | `:above` (default), `:below`, `:above_or_equal`, `:below_or_equal`; `std_dev: 1`, `2` or `3` with `:above`/`:below` | — |
335
+ | `:duplicate`, `:unique`, `:blank`, `:not_blank`, `:error`, `:not_error` | — | — |
336
+ | `:date` | `:yesterday`, `:today`, `:tomorrow`, `:last_7_days`, `:last_week`, `:this_week`, `:next_week`, `:last_month`, `:this_month`, `:next_month` | — |
327
337
  | `:data_bar`, `:color_scale` | — | — |
338
+ | `:icon_set` | — | — |
339
+
340
+ Colors are `"#RRGGBB"` or `0xRRGGBB`. `:data_bar` takes `color:`, which sets both the bar's fill and its border; `:color_scale` takes `colors:`, either `2` or `3` or the 2 or 3 colors from minimum to maximum. `:icon_set` takes `icons:` (default `:three_traffic_lights`): `:three_arrows`, `:three_arrows_gray`, `:three_flags`, `:three_traffic_lights`, `:three_traffic_lights_with_rim`, `:three_signs`, `:three_symbols_circled`, `:three_symbols`, `:three_stars`, `:three_triangles`, `:four_arrows`, `:four_arrows_gray`, `:four_red_to_black`, `:four_histograms`, `:four_traffic_lights`, `:five_arrows`, `:five_arrows_gray`, `:five_histograms`, `:five_quadrants`, `:five_boxes`; `reverse: true` reverses their order and `icons_only: true` hides the cell values.
328
341
 
329
342
  ### Data validation
330
343
 
@@ -350,6 +363,7 @@ ws.write_comment(0, 0, "Checked by finance", author: "Zac") # Excel shows it a
350
363
  ws.insert_image(0, 0, "logo.png") # top-left corner in A1
351
364
  ws.insert_image(0, 5, StringIO.new(blob.download), scale: 0.5, x_offset: 10, y_offset: 4, alt_text: "Logo")
352
365
  ws.insert_image(10, 0, "chart.png", width: 320, height: 180) # pixel size; one of them keeps the aspect ratio
366
+ ws.embed_image("B12", "photo.png", alt_text: "Photo", format: { align: :center }) # in the cell, sized with it (Excel 365; not in memory: :constant/:low)
353
367
  ```
354
368
 
355
369
  A String is always treated as a path, so wrap raw bytes (such as Active Storage's `blob.download`) in a `StringIO`.
@@ -381,7 +395,7 @@ ws.insert_chart(1, 4, type: :column,
381
395
  title: "Q1", x_axis: "Month", y_axis: "Amount", width: 600, height: 360)
382
396
  ```
383
397
 
384
- `type`: `:column`, `:column_stacked`, `:bar`, `:bar_stacked`, `:line`, `:line_stacked`, `:area`, `:area_stacked`, `:pie`, `:doughnut`, `:radar`, `:scatter`. Ranges use Excel syntax, so a chart can plot data from another worksheet. Sizes are in pixels (default 480 × 288).
398
+ `type`: `:column`, `:column_stacked`, `:bar`, `:bar_stacked`, `:line`, `:line_stacked`, `:area`, `:area_stacked`, `:pie`, `:doughnut`, `:radar`, `:scatter`. Ranges use Excel syntax, so a chart can plot data from another worksheet. `title:`, `x_axis:`, `y_axis:` and a series `name:` are text; pass a `FastXlsx::Formula` such as `FastXlsx::Formula.new("Sheet1!$A$1")` to show a cell's content instead. Sizes are in pixels (default 480 × 288).
385
399
 
386
400
  Values are mapped by type:
387
401
 
data/SECURITY.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  ## Supported versions
4
4
 
5
- Security fixes go into the latest release of the newest minor version. Until 1.0 that is 0.8.x; from 1.0, the latest 1.x.
5
+ Security fixes go into the latest release of the newest minor version.
6
6
 
7
7
  | Version | Supported |
8
8
  |---|---|
9
- | 0.8.x | ✅ |
10
- | < 0.8 | ❌ (upgrade to 0.8.x; the [changelog](CHANGELOG.md) lists every change) |
9
+ | 1.2.x | ✅ |
10
+ | < 1.2 | ❌ (upgrade to 1.2.x; the [changelog](CHANGELOG.md) lists every change) |
11
11
 
12
12
  ## Reporting a vulnerability
13
13
 
@@ -14,7 +14,7 @@ magnus = { version = "0.9", features = ["rb-sys"] }
14
14
  rb-sys = { version = "0.9", features = ["stable-api-compiled-fallback"] }
15
15
  # No "zlib" feature: without it zip compresses with zlib-rs, which saves
16
16
  # 20-30% faster than the system zlib (and needs no C library).
17
- rust_xlsxwriter = { version = "0.100.0", features = ["constant_memory"] }
17
+ rust_xlsxwriter = { version = "0.102.0", features = ["constant_memory"] }
18
18
 
19
19
  [build-dependencies]
20
20
  rb-sys-env = "0.2.2"
@@ -10,8 +10,12 @@ use magnus::{
10
10
  };
11
11
  use rust_xlsxwriter::{
12
12
  Color, ConditionalFormat, ConditionalFormat2ColorScale, ConditionalFormat3ColorScale,
13
+ ConditionalFormatAverage, ConditionalFormatAverageRule, ConditionalFormatBlank,
13
14
  ConditionalFormatCell, ConditionalFormatCellRule, ConditionalFormatDataBar,
14
- ConditionalFormatFormula, ConditionalFormatText, ConditionalFormatTextRule,
15
+ ConditionalFormatDate, ConditionalFormatDateRule, ConditionalFormatDuplicate,
16
+ ConditionalFormatError, ConditionalFormatFormula, ConditionalFormatIconSet,
17
+ ConditionalFormatIconType, ConditionalFormatText,
18
+ ConditionalFormatTextRule, ConditionalFormatTop, ConditionalFormatTopRule,
15
19
  ConditionalFormatValue, DataValidation, DataValidationRule, FormatAlign, FormatBorder,
16
20
  FormatScript, FormatUnderline, IgnoreError, IntoDataValidationValue, IntoExcelData, XlsxError,
17
21
  };
@@ -85,6 +89,62 @@ fn check_positive(ruby: &Ruby, what: &str, size: f64) -> Result<f64, Error> {
85
89
  ))
86
90
  }
87
91
 
92
+ // Characters XML 1.0 forbids. rust_xlsxwriter escapes them in cell text but
93
+ // writes them as is into attributes, which makes the file unreadable.
94
+ fn check_xml(what: &str, text: &str) -> Result<(), Error> {
95
+ let illegal = |c: char| {
96
+ (c < ' ' && !matches!(c, '\t' | '\n' | '\r')) || matches!(c, '\u{FFFE}' | '\u{FFFF}')
97
+ };
98
+ if text.chars().any(illegal) {
99
+ return Err(Error::new(
100
+ Ruby::get().unwrap().exception_arg_error(),
101
+ format!("invalid {what} {text:?}: control characters are not allowed"),
102
+ ));
103
+ }
104
+ Ok(())
105
+ }
106
+
107
+ // A chart title, axis name or series name. rust_xlsxwriter reads "Sheet1!A1"
108
+ // and "=(...)" / "=Table[...]" strings as references, so a plain String must
109
+ // not look like one; a FastXlsx::Formula asks for the reference.
110
+ fn chart_label(ruby: &Ruby, v: Value) -> Result<String, Error> {
111
+ if v.is_kind_of(ruby.get_inner(&FORMULA)) {
112
+ let expression: String = v.funcall("expression", ())?;
113
+ let reference = expression.strip_prefix('=').unwrap_or(&expression);
114
+ return Ok(if reference.starts_with('(') || reference.contains('[') {
115
+ format!("={reference}")
116
+ } else {
117
+ reference.to_string()
118
+ });
119
+ }
120
+ let text = String::try_convert(v)?;
121
+ let unparsed = text.starts_with("=(") || (text.starts_with('=') && text.contains('['));
122
+ // The same test as rust_xlsxwriter's is_valid_range().
123
+ let range = text.find('!').is_some_and(|at| {
124
+ let range = text[at + 1..].replace('$', "");
125
+ range.starts_with(|c: char| c.is_ascii_uppercase())
126
+ && range.ends_with(|c: char| c.is_ascii_digit())
127
+ && range
128
+ .chars()
129
+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == ':')
130
+ });
131
+ if unparsed || range {
132
+ return Err(Error::new(
133
+ ruby.exception_arg_error(),
134
+ format!(
135
+ "chart text {text:?} would be read as a cell reference: \
136
+ pass a FastXlsx::Formula to reference a cell"
137
+ ),
138
+ ));
139
+ }
140
+ Ok(text)
141
+ }
142
+
143
+ // The largest area a sheet can cover, in pixels: every column at 255
144
+ // characters wide and every row at 409 points high.
145
+ const MAX_IMAGE_WIDTH: f64 = 16_384.0 * 1_790.0;
146
+ const MAX_IMAGE_HEIGHT: f64 = 1_048_576.0 * 546.0;
147
+
88
148
  // A range of rows is checked before any row changes, so it is all or nothing.
89
149
  fn check_last_row(last: u32) -> Result<(), Error> {
90
150
  if last < MAX_ROWS {
@@ -217,6 +277,7 @@ impl Workbook {
217
277
  Some(name) => {
218
278
  // Validate the name before adding: rust_xlsxwriter adds the
219
279
  // sheet first, so a bad name would leave a "SheetN" behind.
280
+ check_xml("worksheet name", &name)?;
220
281
  rust_xlsxwriter::Worksheet::new()
221
282
  .set_name(&name)
222
283
  .map_err(xerr)?;
@@ -427,7 +488,9 @@ impl CellValue {
427
488
  } else if v.is_kind_of(ruby.get_inner(&FORMULA)) {
428
489
  CellValue::Formula(v.funcall("expression", ())?)
429
490
  } else if v.is_kind_of(ruby.get_inner(&URL)) {
430
- CellValue::Url(v.funcall("url", ())?, v.funcall("text", ())?)
491
+ let url: String = v.funcall("url", ())?;
492
+ check_xml("URL", &url)?;
493
+ CellValue::Url(url, v.funcall("text", ())?)
431
494
  } else if v.is_kind_of(ruby.get_inner(&RICH_STRING)) {
432
495
  let segments: RArray = v.funcall("segments", ())?;
433
496
  let mut parts = Vec::with_capacity(segments.len());
@@ -575,7 +638,14 @@ fn choice<T: Clone>(
575
638
  // A number or string compared against in a conditional format rule.
576
639
  fn cf_value(ruby: &Ruby, v: Value) -> Result<ConditionalFormatValue, Error> {
577
640
  if let Some(s) = RString::from_value(v) {
578
- Ok(s.to_string()?.into())
641
+ let s = s.to_string()?;
642
+ // rust_xlsxwriter writes a "quoted" string as is, so one with a lone
643
+ // quote inside would continue as formula text: quote it here instead.
644
+ let inner = s.strip_prefix('"').and_then(|s| s.strip_suffix('"'));
645
+ if inner.is_some_and(|inner| inner.replace("\"\"", "").contains('"')) {
646
+ return Ok(format!("\"{}\"", s.replace('"', "\"\"")).into());
647
+ }
648
+ Ok(s.into())
579
649
  } else if v.is_kind_of(ruby.class_numeric()) {
580
650
  Ok(f64::try_convert(v)?.into())
581
651
  } else {
@@ -817,7 +887,9 @@ const TABLE_TOTALS: &[(&str, TableFunction)] = &[
817
887
  // Also returns a copy of the column's format, if any, for later writes.
818
888
  fn table_column(ruby: &Ruby, v: Value) -> Result<(TableColumn, Option<Arc<Style>>), Error> {
819
889
  let Some(spec) = RHash::from_value(v) else {
820
- return Ok((TableColumn::new().set_header(String::try_convert(v)?), None));
890
+ let header = String::try_convert(v)?;
891
+ check_xml("table header", &header)?;
892
+ return Ok((TableColumn::new().set_header(header), None));
821
893
  };
822
894
  check_keys(
823
895
  ruby,
@@ -826,11 +898,13 @@ fn table_column(ruby: &Ruby, v: Value) -> Result<(TableColumn, Option<Arc<Style>
826
898
  "table column",
827
899
  )?;
828
900
  let header = String::try_convert(raw_opt(ruby, spec, "header"))?;
901
+ check_xml("table header", &header)?;
829
902
  let mut column = TableColumn::new().set_header(header);
830
903
  if let Some(total) = opt::<Value>(ruby, spec, "total")? {
831
904
  column = column.set_total_function(choice(ruby, "table total", total, TABLE_TOTALS)?);
832
905
  }
833
906
  if let Some(label) = opt::<String>(ruby, spec, "total_label")? {
907
+ check_xml("total_label", &label)?;
834
908
  column = column.set_total_label(label);
835
909
  }
836
910
  let format = opt::<&Format>(ruby, spec, "format")?.map(|f| f.0.clone());
@@ -998,14 +1072,20 @@ impl Format {
998
1072
  "border_color" => taken.set_border_color(color(ruby, value)?),
999
1073
  "num_format" => {
1000
1074
  has_num_format = true;
1001
- taken.set_num_format(String::try_convert(value)?)
1075
+ let num_format = String::try_convert(value)?;
1076
+ check_xml("num_format", &num_format)?;
1077
+ taken.set_num_format(num_format)
1002
1078
  }
1003
1079
  "font_size" => taken.set_font_size(check_positive(
1004
1080
  ruby,
1005
1081
  "font_size",
1006
1082
  f64::try_convert(value)?,
1007
1083
  )?),
1008
- "font_name" => taken.set_font_name(String::try_convert(value)?),
1084
+ "font_name" => {
1085
+ let font_name = String::try_convert(value)?;
1086
+ check_xml("font_name", &font_name)?;
1087
+ taken.set_font_name(font_name)
1088
+ }
1009
1089
  "font_color" => taken.set_font_color(color(ruby, value)?),
1010
1090
  "bg_color" => taken.set_background_color(color(ruby, value)?),
1011
1091
  "align" => taken.set_align(choice(
@@ -1275,6 +1355,9 @@ impl Worksheet {
1275
1355
  format: Option<&Format>,
1276
1356
  ) -> Result<(), Error> {
1277
1357
  rb_self.check_not_flushed(ruby, row)?;
1358
+ // Converting the value can run Ruby code, and a Format made from a
1359
+ // Hash is only kept alive by Format._coerce's cache: keep our own copy.
1360
+ let style = format.map(|f| f.0.clone());
1278
1361
  let value = CellValue::from_ruby(ruby, v)?;
1279
1362
  let tables = rb_self.table_formats.borrow();
1280
1363
  let rows = rb_self.formatted_rows.borrow();
@@ -1290,7 +1373,7 @@ impl Worksheet {
1290
1373
  &columns,
1291
1374
  row,
1292
1375
  col,
1293
- format.map(|f| &*f.0),
1376
+ style.as_deref(),
1294
1377
  &value,
1295
1378
  ),
1296
1379
  )
@@ -1403,6 +1486,7 @@ impl Worksheet {
1403
1486
  name: Option<String>,
1404
1487
  password: Option<String>,
1405
1488
  ) -> Result<Obj<Self>, Error> {
1489
+ check_xml("range name", name.as_deref().unwrap_or(""))?;
1406
1490
  rb_self.with_ws(|ws| {
1407
1491
  ws.unprotect_range_with_options(
1408
1492
  fr,
@@ -1675,15 +1759,6 @@ impl Worksheet {
1675
1759
  lc: u16,
1676
1760
  options: RHash,
1677
1761
  ) -> Result<Obj<Self>, Error> {
1678
- check_keys(
1679
- ruby,
1680
- options,
1681
- &["type", "criteria", "value", "format", "colors"],
1682
- "conditional_format",
1683
- )?;
1684
- let format = opt::<&Format>(ruby, options, "format")?;
1685
- let value = raw_opt(ruby, options, "value");
1686
- let criteria = raw_opt(ruby, options, "criteria");
1687
1762
  let kind = choice(
1688
1763
  ruby,
1689
1764
  "conditional format type",
@@ -1694,8 +1769,73 @@ impl Worksheet {
1694
1769
  ("formula", "formula"),
1695
1770
  ("data_bar", "data_bar"),
1696
1771
  ("color_scale", "color_scale"),
1772
+ ("top", "top"),
1773
+ ("bottom", "bottom"),
1774
+ ("average", "average"),
1775
+ ("duplicate", "duplicate"),
1776
+ ("unique", "unique"),
1777
+ ("blank", "blank"),
1778
+ ("not_blank", "not_blank"),
1779
+ ("error", "error"),
1780
+ ("not_error", "not_error"),
1781
+ ("date", "date"),
1782
+ ("icon_set", "icon_set"),
1697
1783
  ],
1698
1784
  )?;
1785
+ // Each type takes only the options it uses, except the types released
1786
+ // before :top etc., which keep ignoring unused options (SemVer).
1787
+ let allowed: &[&str] = match kind {
1788
+ "top" | "bottom" => &["type", "value", "percent", "format"],
1789
+ "average" => &["type", "criteria", "std_dev", "format"],
1790
+ "date" => &["type", "criteria", "format"],
1791
+ "duplicate" | "unique" | "blank" | "not_blank" | "error" | "not_error" => {
1792
+ &["type", "format"]
1793
+ }
1794
+ "icon_set" => &["type", "icons", "reverse", "icons_only"],
1795
+ // colors: is deprecated on :data_bar; the Ruby wrapper warns and drops it.
1796
+ "data_bar" => &["type", "criteria", "value", "format", "color"],
1797
+ _ => &["type", "criteria", "value", "format", "colors"],
1798
+ };
1799
+ check_keys(ruby, options, allowed, &format!("conditional_format :{kind}"))?;
1800
+ // A copy, as in write(): the options below are converted by Ruby code.
1801
+ let format = opt::<&Format>(ruby, options, "format")?.map(|f| f.0.clone());
1802
+ let value = raw_opt(ruby, options, "value");
1803
+ let criteria = raw_opt(ruby, options, "criteria");
1804
+ // A whole number in `range`: other numbers raise ArgumentError with
1805
+ // `hint`, non-numbers TypeError.
1806
+ let whole = |v: Value, name: &str, range: std::ops::RangeInclusive<f64>, hint: &str| {
1807
+ let n = f64::try_convert(v)?;
1808
+ if n.fract() == 0.0 && range.contains(&n) {
1809
+ Ok(n as u16)
1810
+ } else {
1811
+ Err(Error::new(
1812
+ ruby.exception_arg_error(),
1813
+ format!("invalid {name} {}: {hint}", v.inspect()),
1814
+ ))
1815
+ }
1816
+ };
1817
+ // A color for the options added after 1.0, which raise TypeError for a
1818
+ // non-color type (Format keeps its released ArgumentError).
1819
+ let new_color = |c: Value| {
1820
+ if Integer::from_value(c).is_none() && RString::from_value(c).is_none() {
1821
+ return Err(Error::new(
1822
+ ruby.exception_type_error(),
1823
+ format!("invalid color {}: use \"#RRGGBB\" or 0xRRGGBB", c.inspect()),
1824
+ ));
1825
+ }
1826
+ color(ruby, c)
1827
+ };
1828
+ // true or false (nil when not given); other values raise TypeError.
1829
+ let flag = |name: &str| {
1830
+ let v = raw_opt(ruby, options, name);
1831
+ if v.to_bool() && !v.is_kind_of(ruby.class_true_class()) {
1832
+ return Err(Error::new(
1833
+ ruby.exception_type_error(),
1834
+ format!("invalid {name} {}: use true or false", v.inspect()),
1835
+ ));
1836
+ }
1837
+ Ok(v.to_bool())
1838
+ };
1699
1839
  // Built before taking the lock: building converts Ruby values.
1700
1840
  type AddRule = Box<dyn FnOnce(&mut rust_xlsxwriter::Worksheet) -> Result<(), XlsxError>>;
1701
1841
  fn rule<T: ConditionalFormat + Send + Sync + 'static>(
@@ -1705,17 +1845,25 @@ impl Worksheet {
1705
1845
  Box::new(move |ws| ws.add_conditional_format(fr, fc, lr, lc, &cf).map(|_| ()))
1706
1846
  }
1707
1847
  let range = (fr, fc, lr, lc);
1848
+ // The rule for a conditional format that takes format:.
1849
+ macro_rules! formatted {
1850
+ ($cf:expr) => {
1851
+ rule(
1852
+ range,
1853
+ match &format {
1854
+ Some(f) => $cf.set_format(&f.format),
1855
+ None => $cf,
1856
+ },
1857
+ )
1858
+ };
1859
+ }
1708
1860
  let add_rule = match kind {
1709
1861
  "cell" => {
1710
- let mut cf =
1711
- ConditionalFormatCell::new().set_rule(cell_rule(ruby, criteria, value)?);
1712
- if let Some(f) = format {
1713
- cf = cf.set_format(&f.0.format);
1714
- }
1715
- rule(range, cf)
1862
+ formatted!(ConditionalFormatCell::new().set_rule(cell_rule(ruby, criteria, value)?))
1716
1863
  }
1717
1864
  "text" => {
1718
1865
  let text = String::try_convert(value)?;
1866
+ check_xml("conditional format text", &text)?;
1719
1867
  let text_rule = match choice(
1720
1868
  ruby,
1721
1869
  "text criteria",
@@ -1732,31 +1880,204 @@ impl Worksheet {
1732
1880
  2 => ConditionalFormatTextRule::BeginsWith(text),
1733
1881
  _ => ConditionalFormatTextRule::EndsWith(text),
1734
1882
  };
1735
- let mut cf = ConditionalFormatText::new().set_rule(text_rule);
1736
- if let Some(f) = format {
1737
- cf = cf.set_format(&f.0.format);
1738
- }
1739
- rule(range, cf)
1883
+ formatted!(ConditionalFormatText::new().set_rule(text_rule))
1884
+ }
1885
+ "formula" => formatted!(
1886
+ ConditionalFormatFormula::new().set_rule(String::try_convert(value)?.as_str())
1887
+ ),
1888
+ "top" | "bottom" => {
1889
+ let percent = raw_opt(ruby, options, "percent").to_bool();
1890
+ let max = if percent { 100.0 } else { 1000.0 };
1891
+ let n = if value.is_nil() {
1892
+ 10
1893
+ } else {
1894
+ whole(value, &format!("{kind} value"), 1.0..=max, &format!("use 1..{max}"))?
1895
+ };
1896
+ let top_rule = match (kind, percent) {
1897
+ ("top", false) => ConditionalFormatTopRule::Top(n),
1898
+ ("top", true) => ConditionalFormatTopRule::TopPercent(n),
1899
+ (_, false) => ConditionalFormatTopRule::Bottom(n),
1900
+ (_, true) => ConditionalFormatTopRule::BottomPercent(n),
1901
+ };
1902
+ formatted!(ConditionalFormatTop::new().set_rule(top_rule))
1903
+ }
1904
+ "average" => {
1905
+ use ConditionalFormatAverageRule as A;
1906
+ // The rule without std_dev, and its 1, 2 and 3 std_dev variants.
1907
+ let above = (
1908
+ A::AboveAverage,
1909
+ Some([
1910
+ A::OneStandardDeviationAbove,
1911
+ A::TwoStandardDeviationsAbove,
1912
+ A::ThreeStandardDeviationsAbove,
1913
+ ]),
1914
+ );
1915
+ let (plain, deviations) = if criteria.is_nil() {
1916
+ above
1917
+ } else {
1918
+ choice(
1919
+ ruby,
1920
+ "average criteria",
1921
+ criteria,
1922
+ &[
1923
+ ("above", above),
1924
+ (
1925
+ "below",
1926
+ (
1927
+ A::BelowAverage,
1928
+ Some([
1929
+ A::OneStandardDeviationBelow,
1930
+ A::TwoStandardDeviationsBelow,
1931
+ A::ThreeStandardDeviationsBelow,
1932
+ ]),
1933
+ ),
1934
+ ),
1935
+ ("above_or_equal", (A::EqualOrAboveAverage, None)),
1936
+ ("below_or_equal", (A::EqualOrBelowAverage, None)),
1937
+ ],
1938
+ )?
1939
+ };
1940
+ let std_dev = raw_opt(ruby, options, "std_dev");
1941
+ let hint = "use 1, 2 or 3, with criteria :above or :below";
1942
+ let average_rule = match (std_dev.is_nil(), deviations) {
1943
+ (true, _) => plain,
1944
+ (false, Some([one, two, three])) => {
1945
+ match whole(std_dev, "std_dev", 1.0..=3.0, hint)? {
1946
+ 1 => one,
1947
+ 2 => two,
1948
+ _ => three,
1949
+ }
1950
+ }
1951
+ (false, None) => {
1952
+ return Err(Error::new(
1953
+ ruby.exception_arg_error(),
1954
+ format!("invalid std_dev {}: {hint}", std_dev.inspect()),
1955
+ ))
1956
+ }
1957
+ };
1958
+ formatted!(ConditionalFormatAverage::new().set_rule(average_rule))
1959
+ }
1960
+ "duplicate" => formatted!(ConditionalFormatDuplicate::new()),
1961
+ "unique" => formatted!(ConditionalFormatDuplicate::new().invert()),
1962
+ "blank" => formatted!(ConditionalFormatBlank::new()),
1963
+ "not_blank" => formatted!(ConditionalFormatBlank::new().invert()),
1964
+ "error" => formatted!(ConditionalFormatError::new()),
1965
+ "not_error" => formatted!(ConditionalFormatError::new().invert()),
1966
+ "date" => {
1967
+ use ConditionalFormatDateRule as D;
1968
+ let period = choice(
1969
+ ruby,
1970
+ "date criteria",
1971
+ criteria,
1972
+ &[
1973
+ ("yesterday", D::Yesterday),
1974
+ ("today", D::Today),
1975
+ ("tomorrow", D::Tomorrow),
1976
+ ("last_7_days", D::Last7Days),
1977
+ ("last_week", D::LastWeek),
1978
+ ("this_week", D::ThisWeek),
1979
+ ("next_week", D::NextWeek),
1980
+ ("last_month", D::LastMonth),
1981
+ ("this_month", D::ThisMonth),
1982
+ ("next_month", D::NextMonth),
1983
+ ],
1984
+ )?;
1985
+ formatted!(ConditionalFormatDate::new().set_rule(period))
1740
1986
  }
1741
- "formula" => {
1742
- let mut cf =
1743
- ConditionalFormatFormula::new().set_rule(String::try_convert(value)?.as_str());
1744
- if let Some(f) = format {
1745
- cf = cf.set_format(&f.0.format);
1987
+ "data_bar" => {
1988
+ let bar = ConditionalFormatDataBar::new();
1989
+ match raw_opt(ruby, options, "color") {
1990
+ c if c.is_nil() => rule(range, bar),
1991
+ c => rule(range, bar.set_fill_color(new_color(c)?)),
1746
1992
  }
1747
- rule(range, cf)
1748
1993
  }
1749
- "data_bar" => rule(range, ConditionalFormatDataBar::new()),
1750
- _ => match opt::<u8>(ruby, options, "colors")?.unwrap_or(3) {
1751
- 2 => rule(range, ConditionalFormat2ColorScale::new()),
1752
- 3 => rule(range, ConditionalFormat3ColorScale::new()),
1753
- n => {
1754
- return Err(Error::new(
1994
+ "icon_set" => {
1995
+ use ConditionalFormatIconType as I;
1996
+ let icons = raw_opt(ruby, options, "icons");
1997
+ let icon_type = if icons.is_nil() {
1998
+ I::ThreeTrafficLights
1999
+ } else {
2000
+ choice(
2001
+ ruby,
2002
+ "icons",
2003
+ icons,
2004
+ &[
2005
+ ("three_arrows", I::ThreeArrows),
2006
+ ("three_arrows_gray", I::ThreeArrowsGray),
2007
+ ("three_flags", I::ThreeFlags),
2008
+ ("three_traffic_lights", I::ThreeTrafficLights),
2009
+ ("three_traffic_lights_with_rim", I::ThreeTrafficLightsWithRim),
2010
+ ("three_signs", I::ThreeSigns),
2011
+ ("three_symbols_circled", I::ThreeSymbolsCircled),
2012
+ ("three_symbols", I::ThreeSymbols),
2013
+ ("three_stars", I::ThreeStars),
2014
+ ("three_triangles", I::ThreeTriangles),
2015
+ ("four_arrows", I::FourArrows),
2016
+ ("four_arrows_gray", I::FourArrowsGray),
2017
+ ("four_red_to_black", I::FourRedToBlack),
2018
+ ("four_histograms", I::FourHistograms),
2019
+ ("four_traffic_lights", I::FourTrafficLights),
2020
+ ("five_arrows", I::FiveArrows),
2021
+ ("five_arrows_gray", I::FiveArrowsGray),
2022
+ ("five_histograms", I::FiveHistograms),
2023
+ ("five_quadrants", I::FiveQuadrants),
2024
+ ("five_boxes", I::FiveBoxes),
2025
+ ],
2026
+ )?
2027
+ };
2028
+ rule(
2029
+ range,
2030
+ ConditionalFormatIconSet::new()
2031
+ .set_icon_type(icon_type)
2032
+ .reverse_icons(flag("reverse")?)
2033
+ .show_icons_only(flag("icons_only")?),
2034
+ )
2035
+ }
2036
+ _ => {
2037
+ // colors: is how many (2 or 3), or the colors from minimum to maximum.
2038
+ let colors = raw_opt(ruby, options, "colors");
2039
+ let list = match RArray::from_value(colors) {
2040
+ Some(items) => {
2041
+ let mut list = Vec::with_capacity(items.len());
2042
+ each_entry(items, |_, c| {
2043
+ list.push(new_color(c)?);
2044
+ Ok(())
2045
+ })?;
2046
+ Some(list)
2047
+ }
2048
+ None => None,
2049
+ };
2050
+ let invalid = || {
2051
+ Error::new(
1755
2052
  ruby.exception_arg_error(),
1756
- format!("invalid colors {n}: use 2 or 3"),
1757
- ))
2053
+ format!(
2054
+ "invalid colors {}: use 2 or 3, or an Array of 2 or 3 colors",
2055
+ colors.inspect()
2056
+ ),
2057
+ )
2058
+ };
2059
+ match list.as_deref() {
2060
+ Some(&[min, max]) => rule(
2061
+ range,
2062
+ ConditionalFormat2ColorScale::new()
2063
+ .set_minimum_color(min)
2064
+ .set_maximum_color(max),
2065
+ ),
2066
+ Some(&[min, mid, max]) => rule(
2067
+ range,
2068
+ ConditionalFormat3ColorScale::new()
2069
+ .set_minimum_color(min)
2070
+ .set_midpoint_color(mid)
2071
+ .set_maximum_color(max),
2072
+ ),
2073
+ Some(_) => return Err(invalid()),
2074
+ None => match opt::<u8>(ruby, options, "colors")?.unwrap_or(3) {
2075
+ 2 => rule(range, ConditionalFormat2ColorScale::new()),
2076
+ 3 => rule(range, ConditionalFormat3ColorScale::new()),
2077
+ _ => return Err(invalid()),
2078
+ },
1758
2079
  }
1759
- },
2080
+ }
1760
2081
  };
1761
2082
  rb_self.with_ws(|ws| add_rule(ws).map_err(xerr))?;
1762
2083
  Ok(rb_self)
@@ -1828,6 +2149,7 @@ impl Worksheet {
1828
2149
  ("error_message", DataValidation::set_error_message),
1829
2150
  ] {
1830
2151
  if let Some(text) = opt::<String>(ruby, options, name)? {
2152
+ check_xml(name, &text)?;
1831
2153
  dv = set(dv, text).map_err(xerr)?;
1832
2154
  }
1833
2155
  }
@@ -1880,6 +2202,7 @@ impl Worksheet {
1880
2202
  };
1881
2203
  let width = positive("width")?;
1882
2204
  let height = positive("height")?;
2205
+ let (mut scale_w, mut scale_h) = (1.0, 1.0);
1883
2206
  if let Some(scale) = positive("scale")? {
1884
2207
  if width.is_some() || height.is_some() {
1885
2208
  return Err(Error::new(
@@ -1887,18 +2210,29 @@ impl Worksheet {
1887
2210
  "pass either scale: or width:/height:, not both",
1888
2211
  ));
1889
2212
  }
1890
- image = image.set_scale_width(scale).set_scale_height(scale);
2213
+ (scale_w, scale_h) = (scale, scale);
1891
2214
  } else if width.is_some() || height.is_some() {
1892
2215
  // Displayed size at scale 1, as rust_xlsxwriter computes it from the DPI.
1893
2216
  let natural_w = image.width() * 96.0 / image.width_dpi();
1894
2217
  let natural_h = image.height() * 96.0 / image.height_dpi();
1895
- let scale_w = width.map(|w| w / natural_w);
1896
- let scale_h = height.map(|h| h / natural_h);
2218
+ let sw = width.map(|w| w / natural_w);
2219
+ let sh = height.map(|h| h / natural_h);
1897
2220
  // With only one dimension, scale the other by the same factor.
1898
- let (sw, sh) = (scale_w.or(scale_h).unwrap(), scale_h.or(scale_w).unwrap());
1899
- image = image.set_scale_width(sw).set_scale_height(sh);
2221
+ (scale_w, scale_h) = (sw.or(sh).unwrap(), sh.or(sw).unwrap());
2222
+ }
2223
+ // The size comes from the image's own header, and saving walks every
2224
+ // row and column the image covers, with no way to interrupt it.
2225
+ let shown_w = image.width() * 96.0 / image.width_dpi() * scale_w;
2226
+ let shown_h = image.height() * 96.0 / image.height_dpi() * scale_h;
2227
+ if !(shown_w <= MAX_IMAGE_WIDTH && shown_h <= MAX_IMAGE_HEIGHT) {
2228
+ return Err(Error::new(
2229
+ ruby.get_inner(&ERROR),
2230
+ format!("image is too large for a worksheet: {shown_w} x {shown_h} pixels"),
2231
+ ));
1900
2232
  }
2233
+ image = image.set_scale_width(scale_w).set_scale_height(scale_h);
1901
2234
  if let Some(alt_text) = opt::<String>(ruby, options, "alt_text")? {
2235
+ check_xml("alt_text", &alt_text)?;
1902
2236
  image = image.set_alt_text(alt_text);
1903
2237
  }
1904
2238
  let x = opt::<u32>(ruby, options, "x_offset")?.unwrap_or(0);
@@ -1911,6 +2245,54 @@ impl Worksheet {
1911
2245
  Ok(rb_self)
1912
2246
  }
1913
2247
 
2248
+ fn embed_image(
2249
+ ruby: &Ruby,
2250
+ rb_self: Obj<Self>,
2251
+ row: u32,
2252
+ col: u16,
2253
+ bytes: RString,
2254
+ alt_text: Option<String>,
2255
+ format: Option<&Format>,
2256
+ ) -> Result<Obj<Self>, Error> {
2257
+ // rust_xlsxwriter numbers embedded images only when saving, and panics
2258
+ // if it writes the cell to disk before that.
2259
+ if rb_self.flushes_rows {
2260
+ return Err(Error::new(
2261
+ ruby.get_inner(&ERROR),
2262
+ "embed_image is not supported in constant_memory / low_memory mode",
2263
+ ));
2264
+ }
2265
+ // SAFETY: the bytes are copied into the Image before any Ruby code runs.
2266
+ let mut image = Image::new_from_buffer(unsafe { bytes.as_slice() }).map_err(xerr)?;
2267
+ if let Some(alt_text) = alt_text {
2268
+ image = image.set_alt_text(alt_text);
2269
+ }
2270
+ let tables = rb_self.table_formats.borrow();
2271
+ let rows = rb_self.formatted_rows.borrow();
2272
+ let columns = rb_self.formatted_columns.borrow();
2273
+ // As in write(): an image is never a date, so with no format of its
2274
+ // own it takes its table column's, if any.
2275
+ let format = Self::format_for(
2276
+ &tables,
2277
+ &rows,
2278
+ &columns,
2279
+ row,
2280
+ col,
2281
+ format.map(|f| &*f.0),
2282
+ &CellValue::Empty,
2283
+ );
2284
+ rb_self.with_ws(|ws| {
2285
+ match format {
2286
+ Some(f) => ws.embed_image_with_format(row, col, &image, f),
2287
+ None => ws.embed_image(row, col, &image),
2288
+ }
2289
+ .map(|_| ())
2290
+ .map_err(xerr)
2291
+ })?;
2292
+ rb_self.advance(row);
2293
+ Ok(rb_self)
2294
+ }
2295
+
1914
2296
  fn insert_chart(
1915
2297
  ruby: &Ruby,
1916
2298
  rb_self: Obj<Self>,
@@ -1950,19 +2332,19 @@ impl Worksheet {
1950
2332
  if let Some(categories) = opt::<String>(ruby, s, "categories")? {
1951
2333
  cs.set_categories(categories.as_str());
1952
2334
  }
1953
- if let Some(name) = opt::<String>(ruby, s, "name")? {
1954
- cs.set_name(name.as_str());
2335
+ if let Some(name) = opt::<Value>(ruby, s, "name")? {
2336
+ cs.set_name(chart_label(ruby, name)?.as_str());
1955
2337
  }
1956
2338
  Ok(())
1957
2339
  })?;
1958
- if let Some(title) = opt::<String>(ruby, options, "title")? {
1959
- chart.title().set_name(title.as_str());
2340
+ if let Some(title) = opt::<Value>(ruby, options, "title")? {
2341
+ chart.title().set_name(chart_label(ruby, title)?.as_str());
1960
2342
  }
1961
- if let Some(name) = opt::<String>(ruby, options, "x_axis")? {
1962
- chart.x_axis().set_name(name.as_str());
2343
+ if let Some(name) = opt::<Value>(ruby, options, "x_axis")? {
2344
+ chart.x_axis().set_name(chart_label(ruby, name)?.as_str());
1963
2345
  }
1964
- if let Some(name) = opt::<String>(ruby, options, "y_axis")? {
1965
- chart.y_axis().set_name(name.as_str());
2346
+ if let Some(name) = opt::<Value>(ruby, options, "y_axis")? {
2347
+ chart.y_axis().set_name(chart_label(ruby, name)?.as_str());
1966
2348
  }
1967
2349
  if let Some(width) = opt::<u32>(ruby, options, "width")? {
1968
2350
  chart.set_width(width);
@@ -2287,6 +2669,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
2287
2669
  ws.define_method("name", method!(Worksheet::name, 0))?;
2288
2670
  ws.define_method("_write_comment", method!(Worksheet::write_comment, 4))?;
2289
2671
  ws.define_method("_insert_image", method!(Worksheet::insert_image, 4))?;
2672
+ ws.define_method("_embed_image", method!(Worksheet::embed_image, 5))?;
2290
2673
  ws.define_method("_insert_chart", method!(Worksheet::insert_chart, 3))?;
2291
2674
  ws.define_method("_add_table", method!(Worksheet::add_table, 5))?;
2292
2675
  ws.define_method(
@@ -2,5 +2,5 @@
2
2
 
3
3
  module FastXlsx
4
4
  # The gem version.
5
- VERSION = "1.0.0"
5
+ VERSION = "1.2.0"
6
6
  end
data/lib/fast_xlsx.rb CHANGED
@@ -269,6 +269,13 @@ module FastXlsx
269
269
  end
270
270
  private :_write_ref
271
271
 
272
+ # [row, col, image bytes] from insert_image's and embed_image's (*cell, source).
273
+ def image_args(args)
274
+ row, col, (source, *) = CellRange.cell(args, 1..1)
275
+ [row, col, source.respond_to?(:read) ? source.read : File.binread(source)]
276
+ end
277
+ private :image_args
278
+
272
279
  # Writes one cell: ws["B2"] = 42 or ws[1, 1] = 42. Use {#write} to give
273
280
  # it a format.
274
281
  # @overload []=(ref, value)
@@ -330,14 +337,30 @@ module FastXlsx
330
337
  # Highlights cells in the range by rule; see the README for each type's
331
338
  # options.
332
339
  # @param range a cell range (see {Worksheet})
333
- # @param type [Symbol] :cell, :text, :formula, :data_bar or :color_scale
334
- # @option options [Symbol] :criteria e.g. :>, :between, :contains
335
- # @option options [Numeric, String, Array] :value
340
+ # @param type [Symbol] :cell, :text, :formula, :top, :bottom, :average,
341
+ # :duplicate, :unique, :blank, :not_blank, :error, :not_error, :date,
342
+ # :data_bar, :color_scale or :icon_set
343
+ # @option options [Symbol] :criteria e.g. :>, :between, :contains,
344
+ # :below (:average), :last_7_days (:date)
345
+ # @option options [Numeric, String, Array] :value (:top and :bottom: how many, default 10)
336
346
  # @option options [Format, Hash] :format
337
- # @option options [Integer] :colors 2 or 3 (:color_scale)
347
+ # @option options [Boolean] :percent value is a percentage (:top, :bottom)
348
+ # @option options [Integer] :std_dev 1, 2 or 3 standard deviations (:average)
349
+ # @option options [Integer, Array] :colors 2 or 3, or the 2 or 3 colors
350
+ # ("#RRGGBB" or 0xRRGGBB) from minimum to maximum (:color_scale)
351
+ # @option options [String, Integer] :color bar fill and border color,
352
+ # "#RRGGBB" or 0xRRGGBB (:data_bar)
353
+ # @option options [Symbol] :icons e.g. :three_arrows, :five_boxes; default
354
+ # :three_traffic_lights (:icon_set)
355
+ # @option options [Boolean] :reverse reverse the order of the icons (:icon_set)
356
+ # @option options [Boolean] :icons_only hide the cell values (:icon_set)
338
357
  # @return [self]
339
358
  def conditional_format(*range, type:, **options)
340
359
  options[:format] = Format._coerce(options[:format]) if options.key?(:format)
360
+ if type == :data_bar && options.key?(:colors)
361
+ warn "fast_xlsx: colors: is ignored on :data_bar and will raise in 2.0; use color:", uplevel: 1
362
+ options.delete(:colors)
363
+ end
341
364
  _conditional_format(*CellRange.split(range).first, { type: type, **options })
342
365
  end
343
366
 
@@ -368,11 +391,23 @@ module FastXlsx
368
391
  # @option options [Integer] :x_offset, :y_offset pixels
369
392
  # @option options [String] :alt_text
370
393
  # @return [self]
371
- # @raise [FastXlsx::Error] for data that isn't a supported image
394
+ # @raise [FastXlsx::Error] for data that isn't a supported image, or an
395
+ # image that would be larger than a worksheet
372
396
  def insert_image(*args, **)
373
- row, col, (source, *) = CellRange.cell(args, 1..1)
374
- bytes = source.respond_to?(:read) ? source.read : File.binread(source)
375
- _insert_image(row, col, bytes, { ** })
397
+ _insert_image(*image_args(args), { ** })
398
+ end
399
+
400
+ # Embeds a PNG, JPEG, GIF or BMP image in the cell, where it fits the cell
401
+ # and moves and sizes with it (Excel 365's "Place in Cell"; older Excel
402
+ # shows #VALUE!). Not available in memory: :constant or :low mode.
403
+ # @overload embed_image(*cell, source, alt_text: nil, format: nil)
404
+ # @param source [String, #read] a file path or an IO
405
+ # @param alt_text [String, nil]
406
+ # @param format [Format, Hash, nil] the cell's format, e.g. to center the image
407
+ # @return [self]
408
+ # @raise [FastXlsx::Error] for data that isn't a supported image, or in those modes
409
+ def embed_image(*args, alt_text: nil, format: nil)
410
+ _embed_image(*image_args(args), alt_text, Format._coerce(format))
376
411
  end
377
412
 
378
413
  # Inserts a chart with its top-left corner in the cell.
@@ -381,7 +416,9 @@ module FastXlsx
381
416
  # :radar, :scatter, and the stacked variants
382
417
  # @param series [Array<Hash>] { values:, categories:, name: } with ranges
383
418
  # such as "Sheet1!$B$2:$B$13"
384
- # @option options [String] :title, :x_axis, :y_axis
419
+ # @option options [String, Formula] :title, :x_axis, :y_axis text; these and a
420
+ # series name: take a {Formula} such as "Sheet1!$A$1" to show a cell instead
421
+ # @raise [ArgumentError] for text that Excel would read as a cell reference
385
422
  # @option options [Integer] :width, :height pixels
386
423
  # @return [self]
387
424
  def insert_chart(*cell, type:, series:, **)
data/sig/fast_xlsx.rbs CHANGED
@@ -124,9 +124,18 @@ module FastXlsx
124
124
  | (indexes rows, indexes cols, cell value, ?format? format) -> self
125
125
  | (*cell_range | cell args, format: format?) -> self
126
126
  def conditional_format: (*cell_range range,
127
- type: :cell | :text | :formula | :data_bar | :color_scale,
127
+ type: :cell | :text | :formula | :top | :bottom | :average | :duplicate | :unique
128
+ | :blank | :not_blank | :error | :not_error | :date | :data_bar | :color_scale
129
+ | :icon_set,
128
130
  ?criteria: Symbol, ?value: Numeric | String | Array[Numeric | String],
129
- ?format: format, ?colors: 2 | 3) -> self
131
+ ?format: format, ?percent: bool, ?std_dev: 1 | 2 | 3,
132
+ ?colors: 2 | 3 | Array[Format::color], ?color: Format::color,
133
+ ?icons: icon_type, ?reverse: bool, ?icons_only: bool) -> self
134
+ type icon_type = :three_arrows | :three_arrows_gray | :three_flags | :three_traffic_lights
135
+ | :three_traffic_lights_with_rim | :three_signs | :three_symbols_circled | :three_symbols
136
+ | :three_stars | :three_triangles | :four_arrows | :four_arrows_gray | :four_red_to_black
137
+ | :four_histograms | :four_traffic_lights | :five_arrows | :five_arrows_gray
138
+ | :five_histograms | :five_quadrants | :five_boxes
130
139
  def data_validation: (*cell_range range,
131
140
  type: :list | :whole_number | :decimal | :text_length,
132
141
  ?criteria: Symbol, ?value: Numeric | String | Array[Numeric | String],
@@ -138,13 +147,15 @@ module FastXlsx
138
147
  ?x_offset: Integer, ?y_offset: Integer, ?alt_text: String) -> self
139
148
  | (String cell, String | _Reader source, ?scale: Numeric, ?width: Numeric, ?height: Numeric,
140
149
  ?x_offset: Integer, ?y_offset: Integer, ?alt_text: String) -> self
141
- type chart_series = { values: String, ?categories: String, ?name: String }
150
+ def embed_image: (Integer row, Integer col, String | _Reader source, ?alt_text: String?, ?format: format?) -> self
151
+ | (String cell, String | _Reader source, ?alt_text: String?, ?format: format?) -> self
152
+ type chart_series = { values: String, ?categories: String, ?name: String | Formula }
142
153
 
143
154
  def insert_chart: (Integer row, Integer col, type: Symbol, series: Array[chart_series],
144
- ?title: String, ?x_axis: String, ?y_axis: String,
155
+ ?title: String | Formula, ?x_axis: String | Formula, ?y_axis: String | Formula,
145
156
  ?width: Integer, ?height: Integer) -> self
146
157
  | (String cell, type: Symbol, series: Array[chart_series],
147
- ?title: String, ?x_axis: String, ?y_axis: String,
158
+ ?title: String | Formula, ?x_axis: String | Formula, ?y_axis: String | Formula,
148
159
  ?width: Integer, ?height: Integer) -> self
149
160
  type table_column = String | { header: String, ?total: Symbol, ?total_label: String, ?format: format }
150
161
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: fast_xlsx
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Zac