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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
use super::{convert_bool, Chart, DataValidation, Format, FormatColor, Workbook, XlsxError};
use std::ffi::CString;

#[derive(Debug, Clone, PartialEq, PartialOrd)]
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 row value. Equivalent to `u32`.
///
/// The maximum row in Excel is 1,048,576.
pub type WorksheetCol = libxlsxwriter_sys::lxw_col_t;

/// Integer data type to represent a column value. Equivalent to `u16`.
///
/// The maximum column in Excel is 16,384.
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;

/// 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 i8,
            })
            .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))
            }
        }
    }

    pub fn set_column(
        &mut self,
        first_col: WorksheetCol,
        last_col: WorksheetCol,
        width: f64,
        format: Option<&Format>,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_column(
                self.worksheet,
                first_col,
                last_col,
                width,
                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_column_opt(
        &mut self,
        first_col: WorksheetCol,
        last_col: WorksheetCol,
        width: f64,
        format: Option<&Format>,
        options: &mut RowColOptions,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_column_opt(
                self.worksheet,
                first_col,
                last_col,
                width,
                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))
            }
        }
    }

    /// This function can be used to insert a image into a worksheet. The image can be in PNG, JPEG or BMP format:
    /// ```rust
    /// # use xlsxwriter::*;
    /// # fn main() -> Result<(), XlsxError> {
    /// # let workbook = Workbook::new("test-worksheet_insert_image-1.xlsx");
    /// # let mut worksheet = workbook.add_worksheet(None)?;
    /// worksheet.insert_image(2, 1, "../images/simple1.png")?;
    /// # workbook.close()
    /// # }
    /// ```
    /// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-insert_image-1.png)
    ///
    /// The Worksheet.insert_image_opt() function takes additional optional parameters to position and scale the image, see below.
    ///
    /// ### Note
    /// The scaling of a image may be affected if is crosses a row that has its default height changed due to a font that is larger than the default font size or that has text wrapping turned on. To avoid this you should explicitly set the height of the row using Worksheet.set_row() if it crosses an inserted image.
    ///
    /// BMP images are only supported for backward compatibility. In general it is best to avoid BMP images since they aren't compressed. If used, BMP images must be 24 bit, true color, bitmaps.
    pub fn insert_image(
        &mut self,
        row: WorksheetRow,
        col: WorksheetCol,
        filename: &str,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_insert_image(
                self.worksheet,
                row,
                col,
                CString::new(filename).unwrap().as_c_str().as_ptr(),
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    /// This function is like Worksheet.insert_image() function except that it takes an optional `ImageOptions` struct to scale and position the image:
    /// ```rust
    /// # use xlsxwriter::*;
    /// # fn main() -> Result<(), XlsxError> {
    /// # let workbook = Workbook::new("test-worksheet_insert_image_opt-1.xlsx");
    /// # let mut worksheet = workbook.add_worksheet(None)?;
    /// worksheet.insert_image_opt(
    ///     2, 1,
    ///    "../images/simple1.png",
    ///     &ImageOptions{
    ///         x_offset: 30,
    ///         y_offset: 30,
    ///         x_scale: 0.5,
    ///         y_scale: 0.5,
    ///     }
    /// )?;
    /// # workbook.close()
    /// # }
    /// ```
    /// ![Result Image](https://github.com/informationsea/xlsxwriter-rs/raw/master/images/test-worksheet-insert_image_opt-1.png)
    ///
    /// ### Note
    /// See the notes about row scaling and BMP images in Worksheet.insert_image() above.
    pub fn insert_image_opt(
        &mut self,
        row: WorksheetRow,
        col: WorksheetCol,
        filename: &str,
        opt: &ImageOptions,
    ) -> Result<(), XlsxError> {
        let mut opt_struct = opt.into();
        unsafe {
            let result = libxlsxwriter_sys::worksheet_insert_image_opt(
                self.worksheet,
                row,
                col,
                CString::new(filename).unwrap().as_c_str().as_ptr(),
                &mut opt_struct,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    /// This function can be used to insert a image into a worksheet from a memory buffer:
    /// ```rust
    /// # use xlsxwriter::*;
    /// # fn main() -> Result<(), XlsxError> {
    /// # let workbook = Workbook::new("test-worksheet_insert_image_buffer-1.xlsx");
    /// # let mut worksheet = workbook.add_worksheet(None)?;
    /// let data = include_bytes!("../../images/simple1.png");
    /// worksheet.insert_image_buffer(0, 0, &data[..])?;
    /// # workbook.close()
    /// # }
    /// ```
    /// See Worksheet.insert_image() for details about the supported image formats, and other image features.
    pub fn insert_image_buffer(
        &mut self,
        row: WorksheetRow,
        col: WorksheetCol,
        buffer: &[u8],
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_insert_image_buffer(
                self.worksheet,
                row,
                col,
                buffer.as_ptr(),
                buffer.len() as libxlsxwriter_sys::size_t,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn insert_image_buffer_opt(
        &mut self,
        row: WorksheetRow,
        col: WorksheetCol,
        buffer: &[u8],
        opt: &ImageOptions,
    ) -> Result<(), XlsxError> {
        let mut opt_struct = opt.into();
        unsafe {
            let result = libxlsxwriter_sys::worksheet_insert_image_buffer_opt(
                self.worksheet,
                row,
                col,
                buffer.as_ptr(),
                buffer.len() as libxlsxwriter_sys::size_t,
                &mut opt_struct,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn insert_chart(
        &mut self,
        row: WorksheetRow,
        column: WorksheetCol,
        chart: &Chart,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result =
                libxlsxwriter_sys::worksheet_insert_chart(self.worksheet, row, column, chart.chart);
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn merge_range(
        &mut self,
        first_row: WorksheetRow,
        first_col: WorksheetCol,
        last_row: WorksheetRow,
        last_col: WorksheetCol,
        string: &str,
        format: Option<&Format>,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_merge_range(
                self.worksheet,
                first_row,
                first_col,
                last_row,
                last_col,
                CString::new(string).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))
            }
        }
    }

    pub fn autofilter(
        &mut self,
        first_row: WorksheetRow,
        first_col: WorksheetCol,
        last_row: WorksheetRow,
        last_col: WorksheetCol,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_autofilter(
                self.worksheet,
                first_row,
                first_col,
                last_row,
                last_col,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn data_validation_cell(
        &mut self,
        row: WorksheetRow,
        col: WorksheetCol,
        validation: &DataValidation,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_data_validation_cell(
                self.worksheet,
                row,
                col,
                &mut validation.to_c_struct().data_validation,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn data_validation_range(
        &mut self,
        first_row: WorksheetRow,
        first_col: WorksheetCol,
        last_row: WorksheetRow,
        last_col: WorksheetCol,
        validation: &DataValidation,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_data_validation_range(
                self.worksheet,
                first_row,
                first_col,
                last_row,
                last_col,
                &mut validation.to_c_struct().data_validation,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn activate(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_activate(self.worksheet);
        }
    }

    pub fn select(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_select(self.worksheet);
        }
    }

    pub fn hide(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_hide(self.worksheet);
        }
    }

    pub fn set_first_sheet(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_first_sheet(self.worksheet);
        }
    }

    pub fn freeze_panes(&mut self, row: WorksheetRow, col: WorksheetCol) {
        unsafe {
            libxlsxwriter_sys::worksheet_freeze_panes(self.worksheet, row, col);
        }
    }

    pub fn split_panes(&mut self, vertical: f64, horizontal: f64) {
        unsafe {
            libxlsxwriter_sys::worksheet_split_panes(self.worksheet, vertical, horizontal);
        }
    }

    pub fn set_selection(
        &mut self,
        first_row: WorksheetRow,
        first_col: WorksheetCol,
        last_row: WorksheetRow,
        last_col: WorksheetCol,
    ) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_selection(
                self.worksheet,
                first_row,
                first_col,
                last_row,
                last_col,
            );
        }
    }

    pub fn set_landscape(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_landscape(self.worksheet);
        }
    }

    pub fn set_portrait(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_portrait(self.worksheet);
        }
    }

    pub fn set_page_view(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_page_view(self.worksheet);
        }
    }

    pub fn set_paper(&mut self, paper: PaperType) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_paper(self.worksheet, paper.value());
        }
    }

    pub fn set_header(&mut self, header: &str) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_header(
                self.worksheet,
                CString::new(header).unwrap().as_c_str().as_ptr(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn set_footer(&mut self, footer: &str) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_footer(
                self.worksheet,
                CString::new(footer).unwrap().as_c_str().as_ptr(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn set_header_opt(
        &mut self,
        header: &str,
        options: &HeaderFooterOptions,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_header_opt(
                self.worksheet,
                CString::new(header).unwrap().as_c_str().as_ptr(),
                &mut options.into(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn set_footer_opt(
        &mut self,
        footer: &str,
        options: &HeaderFooterOptions,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_footer_opt(
                self.worksheet,
                CString::new(footer).unwrap().as_c_str().as_ptr(),
                &mut options.into(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn set_h_pagebreaks(&mut self, breaks: &[WorksheetRow]) -> Result<(), XlsxError> {
        let mut breaks_vec = breaks.to_vec();
        breaks_vec.push(0);
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_h_pagebreaks(
                self.worksheet,
                breaks_vec.as_mut_ptr(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn set_v_pagebreaks(&mut self, breaks: &[WorksheetCol]) -> Result<(), XlsxError> {
        let mut breaks_vec = breaks.to_vec();
        breaks_vec.push(0);
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_v_pagebreaks(
                self.worksheet,
                breaks_vec.as_mut_ptr(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn print_across(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_print_across(self.worksheet);
        }
    }

    pub fn set_zoom(&mut self, scale: u16) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_zoom(self.worksheet, scale);
        }
    }

    pub fn gridlines(&mut self, option: GridLines) {
        unsafe {
            libxlsxwriter_sys::worksheet_gridlines(self.worksheet, option.value());
        }
    }

    pub fn center_horizontally(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_center_horizontally(self.worksheet);
        }
    }

    pub fn center_vertically(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_center_vertically(self.worksheet);
        }
    }

    pub fn print_row_col_headers(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_print_row_col_headers(self.worksheet);
        }
    }

    pub fn repeat_rows(
        &mut self,
        first_row: WorksheetRow,
        last_row: WorksheetRow,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result =
                libxlsxwriter_sys::worksheet_repeat_rows(self.worksheet, first_row, last_row);
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn repeat_columns(
        &mut self,
        first_col: WorksheetCol,
        last_col: WorksheetCol,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result =
                libxlsxwriter_sys::worksheet_repeat_columns(self.worksheet, first_col, last_col);
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn print_area(
        &mut self,
        first_row: WorksheetRow,
        first_col: WorksheetCol,
        last_row: WorksheetRow,
        last_col: WorksheetCol,
    ) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_print_area(
                self.worksheet,
                first_row,
                first_col,
                last_row,
                last_col,
            );
            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }

    pub fn fit_to_pages(&mut self, width: u16, height: u16) {
        unsafe {
            libxlsxwriter_sys::worksheet_fit_to_pages(self.worksheet, width, height);
        }
    }

    pub fn set_start_page(&mut self, start_page: u16) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_start_page(self.worksheet, start_page);
        }
    }

    pub fn set_print_scale(&mut self, scale: u16) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_print_scale(self.worksheet, scale);
        }
    }

    pub fn set_right_to_left(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_right_to_left(self.worksheet);
        }
    }

    pub fn set_hide_zero(&mut self) {
        unsafe {
            libxlsxwriter_sys::worksheet_hide_zero(self.worksheet);
        }
    }

    pub fn set_tab_color(&mut self, color: FormatColor) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_tab_color(self.worksheet, color.value());
        }
    }

    pub fn protect(&mut self, password: &str, protection: &Protection) {
        unsafe {
            libxlsxwriter_sys::worksheet_protect(
                self.worksheet,
                CString::new(password).unwrap().as_c_str().as_ptr(),
                &mut protection.into(),
            );
        }
    }

    pub fn outline_settings(
        &mut self,
        visible: bool,
        symbols_below: bool,
        symbols_right: bool,
        auto_style: bool,
    ) {
        unsafe {
            libxlsxwriter_sys::worksheet_outline_settings(
                self.worksheet,
                convert_bool(visible),
                convert_bool(symbols_below),
                convert_bool(symbols_right),
                convert_bool(auto_style),
            )
        }
    }

    pub fn set_default_row(&mut self, height: f64, hide_unused_rows: bool) {
        unsafe {
            libxlsxwriter_sys::worksheet_set_default_row(
                self.worksheet,
                height,
                convert_bool(hide_unused_rows),
            )
        }
    }

    pub fn set_vba_name(&mut self, name: &str) -> Result<(), XlsxError> {
        unsafe {
            let result = libxlsxwriter_sys::worksheet_set_vba_name(
                self.worksheet,
                CString::new(name).unwrap().as_c_str().as_ptr(),
            );

            if result == libxlsxwriter_sys::lxw_error_LXW_NO_ERROR {
                Ok(())
            } else {
                Err(XlsxError::new(result))
            }
        }
    }
}