-
Notifications
You must be signed in to change notification settings - Fork 44
/
mod.rs
1699 lines (1604 loc) · 59.3 KB
/
mod.rs
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
mod table;
mod validation;
use super::{convert_bool, Chart, Format, FormatColor, Workbook, XlsxError};
use std::ffi::CString;
use std::os::raw::c_char;
pub use table::*;
pub use validation::*;
#[derive(Debug, Clone, PartialEq, PartialOrd, Default)]
pub struct DateTime {
pub year: i16,
pub month: i8,
pub day: i8,
pub hour: i8,
pub min: i8,
pub second: f64,
}
impl DateTime {
pub fn new(year: i16, month: i8, day: i8, hour: i8, min: i8, second: f64) -> DateTime {
DateTime {
year,
month,
day,
hour,
min,
second,
}
}
}
impl From<&DateTime> for libxlsxwriter_sys::lxw_datetime {
fn from(datetime: &DateTime) -> Self {
libxlsxwriter_sys::lxw_datetime {
year: datetime.year.into(),
month: datetime.month.into(),
day: datetime.day.into(),
hour: datetime.hour.into(),
min: datetime.min.into(),
sec: datetime.second,
}
}
}
/// Options for modifying images inserted via [Worksheet.insert_image_opt()](struct.Worksheet.html#method.insert_image_opt).
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct ImageOptions {
/// Offset from the left of the cell in pixels.
pub x_offset: i32,
/// Offset from the top of the cell in pixels.
pub y_offset: i32,
/// X scale of the image as a decimal.
pub x_scale: f64,
/// Y scale of the image as a decimal.
pub y_scale: f64,
}
impl From<&ImageOptions> for libxlsxwriter_sys::lxw_image_options {
fn from(options: &ImageOptions) -> Self {
libxlsxwriter_sys::lxw_image_options {
x_offset: options.x_offset,
y_offset: options.y_offset,
x_scale: options.x_scale,
y_scale: options.y_scale,
description: std::ptr::null_mut(),
url: std::ptr::null_mut(),
tip: std::ptr::null_mut(),
object_position: 0,
decorative: 0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum PaperType {
PrinterDefault,
Letter,
Tabloid,
Ledger,
Legal,
Statement,
Executive,
A3,
A4,
A5,
B4,
B5,
Folio,
Quarto,
Other(u8),
}
impl PaperType {
fn value(self) -> u8 {
let value = match self {
PaperType::PrinterDefault => 0,
PaperType::Letter => 1,
PaperType::Tabloid => 3,
PaperType::Ledger => 4,
PaperType::Legal => 5,
PaperType::Statement => 6,
PaperType::Executive => 7,
PaperType::A3 => 8,
PaperType::A4 => 9,
PaperType::A5 => 11,
PaperType::B4 => 12,
PaperType::B5 => 13,
PaperType::Folio => 14,
PaperType::Quarto => 15,
PaperType::Other(x) => x.into(),
};
value as u8
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct HeaderFooterOptions {
pub margin: f64,
}
impl From<&HeaderFooterOptions> for libxlsxwriter_sys::lxw_header_footer_options {
fn from(options: &HeaderFooterOptions) -> libxlsxwriter_sys::lxw_header_footer_options {
libxlsxwriter_sys::lxw_header_footer_options {
margin: options.margin,
image_left: std::ptr::null_mut(),
image_center: std::ptr::null_mut(),
image_right: std::ptr::null_mut(),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub enum GridLines {
HideAllGridLines,
ShowScreenGridLines,
ShowPrintGridLines,
ShowAllGridLines,
}
impl GridLines {
fn value(self) -> u8 {
let value = match self {
GridLines::HideAllGridLines => libxlsxwriter_sys::lxw_gridlines_LXW_HIDE_ALL_GRIDLINES,
GridLines::ShowScreenGridLines => {
libxlsxwriter_sys::lxw_gridlines_LXW_SHOW_SCREEN_GRIDLINES
}
GridLines::ShowPrintGridLines => {
libxlsxwriter_sys::lxw_gridlines_LXW_SHOW_PRINT_GRIDLINES
}
GridLines::ShowAllGridLines => libxlsxwriter_sys::lxw_gridlines_LXW_SHOW_ALL_GRIDLINES,
};
value as u8
}
}
#[derive(Debug, Copy, Clone, PartialEq, PartialOrd)]
pub struct Protection {
pub no_select_locked_cells: bool,
pub no_select_unlocked_cells: bool,
pub format_cells: bool,
pub format_columns: bool,
pub format_rows: bool,
pub insert_columns: bool,
pub insert_rows: bool,
pub insert_hyperlinks: bool,
pub delete_columns: bool,
pub delete_rows: bool,
pub sort: bool,
pub autofilter: bool,
pub pivot_tables: bool,
pub scenarios: bool,
pub objects: bool,
pub no_content: bool,
pub no_objects: bool,
}
impl Protection {
pub fn new() -> Protection {
Protection {
no_select_locked_cells: true,
no_select_unlocked_cells: true,
format_cells: false,
format_columns: false,
format_rows: false,
insert_columns: false,
insert_rows: false,
insert_hyperlinks: false,
delete_columns: false,
delete_rows: false,
sort: false,
autofilter: false,
pivot_tables: false,
scenarios: false,
objects: false,
no_content: false,
no_objects: false,
}
}
}
impl Default for Protection {
fn default() -> Self {
Protection::new()
}
}
impl From<&Protection> for libxlsxwriter_sys::lxw_protection {
fn from(protection: &Protection) -> libxlsxwriter_sys::lxw_protection {
libxlsxwriter_sys::lxw_protection {
no_select_locked_cells: convert_bool(protection.no_select_locked_cells),
no_select_unlocked_cells: convert_bool(protection.no_select_unlocked_cells),
format_cells: convert_bool(protection.format_cells),
format_columns: convert_bool(protection.format_columns),
format_rows: convert_bool(protection.format_rows),
insert_columns: convert_bool(protection.insert_columns),
insert_rows: convert_bool(protection.insert_rows),
insert_hyperlinks: convert_bool(protection.insert_hyperlinks),
delete_columns: convert_bool(protection.delete_columns),
delete_rows: convert_bool(protection.delete_rows),
sort: convert_bool(protection.sort),
autofilter: convert_bool(protection.autofilter),
pivot_tables: convert_bool(protection.pivot_tables),
scenarios: convert_bool(protection.scenarios),
objects: convert_bool(protection.objects),
no_content: convert_bool(protection.no_content),
no_objects: convert_bool(protection.no_objects),
}
}
}
/// Integer data type to represent a column value. Equivalent to `u16`.
///
/// The maximum column in Excel is 16,384.
pub type WorksheetCol = libxlsxwriter_sys::lxw_col_t;
/// Integer data type to represent a row value. Equivalent to `u32`.
///
/// The maximum row in Excel is 1,048,576.
pub type WorksheetRow = libxlsxwriter_sys::lxw_row_t;
pub type CommentOptions = libxlsxwriter_sys::lxw_comment_options;
pub type RowColOptions = libxlsxwriter_sys::lxw_row_col_options;
pub const LXW_DEF_ROW_HEIGHT: f64 = 8.43;
pub const LXW_DEF_ROW_HEIGHT_PIXELS: u32 = 20;
pub const LXW_DEF_COL_WIDTH: f64 = 15.0;
pub const LXW_DEF_COL_WIDTH_PIXELS: u32 = 64;
/// The Worksheet object represents an Excel worksheet. It handles operations such as writing data to cells or formatting worksheet layout.
///
/// A Worksheet object isn't created directly. Instead a worksheet is created by calling the `workbook.add_worksheet()` function from a [Workbook](struct.Workbook.html) object:
/// ```rust
/// use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// let workbook = Workbook::new("test-worksheet.xlsx");
/// let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_string(0, 0, "Hello, excel", None)?;
/// workbook.close()
/// # }
/// ```
/// Please read [original libxlsxwriter document](https://libxlsxwriter.github.io/worksheet_8h.html) for description missing functions.
/// Most of this document is based on libxlsxwriter document.
pub struct Worksheet<'a> {
pub(crate) _workbook: &'a Workbook,
pub(crate) worksheet: *mut libxlsxwriter_sys::lxw_worksheet,
}
impl<'a> Worksheet<'a> {
/// This function writes the comment of a cell
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_comment-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_comment(0, 0, "This is some comment text")?;
/// worksheet.write_comment(1, 0, "This cell also has a comment")?;
/// # workbook.close()
/// # }
/// ```
pub fn write_comment(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
text: &str,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_comment(
self.worksheet,
row,
col,
CString::new(text).unwrap().as_c_str().as_ptr(),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
pub fn write_comment_opt(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
text: &str,
options: &mut CommentOptions,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_comment_opt(
self.worksheet,
row,
col,
CString::new(text).unwrap().as_c_str().as_ptr(),
options,
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function writes numeric types to the cell specified by row and column:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_number-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_number(0, 0, 123456.0, None)?;
/// worksheet.write_number(1, 0, 2.3451, None)?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_number-1.png)
///
/// The native data type for all numbers in Excel is a IEEE-754 64-bit double-precision floating point, which is also the default type used by worksheet_write_number.
///
/// The format parameter is used to apply formatting to the cell. This parameter can be `None` to indicate no formatting or it can be a Format object.
///
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_number-2.xlsx");
/// let format = workbook.add_format()
/// .set_num_format("$#,##0.00");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_number(0, 0, 1234.567, Some(&format))?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_number-2.png)
///
/// ### Note
/// Excel doesn't support NaN, Inf or -Inf as a number value. If you are writing data that contains these values then your application should convert them to a string or handle them in some other way.
pub fn write_number(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
number: f64,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_number(
self.worksheet,
row,
col,
number,
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function writes a string to the cell specified by row and column:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_string-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_string(0, 0, "This phrase is English!", None)?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_string-1.png)
///
/// The format parameter is used to apply formatting to the cell. This parameter can be `None` to indicate no formatting or it can be a Format object:
///
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_string-2.xlsx");
/// let format = workbook.add_format()
/// .set_bold();
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_string(0, 0, "This phrase is Bold!", Some(&format))?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_string-2.png)
///
/// Unicode strings are supported in UTF-8 encoding.
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_string-3.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_string(0, 0, "こんにちは、世界!", None)?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_string-3.png)
pub fn write_string(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
text: &str,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_string(
self.worksheet,
row,
col,
CString::new(text).unwrap().as_c_str().as_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function writes a formula or function to the cell specified by row and column:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_formula-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_formula(0, 0, "=B3 + 6", None)?;
/// worksheet.write_formula(1, 0, "=SIN(PI()/4)", None)?;
/// worksheet.write_formula(2, 0, "=SUM(A1:A2)", None)?;
/// worksheet.write_formula(3, 0, "=IF(A3>1,\"Yes\", \"No\")", None)?;
/// worksheet.write_formula(4, 0, "=AVERAGE(1, 2, 3, 4)", None)?;
/// worksheet.write_formula(5, 0, "=DATEVALUE(\"1-Jan-2013\")", None)?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_formula-1.png)
///
/// The `format` parameter is used to apply formatting to the cell. This parameter can be `None` to indicate no formatting or it can be a Format object.
///
/// Libxlsxwriter doesn't calculate the value of a formula and instead stores a default value of `0`. The correct formula result is displayed in Excel, as shown in the example above, since it recalculates the formulas when it loads the file. For cases where this is an issue see the `write_formula_num()` function and the discussion in that section.
///
/// Formulas must be written with the US style separator/range operator which is a comma (not semi-colon). Therefore a formula with multiple values should be written as follows:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_formula-2.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// // OK
/// worksheet.write_formula(0, 0, "=SUM(1, 2, 3)", None)?;
/// // NO. Error on load.
/// worksheet.write_formula(1, 0, "=SUM(1; 2; 3)", None)?;
/// # workbook.close()
/// # }
/// ```
/// See also [Working with Formulas](https://libxlsxwriter.github.io/working_with_formulas.html).
pub fn write_formula(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
formula: &str,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_formula(
self.worksheet,
row,
col,
CString::new(formula).unwrap().as_c_str().as_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function writes an array formula to a cell range. In Excel an array formula is a formula that performs a calculation on a set of values.
/// In Excel an array formula is indicated by a pair of braces around the formula: `{=SUM(A1:B1*A2:B2)}`.
///
/// Array formulas can return a single value or a range or values. For array formulas that return a range of values you must specify the range that the return values will be written to. This is why this function has first_ and last_ row/column parameters:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_array_formula-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_array_formula(4, 0, 6, 0, "{=TREND(C5:C7,B5:B7)}", None)?;
/// # workbook.close()
/// # }
/// ```
/// If the array formula returns a single value then the first_ and last_ parameters should be the same:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_array_formula-2.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_array_formula(1, 0, 1, 0, "{=SUM(B1:C1*B2:C2)}", None)?;
/// # workbook.close()
/// # }
/// ```
pub fn write_array_formula(
&mut self,
first_row: WorksheetRow,
first_col: WorksheetCol,
last_row: WorksheetRow,
last_col: WorksheetCol,
formula: &str,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_array_formula(
self.worksheet,
first_row,
first_col,
last_row,
last_col,
CString::new(formula).unwrap().as_c_str().as_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function can be used to write a date or time to the cell specified by row and column:
/// ```rust
/// use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_datetime-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// let datetime = DateTime::new(2013, 2, 28, 12, 0, 0.0);
/// let datetime_format = workbook.add_format()
/// .set_num_format("mmm d yyyy hh:mm AM/PM");
/// worksheet.write_datetime(1, 0, &datetime, Some(&datetime_format))?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_datetime-1.png)
///
/// The `format` parameter should be used to apply formatting to the cell using a [Format](struct.Format.html) object as shown above. Without a date format the datetime will appear as a number only.
///
/// See [Working with Dates and Times](https://libxlsxwriter.github.io/working_with_dates.html) for more information about handling dates and times in libxlsxwriter.
pub fn write_datetime(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
datetime: &DateTime,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let mut xls_datetime: libxlsxwriter_sys::lxw_datetime = datetime.into();
let result = libxlsxwriter_sys::worksheet_write_datetime(
self.worksheet,
row,
col,
&mut xls_datetime,
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function is used to write a URL/hyperlink to a worksheet cell specified by row and column.
/// The format parameter is used to apply formatting to the cell. This parameter can be `None` to indicate no formatting or it can be a [Format](struct.Format.html) object. The typical worksheet format for a hyperlink is a blue underline:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_url-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// let url_format = workbook.add_format()
/// .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_url(0, 0, "http://libxlsxwriter.github.io", Some(&url_format))?;
/// # workbook.close()
/// # }
/// ```
///
/// The usual web style URI's are supported: `http://`, `https://`, `ftp://` and `mailto:` :
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_url-2.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// # let mut url_format = workbook.add_format()
/// # .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_url(0, 0, "ftp://www.python.org/", Some(&url_format))?;
/// worksheet.write_url(1, 0, "http://www.python.org/", Some(&url_format))?;
/// worksheet.write_url(2, 0, "https://www.python.org/", Some(&url_format))?;
/// worksheet.write_url(3, 0, "mailto:foo@example.com", Some(&url_format))?;
/// # workbook.close()
/// # }
/// ```
///
/// An Excel hyperlink is comprised of two elements: the displayed string and the non-displayed link. By default the displayed string is the same as the link. However, it is possible to overwrite it with any other libxlsxwriter type using the appropriate `Worksheet.write_*()` function. The most common case is to overwrite the displayed link text with another string:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_url-3.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// # let mut url_format = workbook.add_format()
/// # .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_url(0, 0, "http://libxlsxwriter.github.io", Some(&url_format))?;
/// worksheet.write_string(0, 0, "Read the documentation.", Some(&url_format))?;
/// # workbook.close()
/// # }
/// ```
///
/// Two local URIs are supported: `internal:` and `external:`. These are used for hyperlinks to internal worksheet references or external workbook and worksheet references:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_url-4.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// # let mut worksheet2 = workbook.add_worksheet(None)?;
/// # let mut worksheet3 = workbook.add_worksheet(Some("Sales Data"))?;
/// # let mut url_format = workbook.add_format()
/// # .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_url(0, 0, "internal:Sheet2!A1", Some(&url_format))?;
/// worksheet.write_url(1, 0, "internal:Sheet2!B2", Some(&url_format))?;
/// worksheet.write_url(2, 0, "internal:Sheet2!A1:B2", Some(&url_format))?;
/// worksheet.write_url(3, 0, "internal:'Sales Data'!A1", Some(&url_format))?;
/// worksheet.write_url(4, 0, "external:c:\\temp\\foo.xlsx", Some(&url_format))?;
/// worksheet.write_url(5, 0, "external:c:\\foo.xlsx#Sheet2!A1", Some(&url_format))?;
/// worksheet.write_url(6, 0, "external:..\\foo.xlsx", Some(&url_format))?;
/// worksheet.write_url(7, 0, "external:..\\foo.xlsx#Sheet2!A1", Some(&url_format))?;
/// worksheet.write_url(8, 0, "external:\\\\NET\\share\\foo.xlsx", Some(&url_format))?;
/// # workbook.close()
/// # }
/// ```
pub fn write_url(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
url: &str,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_url(
self.worksheet,
row,
col,
CString::new(url).unwrap().as_c_str().as_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// Write an Excel boolean to the cell specified by row and column:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_boolean-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// worksheet.write_boolean(0, 0, true, None)?;
/// worksheet.write_boolean(1, 0, false, None)?;
/// # workbook.close()
/// # }
/// ```
pub fn write_boolean(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
value: bool,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_boolean(
self.worksheet,
row,
col,
if value { 1 } else { 0 },
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// Write a blank cell specified by row and column:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_blank-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// # let mut url_format = workbook.add_format()
/// # .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_blank(1, 1, Some(&url_format));
/// # workbook.close()
/// # }
/// ```
/// This function is used to add formatting to a cell which doesn't contain a string or number value.
///
/// Excel differentiates between an "Empty" cell and a "Blank" cell. An Empty cell is a cell which doesn't contain data or formatting whilst a Blank cell doesn't contain data but does contain formatting. Excel stores Blank cells but ignores Empty cells.
///
/// As such, if you write an empty cell without formatting it is ignored.
pub fn write_blank(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_blank(
self.worksheet,
row,
col,
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function writes a formula or Excel function to the cell specified by row and column with a user defined numeric result:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_formula_num-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// # let mut url_format = workbook.add_format()
/// # .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_formula_num(1, 1, "=1 + 2", None, 3.0);
/// # workbook.close()
/// # }
/// ```
/// Libxlsxwriter doesn't calculate the value of a formula and instead stores the value 0 as the formula result.
/// It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened.
///
/// This is the method recommended in the Excel documentation and in general it works fine with spreadsheet applications.
///
/// However, applications that don't have a facility to calculate formulas, such as Excel Viewer, or some mobile
/// applications will only display the 0 results.
///
/// If required, the worksheet_write_formula_num() function can be used to specify a formula and its result.
///
/// This function is rarely required and is only provided for compatibility with some third party applications.
/// For most applications the worksheet_write_formula() function is the recommended way of writing formulas.
#[allow(clippy::too_many_arguments)]
pub fn write_formula_num(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
formula: &str,
format: Option<&Format>,
number: f64,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_formula_num(
self.worksheet,
row,
col,
CString::new(formula).unwrap().as_c_str().as_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
number,
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function writes a formula or Excel function to the cell specified by row and column with a user defined string result:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_formula_str-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// # let mut url_format = workbook.add_format()
/// # .set_underline(FormatUnderline::Single).set_font_color(FormatColor::Blue);
/// worksheet.write_formula_str(1, 1, "=\"A\" & \"B\"", None, "AB");
/// # workbook.close()
/// # }
/// ```
/// The worksheet_write_formula_str() function is similar to the worksheet_write_formula_num() function except it
/// writes a string result instead or a numeric result. See worksheet_write_formula_num() for more details on
/// why/when these functions are required.
///
/// One place where the worksheet_write_formula_str() function may be required is to specify an empty result which
/// will force a recalculation of the formula when loaded in LibreOffice.
#[allow(clippy::too_many_arguments)]
pub fn write_formula_str(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
formula: &str,
format: Option<&Format>,
result: &str,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_write_formula_str(
self.worksheet,
row,
col,
CString::new(formula).unwrap().as_c_str().as_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
CString::new(result).unwrap().as_c_str().as_ptr(),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// This function is used to write strings with multiple formats. For example to write the string 'This is bold and this is italic' you would use the following:
/// ```rust
/// # use xlsxwriter::*;
/// # fn main() -> Result<(), XlsxError> {
/// # let workbook = Workbook::new("test-worksheet_write_richtext-1.xlsx");
/// # let mut worksheet = workbook.add_worksheet(None)?;
/// let mut bold = workbook.add_format()
/// .set_bold();
/// let mut italic = workbook.add_format()
/// .set_italic();
/// worksheet.write_rich_string(
/// 0, 0,
/// &[
/// ("This is ", None),
/// ("bold", Some(&bold)),
/// (" and this is ", None),
/// ("italic", Some(&italic))
/// ],
/// None
/// )?;
/// # workbook.close()
/// # }
/// ```
/// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-write_richtext-1.png)
///
/// The basic rule is to break the string into fragments and put a lxw_format object before the fragment that you want to format. So if we look at the above example again:
///
/// This is **bold** and this is *italic*
///
/// The would be broken down into 4 fragments:
/// ```text
/// default: |This is |
/// bold: |bold|
/// default: | and this is |
/// italic: |italic|
/// ```
/// This in then converted to the tuple fragments shown in the example above. For the default format we use None.
///
/// ### Note
/// Excel doesn't allow the use of two consecutive formats in a rich string or an empty string fragment. For either of these conditions a warning is raised and the input to `worksheet.write_rich_string()` is ignored.
pub fn write_rich_string(
&mut self,
row: WorksheetRow,
col: WorksheetCol,
text: &[(&str, Option<&Format>)],
format: Option<&Format>,
) -> Result<(), XlsxError> {
let mut c_str: Vec<Vec<u8>> = text
.iter()
.map(|x| {
CString::new(x.0)
.unwrap()
.as_c_str()
.to_bytes_with_nul()
.to_vec()
})
.collect();
let mut rich_text: Vec<_> = text
.iter()
.zip(c_str.iter_mut())
.map(|(x, y)| libxlsxwriter_sys::lxw_rich_string_tuple {
format: x.1.map(|z| z.format).unwrap_or(std::ptr::null_mut()),
string: y.as_mut_ptr() as *mut c_char,
})
.collect();
let mut rich_text_ptr: Vec<*mut libxlsxwriter_sys::lxw_rich_string_tuple> = rich_text
.iter_mut()
.map(|x| x as *mut libxlsxwriter_sys::lxw_rich_string_tuple)
.collect();
rich_text_ptr.push(std::ptr::null_mut());
unsafe {
let result = libxlsxwriter_sys::worksheet_write_rich_string(
self.worksheet,
row,
col,
rich_text_ptr.as_mut_ptr(),
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
pub fn set_row(
&mut self,
row: WorksheetRow,
height: f64,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_set_row(
self.worksheet,
row,
height,
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
pub fn set_row_opt(
&mut self,
row: WorksheetRow,
height: f64,
format: Option<&Format>,
options: &mut RowColOptions,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_set_row_opt(
self.worksheet,
row,
height,
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
options,
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}
}
/// The set_row_pixels() function is the same as the [Worksheet::set_row()] function except that the height can be set in pixels.
///
/// If you wish to set the format of a row without changing the height you can pass the default row height in pixels: [LXW_DEF_ROW_HEIGHT_PIXELS].
pub fn set_row_pixels(
&mut self,
row: WorksheetRow,
pixels: u32,
format: Option<&Format>,
) -> Result<(), XlsxError> {
unsafe {
let result = libxlsxwriter_sys::worksheet_set_row_pixels(
self.worksheet,
row,
pixels,
format.map(|x| x.format).unwrap_or(std::ptr::null_mut()),
);
if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
Ok(())
} else {
Err(XlsxError::new(result))
}
}