doe 1.1.78

doe is a powerful Rust crate designed to enhance development workflow by providing an extensive collection of useful macros and utility functions. It not only simplifies common tasks but also offers convenient features for clipboard management,robust cryptographic functions,keyboard input, and mouse interaction.
Documentation
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
/// xlsx model
/// ```ignore
/// use doe::xlsx;
/// let mut book = xlsx::new_file();
/// book.set_sheet_name(0, "book");
/// xlsx::write(&book, "book.xlsx".to_path_buf()).unwrap();
///
///
///use doe::xlsx::*;
/// use doe::xlsx::read_xlsx;
/// let xx = "E:/code/rust_code/doe_test/demo.xlsx";
/// let mut xlsx_book = read_xlsx(xx).unwrap();
/// let sheet_names: Vec<String> = xlsx_book.get_sheet_names();
/// println!("{:?}", sheet_names);
/// let sheet = xlsx_book.get_sheet(&0).unwrap();
/// let cells = sheet.read_cells().unwrap();
/// for (_, cell) in cells.iter().enumerate() {
///     for (c, c_idx, _) in cell {
///         let col_name = num_to_col(*c_idx as usize);
///         if col_name == "T" {
///             if let Some(c) = c {
///                 println!(
///                     "{:?},{}",
///                     c.get_cell_value().get_raw_value().get_data_type(),
///                     c.get_cell_value().get_value()
///                 );
///             }
///         }
///     }
/// }
/// ```
///
#[allow(warnings)]
#[cfg(feature = "xlsx")]
pub mod xlsx {
    use std::{io::Cursor, path::PathBuf};
    pub use umya_spreadsheet::writer::xlsx::*;
    pub use umya_spreadsheet::*;
    ///
    /// ```ignore
    /// use doe::xlsx;
    /// let s = vec![
    ///     vec!["a".to_string(), "b".to_string(), "c".to_string()],
    ///     vec!["d".to_string(), "e".to_string(), "f".to_string()],
    ///     vec!["g".to_string(), "h".to_string(), "i".to_string()],
    /// ];
    /// xlsx::write_csv_as_xlsx("demo.xlsx", s).unwrap();
    /// ```
    ///
    ///
    pub fn write_csv_as_xlsx(
        xlsx_path: impl AsRef<Path>,
        csv_data: Vec<Vec<String>>,
    ) -> anyhow::Result<()> {
        use crate::xlsx;
        let mut xlsx_book = xlsx::new_file();
        let mut st = Worksheet::default();
        st.set_name("csv_data".to_string());
        xlsx_book.add_sheet(st).map_err(|s| anyhow!(s))?;
        // xlsx_book.set_sheet_name(0, "Sheet1");
        if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut("csv_data") {
            for (r_index, row) in csv_data.iter().enumerate() {
                for (c_index, val) in row.iter().enumerate() {
                    let (col_name, _) = position_to_coordinate_tuple(c_index + 1, r_index + 1)
                        .context("Unexpected error at position_to_coordinate")?;
                    sheet
                        .get_column_dimension_mut(&col_name)
                        .set_auto_width(true);
                    let coordinate = position_to_coordinate(c_index + 1, r_index + 1)
                        .context("Unexpected error at position_to_coordinate")?;
                    let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                    cell.set_value_string(val.to_string());
                }
            }
            writer::xlsx::write(&xlsx_book, xlsx_path)?;
        } else {
            anyhow::anyhow!("Unexpected error at get sheet");
        }
        Ok(())
    }

    #[derive(Debug, Clone)]
    pub struct SheetData {
        pub sheet_name: String,
        pub csv_data: Vec<Vec<String>>,
    }

    pub fn write_xlsx_with_sheet_data_list(
        xlsx_path: impl AsRef<Path>,
        sheet_data: Vec<SheetData>,
    ) -> anyhow::Result<()> {
        use crate::xlsx;
        let mut xlsx_book = xlsx::new_file();
        let _ = xlsx_book.remove_sheet_by_name("Sheet1");
        for sd in sheet_data {
            let sheet_name = sd.sheet_name;
            let csv_data = sd.csv_data;
            let mut st = Worksheet::default();
            st.set_name(sheet_name.to_string());
            xlsx_book.add_sheet(st).map_err(|s| anyhow!(s))?;
            // xlsx_book.set_sheet_name(0, "Sheet1");
            if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name.to_string()) {
                for (r_index, row) in csv_data.iter().enumerate() {
                    for (c_index, val) in row.iter().enumerate() {
                        let (col_name, _) = position_to_coordinate_tuple(c_index + 1, r_index + 1)
                            .context("Unexpected error at position_to_coordinate")?;
                        sheet
                            .get_column_dimension_mut(&col_name)
                            .set_auto_width(true);

                        let coordinate = position_to_coordinate(c_index + 1, r_index + 1)
                            .context("Unexpected error at position_to_coordinate")?;
                        let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                        cell.set_value_string(val.to_string());
                    }
                }
            } else {
                anyhow::anyhow!("Unexpected error at get sheet");
            }
        }
        writer::xlsx::write(&xlsx_book, xlsx_path)?;
        Ok(())
    }

    // if width == -1.0 => set_auto_width else set with width val
    pub fn write_xlsx_with_sheet_data_list_with_width(
        xlsx_path: impl AsRef<Path>,
        sheet_data: Vec<SheetData>,
        width: Option<f64>,
    ) -> anyhow::Result<()> {
        use crate::xlsx;
        let mut xlsx_book = xlsx::new_file();
        let _ = xlsx_book.remove_sheet_by_name("Sheet1");
        for sd in sheet_data {
            let sheet_name = sd.sheet_name;
            let csv_data = sd.csv_data;
            let mut st = Worksheet::default();
            st.set_name(sheet_name.to_string());
            xlsx_book.add_sheet(st).map_err(|s| anyhow!(s))?;
            // xlsx_book.set_sheet_name(0, "Sheet1");
            if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name.to_string()) {
                for (r_index, row) in csv_data.iter().enumerate() {
                    for (c_index, val) in row.iter().enumerate() {
                        let (col_name, _) = position_to_coordinate_tuple(c_index + 1, r_index + 1)
                            .context("Unexpected error at position_to_coordinate")?;
                        if width.is_none() {
                            sheet
                                .get_column_dimension_mut(&col_name)
                                .set_auto_width(true);
                        } else {
                            sheet
                                .get_column_dimension_mut(&col_name)
                                .set_width(width.unwrap_or_default());
                        }
                        let coordinate = position_to_coordinate(c_index + 1, r_index + 1)
                            .context("Unexpected error at position_to_coordinate")?;
                        let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                        cell.set_value_string(val.to_string());
                    }
                }
            } else {
                anyhow::anyhow!("Unexpected error at get sheet");
            }
        }
        writer::xlsx::write(&xlsx_book, xlsx_path)?;
        Ok(())
    }

    pub fn write_csv_as_xlsx_with_sheet_name(
        xlsx_path: impl AsRef<Path>,
        sheet_name: impl ToString,
        csv_data: Vec<Vec<String>>,
    ) -> anyhow::Result<()> {
        use crate::xlsx;
        let mut xlsx_book = xlsx::new_file();
        let _ = xlsx_book.remove_sheet_by_name("Sheet1");
        let mut st = Worksheet::default();
        st.set_name(sheet_name.to_string());
        xlsx_book.add_sheet(st).map_err(|s| anyhow!(s))?;
        // xlsx_book.set_sheet_name(0, "Sheet1");
        if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name.to_string()) {
            for (r_index, row) in csv_data.iter().enumerate() {
                for (c_index, val) in row.iter().enumerate() {
                    let (col_name, _) = position_to_coordinate_tuple(c_index + 1, r_index + 1)
                        .context("Unexpected error at position_to_coordinate")?;
                    sheet
                        .get_column_dimension_mut(&col_name)
                        .set_auto_width(true);
                    let coordinate = position_to_coordinate(c_index + 1, r_index + 1)
                        .context("Unexpected error at position_to_coordinate")?;
                    let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                    cell.set_value_string(val.to_string());
                }
            }
            writer::xlsx::write(&xlsx_book, xlsx_path)?;
        } else {
            anyhow::anyhow!("Unexpected error at get sheet");
        }
        Ok(())
    }

    pub fn write_csv_to_xlsx(
        xlsx_path: impl AsRef<Path>,
        sheet_name: impl ToString,
        csv_data: Vec<Vec<String>>,
    ) -> anyhow::Result<()> {
        let mut xlsx_book = umya_spreadsheet::reader::xlsx::lazy_read(xlsx_path.as_ref())?;
        if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name.to_string()) {
            for (r_index, row) in csv_data.iter().enumerate() {
                for (c_index, val) in row.iter().enumerate() {
                    let (col_name, _) = position_to_coordinate_tuple(c_index + 1, r_index + 1)
                        .context("Unexpected error at position_to_coordinate")?;
                    sheet
                        .get_column_dimension_mut(&col_name)
                        .set_auto_width(true);
                    let coordinate = position_to_coordinate(c_index, r_index)
                        .context("Unexpected error at position_to_coordinate")?;
                    let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                    cell.set_value_string(val.to_string());
                }
            }
            writer::xlsx::write(&xlsx_book, xlsx_path)?;
        } else {
            let mut st = Worksheet::default();
            st.set_name(sheet_name.to_string());
            xlsx_book.add_sheet(st);
            writer::xlsx::write(&xlsx_book, xlsx_path.as_ref())?;
            let mut xlsx_book = umya_spreadsheet::reader::xlsx::lazy_read(xlsx_path.as_ref())?;
            if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name.to_string()) {
                for (r_index, row) in csv_data.iter().enumerate() {
                    for (c_index, val) in row.iter().enumerate() {
                        let (col_name, _) = position_to_coordinate_tuple(c_index + 1, r_index + 1)
                            .context("Unexpected error at position_to_coordinate")?;
                        sheet
                            .get_column_dimension_mut(&col_name)
                            .set_auto_width(true);
                        let coordinate = position_to_coordinate(c_index + 1, r_index + 1)
                            .context("Unexpected error at position_to_coordinate")?;
                        let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                        cell.set_value_string(val.to_string());
                    }
                }
                writer::xlsx::write(&xlsx_book, xlsx_path)?;
            } else {
                anyhow::anyhow!("Unexpected error at get sheet");
            }
        }
        Ok(())
    }
    use crate::{DebugPrint, Print};
    ///
    /// value_type can be 'formula' 'string' 'number' 'bool' 'hyperlink'
    ///
    ///```rust
    ///use doe::*;
    ///xlsx::xlsx_set_values("./demo.xlsx", "Sheet1", &[cellvalue!("M4", "3", "number")]);
    /// ```
    ///
    #[macro_export]
    macro_rules! cellvalue {
        ($coordinate:expr,$value:expr,$value_type:expr) => {
            $crate::xlsx::CellValue::new($coordinate, $value, $value_type)
        };
    }
    ///num_to_col
    /// ```ignore
    ///col_to_num("D").dprintln();//4
    ///num_to_col(4).dprintln();//D
    ///coordinate_to_position("D27").dprintln();//4,27
    ///position_to_coordinate(4, 27).unwrap().dprintln();//D27
    /// ```
    pub fn num_to_col(index: usize) -> String {
        let index = index + 1;
        let mut result = String::new();
        let mut index = index;

        while index > 0 {
            let remainder = (index - 1) % 26;
            result.push((b'A' + remainder as u8) as char);
            index = (index - 1) / 26;
        }

        result.chars().rev().collect()
    }
    ///col_to_num
    /// ```ignore
    ///col_to_num("D").dprintln();//4
    ///num_to_col(4).dprintln();//D
    ///coordinate_to_position("D27").dprintln();//4,27
    ///position_to_coordinate(4, 27).unwrap().dprintln();//D27
    /// ```
    pub fn col_to_num(col: impl ToString) -> usize {
        let col_str = col.to_string().to_uppercase();
        let mut col_num = 0;
        for (i, c) in col_str.chars().enumerate() {
            if (c as u8 as i8 - 'A' as u8 as i8) >= 0 {
                let offset = (c as u8 - b'A') as usize + 1;
                col_num = col_num * 26 + offset;
            }
        }
        col_num - 1
    }
    ///coordinate_to_position
    /// ```ignore
    ///col_to_num("D").dprintln();//4
    ///num_to_col(4).dprintln();//D
    ///coordinate_to_position("D27").dprintln();//4,27
    ///position_to_coordinate(4, 27).unwrap().dprintln();//D27
    /// ```
    pub fn coordinate_to_position(coordinate: impl ToString) -> (usize, usize) {
        let coord_str = coordinate.to_string();
        let mut col_str = String::new();
        let mut row_str = String::new();
        for c in coord_str.chars() {
            if c.is_digit(10) {
                row_str.push(c);
            } else {
                col_str.push(c);
            }
        }
        let col_num = col_to_num(col_str);
        let row_num = row_str.parse::<usize>().unwrap();
        (col_num, row_num)
    }
    ///position_to_coordinate
    /// ```ignore
    ///col_to_num("D").dprintln();//4
    ///num_to_col(4).dprintln();//D
    ///coordinate_to_position("D27").dprintln();//4,27
    ///position_to_coordinate(4, 27).unwrap().dprintln();//D27
    /// ```
    pub fn position_to_coordinate(x: usize, y: usize) -> Option<String> {
        if x >= 1 && y >= 1 {
            let mut num = x;
            let mut col_name = String::new();
            while num > 0 {
                let rem = (num - 1) % 26;
                col_name.insert(0, ((rem as u8) + b'A') as char);
                num = (num - 1) / 26;
            }
            Some(format!("{}{}", col_name, y))
        } else {
            None
        }
    }

    pub fn position_to_coordinate_tuple(x: usize, y: usize) -> Option<(String, String)> {
        if x >= 1 && y >= 1 {
            let mut num = x;
            let mut col_name = String::new();
            while num > 0 {
                let rem = (num - 1) % 26;
                col_name.insert(0, ((rem as u8) + b'A') as char);
                num = (num - 1) / 26;
            }
            Some((format!("{}", col_name), format!("{}", y)))
        } else {
            None
        }
    }
    pub trait SpreadsheetHelper {
        fn get_sheet_names(&mut self) -> Vec<String>;
    }
    pub trait WorksheetHelper {
        fn get_cell_types(&self) -> Vec<String>;
        fn read_cells(&self) -> anyhow::Result<Vec<Vec<(Option<Cell>, u32, u32)>>>;
    }
    impl WorksheetHelper for Worksheet {
        fn get_cell_types(&self) -> Vec<String> {
            let cell_types: Vec<String> = self
                .get_cell_collection()
                .iter()
                .map(|c| c.get_cell_value().get_data_type().to_string())
                .collect();
            cell_types
        }
        fn read_cells(&self) -> anyhow::Result<Vec<Vec<(Option<Cell>, u32, u32)>>> {
            let col = self.get_highest_column();
            let row = self.get_highest_row();
            let mut csv_data = vec![];
            for r in 1..col + 1 {
                let mut row_vec: Vec<(Option<Cell>, u32, u32)> = Vec::new();
                for c in 1..row + 1 {
                    let cell: Option<Cell> =
                        self.get_cell((c as u32, r as u32)).map(|s| s.to_owned());
                    row_vec.push((cell, c as u32, r as u32));
                }
                csv_data.push(row_vec);
            }
            anyhow::Ok(csv_data)
        }
    }

    impl WorksheetHelper for &mut Worksheet {
        fn get_cell_types(&self) -> Vec<String> {
            let cell_types: Vec<String> = self
                .get_cell_collection()
                .iter()
                .map(|c| c.get_cell_value().get_data_type().to_string())
                .collect();
            cell_types
        }
        fn read_cells(&self) -> anyhow::Result<Vec<Vec<(Option<Cell>, u32, u32)>>> {
            let col = self.get_highest_column();
            let row = self.get_highest_row();
            let mut csv_data = vec![];
            for r in 1..col + 1 {
                let mut row_vec = Vec::new();
                for c in 1..row + 1 {
                    let cell: Option<Cell> =
                        self.get_cell((c as u32, r as u32)).map(|s| s.to_owned());
                    row_vec.push((cell, c as u32, r as u32));
                }
                csv_data.push(row_vec);
            }
            anyhow::Ok(csv_data)
        }
    }
    impl SpreadsheetHelper for Spreadsheet {
        fn get_sheet_names(&mut self) -> Vec<String> {
            let sheet_count = self.get_sheet_count();
            for i in 0..sheet_count {
                self.read_sheet(i);
            }
            let sheet_names: Vec<String> = self
                .get_sheet_collection_no_check()
                .iter()
                .map(|s| s.get_name().to_string())
                .collect();
            sheet_names
        }
    }
    impl SpreadsheetHelper for &mut Spreadsheet {
        fn get_sheet_names(&mut self) -> Vec<String> {
            let sheet_count = self.get_sheet_count();
            for i in 0..sheet_count {
                self.read_sheet(i);
            }
            let sheet_names: Vec<String> = self
                .get_sheet_collection_no_check()
                .iter()
                .map(|s| s.get_name().to_string())
                .collect();
            sheet_names
        }
    }
    ///xlsx_get_sheet_names
    ///```ignore
    ///let sheet_names = xlsx_get_sheet_names("./book.xlsx").unwrap();
    ///println!("{:?}", sheet_names);
    ///```
    pub fn xlsx_get_sheet_names(xlsx_path: impl ToString) -> Option<Vec<String>> {
        let xlsx_path = xlsx_path.to_string();
        let path = std::path::Path::new(&xlsx_path);
        if let std::result::Result::Ok(mut xlsx_book) =
            umya_spreadsheet::reader::xlsx::lazy_read(path)
        {
            let sheet_count = xlsx_book.get_sheet_count();
            let sheet_names: Vec<String> = xlsx_book
                .get_sheet_collection_no_check()
                .iter()
                .map(|s| s.get_name().to_string())
                .collect();
            return Some(sheet_names);
        } else {
            anyhow::anyhow!("Unexpected error at read xlsx file");
            return None;
        }
        return None;
    }
    ///xlsx_get_cell_value
    ///```ignore
    /// let cell_value = xlsx_get_cell_value("./lang.xlsx","Sheet1","D27");
    /// ```
    pub fn xlsx_get_cell_value(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
        coordinate: impl ToString,
    ) -> Option<String> {
        let xlsx_path = xlsx_path.to_string();
        let sheet_name = sheet_name.to_string();
        let coordinate = coordinate.to_string();
        let path = std::path::Path::new(&xlsx_path);
        if let std::result::Result::Ok(mut xlsx_book) =
            umya_spreadsheet::reader::xlsx::lazy_read(path)
        {
            if let Some(sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name) {
                let value = sheet.get_cell_value(coordinate).get_value().to_string();
                return Some(value);
            } else {
                anyhow::anyhow!("Unexpected error at get sheet");
            }
            return None;
        } else {
            anyhow::anyhow!("Unexpected error at read xlsx file");
        }
        return None;
    }

    pub fn xlsx_get_cell(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
        coordinate: impl ToString,
    ) -> Option<umya_spreadsheet::CellValue> {
        let xlsx_path = xlsx_path.to_string();
        let sheet_name = sheet_name.to_string();
        let coordinate = coordinate.to_string();
        let path = std::path::Path::new(&xlsx_path);
        if let std::result::Result::Ok(mut xlsx_book) =
            umya_spreadsheet::reader::xlsx::lazy_read(path)
        {
            if let Some(sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name) {
                let value = sheet.get_cell_value(coordinate);
                return Some(value.to_owned());
            } else {
                anyhow::anyhow!("Unexpected error at get sheet");
            }
            return None;
        } else {
            anyhow::anyhow!("Unexpected error at read xlsx file");
        }
        return None;
    }
    /// CellValue coordinate is linke "A4" ..
    ///
    /// value is impl Tosting
    ///
    /// value_type can be 'formula' 'string' 'number' 'bool' 'hyperlink'
    pub struct CellValue<T: ToString, U: ToString> {
        pub coordinate: T,
        pub value: U,
        pub value_type: &'static str,
    }
    ///
    ///```rust
    ///use doe::*;
    ///xlsx::xlsx_set_values("./demo.xlsx", "Sheet1", &[CellValue::new("M4", "", "formula_attributes")]);
    /// ```
    ///
    impl<T: ToString, U: ToString> CellValue<T, U> {
        ///
        ///```rust
        ///use doe::*;
        ///xlsx::xlsx_set_values("./demo.xlsx", "Sheet1", &[CellValue::new("M4", "", "formula_attributes")]);
        /// ```
        /// value_type can be 'formula' 'string' 'number' 'bool' 'hyperlink'
        ///
        pub fn new(coordinate: T, value: U, value_type: &'static str) -> Self {
            Self {
                coordinate,
                value,
                value_type,
            }
        }
    }
    /// ### xlsx_bytes_set_values_and_save example
    ///```ignore
    /// let xlsx_bytes = std::fs::read("./demo.xlsx").unwrap();
    /// doe::xlsx::xlsx_bytes_set_values_and_save(xlsx_bytes, "Sheet1", &[CellValue::new("B4", "./XJTJWSHRD2023000026.pdf,pdf", "hyperlink")],"new.xlsx").unwrap();
    /// doe::xlsx::xlsx_bytes_set_values_and_save(xlsx_bytes, "Sheet1", &[CellValue::new("B4", "andrew", "string")],"new.xlsx").unwrap();
    /// doe::xlsx::xlsx_bytes_set_values_and_save(xlsx_bytes, "Sheet1", &[CellValue::new("B4", "12", "number")],"new.xlsx").unwrap();
    ///```

    pub fn xlsx_bytes_set_values_and_save(
        xlsx_bytes: Vec<u8>,
        sheet_name: impl ToString,
        values: &[CellValue<impl ToString, impl ToString>],
        path: PathBuf,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let values = values;
        use umya_spreadsheet::writer;
        // let xlsx_path = xlsx_path.to_string();
        // let path = std::path::Path::new(&xlsx_path);
        let reader = Cursor::new(xlsx_bytes);
        let mut xlsx_book =
            umya_spreadsheet::reader::xlsx::read_reader(reader, true).expect("read xlsx Error");
        let mut sheet = xlsx_book
            .get_sheet_by_name_mut(&sheet_name.to_string())
            .expect("read sheet Error");
        for cellvalue in values.iter() {
            let mut cell = sheet.get_cell_mut(cellvalue.coordinate.to_string());
            let mut cell_value = cell.get_cell_value_mut();
            if cellvalue.value_type.to_string() == "string" {
                cell_value.set_value_string(cellvalue.value.to_string());
            } else if cellvalue.value_type.to_string() == "number" {
                cell_value.set_value_number(
                    cellvalue
                        .value
                        .to_string()
                        .parse::<f64>()
                        .expect("number parse f64 Error"),
                );
            } else if cellvalue.value_type.to_string() == "formula" {
                cell_value.set_formula(cellvalue.value.to_string());
            }
            // fn main() {
            //     use doe::*;
            //     xlsx::xlsx_set_values("./demo.xlsx", "Sheet1", &[CellValue::new("B4", "./XJTJWSHRD2023000026.pdf,pdf", "hyperlink")]).unwrap();
            // }
            else if cellvalue.value_type.to_string() == "hyperlink" {
                let mut hyperlink = Hyperlink::default();
                let v = cellvalue.value.to_string();
                let hyperlink_vec: Vec<_> = v.split(",").filter(|s| !s.is_empty()).collect();
                hyperlink
                    .set_url(hyperlink_vec.iter().nth(0).unwrap().to_string())
                    .set_tooltip(hyperlink_vec.iter().nth(1).unwrap().to_string())
                    .set_location(false);

                cell.set_hyperlink(hyperlink);
            } else if cellvalue.value_type.to_string() == "bool" {
                let value = move || {
                    if cellvalue.value.to_string() == "true" || cellvalue.value.to_string() == "1" {
                        true
                    } else if cellvalue.value.to_string() == "false"
                        || cellvalue.value.to_string() == "0"
                    {
                        false
                    } else {
                        false
                    }
                };
                cell_value.set_value_bool(value());
            }
        }

        let _ = writer::xlsx::write(&xlsx_book, path);
        std::result::Result::Ok(())
    }

    use umya_spreadsheet::Hyperlink;
    ///```rust
    /// use doe::*;
    /// xlsx::xlsx_set_values("./rust.xlsx", "Sheet1", &[cellvalue!("A5","rust","string")]);
    /// xlsx::xlsx_set_values("./demo.xlsx", "Sheet1", &[CellValue::new("B4", "./XJTJWSHRD2023000026.pdf,pdf", "hyperlink")]).unwrap();
    ///  let mut cellvalues = vec![];
    ///  for (index, c) in c_vec.iter().enumerate() {
    ///      for (a, q) in a_vec.iter().zip(q_vec.iter()) {
    ///          if c == q{
    ///              cellvalues.push(cellvalue!("A".push_back(index+2), a, "string"));
    ///          }
    ///          
    ///     }
    /// }
    /// xlsx_set_values("148.xlsx", "1704344947003", &cellvalues).unwrap();
    /// ```
    pub fn xlsx_set_values(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
        values: &[CellValue<impl ToString, impl ToString>],
    ) -> Result<(), Box<dyn std::error::Error>> {
        let values = values;
        use umya_spreadsheet::writer;
        let xlsx_path = xlsx_path.to_string();
        let path = std::path::Path::new(&xlsx_path);
        // umya_spreadsheet::reader::xlsx::read_reader
        let mut xlsx_book =
            umya_spreadsheet::reader::xlsx::lazy_read(path).expect("read xlsx Error");
        let mut sheet = xlsx_book
            .get_sheet_by_name_mut(&sheet_name.to_string())
            .expect("read sheet Error");
        for cellvalue in values.iter() {
            let mut cell = sheet.get_cell_mut(cellvalue.coordinate.to_string());
            let mut cell_value = cell.get_cell_value_mut();
            if cellvalue.value_type.to_string() == "string" {
                cell_value.set_value_string(cellvalue.value.to_string());
            } else if cellvalue.value_type.to_string() == "number" {
                cell_value.set_value_number(
                    cellvalue
                        .value
                        .to_string()
                        .parse::<f64>()
                        .expect("number parse f64 Error"),
                );
            } else if cellvalue.value_type.to_string() == "formula" {
                cell_value.set_formula(cellvalue.value.to_string());
            }
            // fn main() {
            //     use doe::*;
            //     xlsx::xlsx_set_values("./demo.xlsx", "Sheet1", &[CellValue::new("B4", "./XJTJWSHRD2023000026.pdf,pdf", "hyperlink")]).unwrap();
            // }
            else if cellvalue.value_type.to_string() == "hyperlink" {
                let mut hyperlink = Hyperlink::default();
                let v = cellvalue.value.to_string();
                let hyperlink_vec: Vec<_> = v.split(",").filter(|s| !s.is_empty()).collect();
                hyperlink
                    .set_url(hyperlink_vec.iter().nth(0).unwrap().to_string())
                    .set_tooltip(hyperlink_vec.iter().nth(1).unwrap().to_string())
                    .set_location(false);

                cell.set_hyperlink(hyperlink);
            } else if cellvalue.value_type.to_string() == "bool" {
                let value = move || {
                    if cellvalue.value.to_string() == "true" || cellvalue.value.to_string() == "1" {
                        true
                    } else if cellvalue.value.to_string() == "false"
                        || cellvalue.value.to_string() == "0"
                    {
                        false
                    } else {
                        false
                    }
                };
                cell_value.set_value_bool(value());
            }
        }
        let _ = writer::xlsx::write(&xlsx_book, path);
        std::result::Result::Ok(())
    }
    ///xlsx_set_cell_value
    /// ```ignore
    /// use doe::xlsx::position_to_coordinate as ptc;
    /// use doe::*;
    /// xlsx::xlsx_get_sheet_names("./book.xlsx").dprintln();
    /// for x in 1..10 {
    ///     for y in 1..10 {
    ///         xlsx::xlsx_set_cell_value_string("./book.xlsx", "Info", ptc(x, y).unwrap(), format!("{},{}", x, y));
    ///     }
    /// }
    /// xlsx::xlsx_set_cell_value_string("./book.xlsx", "Sheet1", "D27", "some value").unwrap();
    /// ```
    ///
    pub fn xlsx_set_cell_value_string(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
        coordinate: impl ToString,
        new_value: impl ToString,
    ) -> Result<(), Box<dyn std::error::Error>> {
        use umya_spreadsheet::writer;
        let xlsx_path = xlsx_path.to_string();
        let path = std::path::Path::new(&xlsx_path);
        if let std::result::Result::Ok(mut xlsx_book) =
            umya_spreadsheet::reader::xlsx::lazy_read(path)
        {
            if let Some(mut sheet) = xlsx_book.get_sheet_by_name_mut(&sheet_name.to_string()) {
                let mut cell = sheet.get_cell_value_mut(coordinate.to_string());
                cell.set_value_string(new_value.to_string());
                let _ = writer::xlsx::write(&xlsx_book, path);
            } else {
                anyhow::anyhow!("Unexpected error at get sheet");
            }
        } else {
            anyhow::anyhow!("Unexpected error at read xlsx file");
        }
        std::result::Result::Ok(())
    }
    ///
    /// ```ignore
    /// let data:Vec<String> = xlsx_get_col_values("2024-01-08.xlsx", "检验报告查询导出2024-01-08","J").unwrap();
    /// ```
    ///
    ///
    pub fn xlsx_get_col_values(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
        col: impl ToString,
    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let xlsx_path = xlsx_path.to_string();
        let sheet_name = sheet_name.to_string();
        let col = col.to_string();
        let col_num = col_to_num(col);
        let path = std::path::Path::new(&xlsx_path);
        let mut xlsx_book = umya_spreadsheet::reader::xlsx::lazy_read(path)?;
        let mut sheet = xlsx_book
            .get_sheet_by_name_mut(&sheet_name.to_string())
            .expect("Couldn't find sheet");
        let cells = sheet.get_cell_collection();
        let mut max = 0;
        for cell in cells.clone() {
            let coordinate = cell.get_coordinate().get_coordinate();
            let (x, y) = coordinate_to_position(coordinate);
            if x > max {
                max = x;
            }
            if y > max {
                max = y;
            }
        }
        let mut csv_data = vec![];
        for cell in cells.clone() {
            let coordinate = cell.get_coordinate().get_coordinate();
            let (x, y) = coordinate_to_position(coordinate);
            // csv_data[y - 1][x - 1] = cell.get_value().to_string();
            if x == col_num {
                csv_data.push(cell.get_value().to_string());
            }
        }
        return std::result::Result::Ok(csv_data);
    }

    pub fn convert_excel_date(excel_date_str: &str) -> String {
        use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike};

        // 去除可能的空白字符
        let excel_date_str = excel_date_str.trim();

        // 如果已经是标准日期时间格式,直接返回
        if excel_date_str.contains("-") && excel_date_str.len() >= 10 {
            return excel_date_str.to_string();
        }

        // 尝试解析为f64(Excel数字格式)
        if let std::result::Result::Ok(excel_date) = excel_date_str.parse::<f64>() {
            // Excel日期系统说明:
            // Excel 1 = 1900-01-01
            // Excel 2 = 1900-01-02
            // ...
            // Excel 60 = 1900-02-29 (这个日期实际上不存在,Excel错误地认为1900年是闰年)
            // Excel 61 = 1900-03-01
            // 所以我们需要处理这个1900闰年bug

            let whole_days = excel_date.floor() as i64;
            let fraction = excel_date.fract();

            // 基准日期:1899-12-30,这样Excel 1 = 1900-01-01
            let base_date = NaiveDate::from_ymd_opt(1899, 12, 30).unwrap();

            // 计算天数
            let adjusted_days = whole_days;

            // 注意:Excel的1900年闰年bug处理
            // Excel错误地认为1900年是闰年,所以Excel 60 = 1900-02-29(不存在的日期)
            // Excel 61 = 1900-03-01
            // 但是我们使用1899-12-30作为基准日期,这个基准已经考虑了这个bug
            // 所以不需要额外调整天数

            // 计算最终日期
            let date = match base_date.checked_add_signed(chrono::Duration::days(adjusted_days)) {
                Some(d) => d,
                None => return excel_date_str.to_string(),
            };

            // 处理时间部分(Excel的小数部分是时间的比例)
            let total_seconds = (fraction * 86400.0).round() as u32;
            let hours = total_seconds / 3600;
            let minutes = (total_seconds % 3600) / 60;
            let seconds = total_seconds % 60;

            // 创建日期时间
            let datetime = date.and_hms_opt(hours, minutes, seconds);

            match datetime {
                Some(dt) => {
                    // 格式化输出
                    format!(
                        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
                        dt.year(),
                        dt.month(),
                        dt.day(),
                        dt.hour(),
                        dt.minute(),
                        dt.second()
                    )
                }
                None => excel_date_str.to_string(),
            }
        } else {
            // 尝试处理"2025/1/12"这样的格式
            excel_date_str.to_string()
        }
    }

    // 辅助函数:将"YYYY/MM/DD"格式转换为"YYYY-MM-DD HH:MM:SS"
    pub fn convert_date_format(date_str: &str) -> String {
        let parts: Vec<&str> = date_str.split('/').collect();
        if parts.len() == 3 {
            let year = parts[0];
            let month = parts[1];
            let day = parts[2];

            // 如果包含时间,处理时间部分
            // In function `convert_date_format`, around line 105
            let (day_part, time_part) = if day.contains(' ') {
                let day_parts: Vec<&str> = day.split(' ').collect();
                (day_parts[0], day_parts.get(1).copied().unwrap_or(""))
            } else {
                (day, "")
            };

            let mut result = format!(
                "{}-{:02}-{:02}",
                year,
                month.parse::<u32>().unwrap_or(0),
                day_part.parse::<u32>().unwrap_or(0)
            );

            if !time_part.is_empty() {
                result.push_str(&format!(" {}", time_part));
            } else {
                result.push_str(" 00:00:00");
            }

            result
        } else {
            date_str.to_string()
        }
    }

    pub fn read_xlsx(xlsx_path: impl ToString) -> Result<Spreadsheet, Box<dyn std::error::Error>> {
        let xlsx_path = xlsx_path.to_string();
        let path = std::path::Path::new(&xlsx_path);
        let mut xlsx_book: Spreadsheet = umya_spreadsheet::reader::xlsx::lazy_read(path)?;
        return std::result::Result::Ok(xlsx_book);
    }

    pub fn read_xlsx_from_buf(xlsx_buf: &[u8]) -> Result<Spreadsheet, Box<dyn std::error::Error>> {
        use std::io::Cursor;
        let cursor: Cursor<&[u8]> = Cursor::new(xlsx_buf);
        let xlsx_book: Spreadsheet = umya_spreadsheet::reader::xlsx::read_reader(cursor, true)?;
        return std::result::Result::Ok(xlsx_book);
    }

    pub fn xlsx_style_as_text_and_read_as_csv(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
    ) -> Result<Vec<Vec<String>>, Box<dyn std::error::Error>> {
        let xlsx_path = xlsx_path.to_string();
        let sheet_name = sheet_name.to_string();
        let path = std::path::Path::new(&xlsx_path);
        let mut xlsx_book = umya_spreadsheet::reader::xlsx::lazy_read(path)?;
        let mut sheet = xlsx_book
            .get_sheet_by_name_mut(&sheet_name.to_string())
            .expect("get_sheet_by_name error");
        let sheet_clone = sheet.clone();
        let col = sheet_clone.get_highest_column();
        let row = sheet_clone.get_highest_row();
        let mut csv_data = vec![];
        for r in 1..row + 1 {
            let mut row_vec = Vec::new();
            for c in 1..col + 1 {
                let cell = sheet.get_cell_mut((c as u32, r as u32));
                // let mut cell_val = sheet.get_cell_value_mut((c as u32, r as u32));
                cell.get_style_mut()
                    .get_number_format_mut()
                    .set_format_code("@");
                if cell.get_data_type() == "n" {
                    // row_vec.push(convert_excel_date(&cell.get_value_lazy().to_string()));
                    row_vec.push(cell.get_value_lazy().to_string());
                } else {
                    row_vec.push(cell.get_value_lazy().to_string());
                }
            }
            csv_data.push(row_vec);
        }
        return std::result::Result::Ok(csv_data);
    }

    pub fn xlsx_to_csv(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
    ) -> Result<Vec<Vec<String>>, Box<dyn std::error::Error>> {
        let xlsx_path = xlsx_path.to_string();
        let sheet_name = sheet_name.to_string();
        let path = std::path::Path::new(&xlsx_path);
        let mut xlsx_book = umya_spreadsheet::reader::xlsx::lazy_read(path)?;
        let mut sheet = xlsx_book
            .get_sheet_by_name_mut(&sheet_name.to_string())
            .expect("get_sheet_by_name error");
        let sheet_clone = sheet.clone();
        let col = sheet_clone.get_highest_column();
        let row = sheet_clone.get_highest_row();
        let mut csv_data = vec![];
        for r in 1..row + 1 {
            let mut row_vec = Vec::new();
            for c in 1..col + 1 {
                let cell = sheet.get_cell_mut((c as u32, r as u32));
                // let mut cell_val = sheet.get_cell_value_mut((c as u32, r as u32));
                // cell.get_style_mut()
                // .get_number_format_mut()
                // .set_format_code("@");
                if cell.get_data_type() == "n" {
                    // row_vec.push(convert_excel_date(&cell.get_value_lazy().to_string()));
                    row_vec.push(cell.get_value_lazy().to_string());
                } else {
                    row_vec.push(cell.get_value_lazy().to_string());
                }
            }
            csv_data.push(row_vec);
        }
        return std::result::Result::Ok(csv_data);
    }
    ///xlsx_to_btree_map
    /// ```ignore
    /// use doe::*;
    /// let bmap = doe::xlsx::xlsx_to_btree_map("get_xlsx.xlsx")?;
    /// bmap.iter().for_each(|(k, v)| {
    ///     std::fs::write(k.push_back(".csv"), v.iter().map(|s|s.join(",")).collect::<Vec<_>>().join("\n")).unwrap();
    /// });
    /// ```
    pub fn xlsx_to_btree_map(
        path: &str,
    ) -> crate::DynError<std::collections::BTreeMap<String, Vec<Vec<String>>>> {
        // 每个sheet就是一个二维数组
        use crate::*;
        // key 是sheet的名字
        // value 是二维数组
        let mut btree_map: std::collections::BTreeMap<String, Vec<Vec<String>>> = btreemap!();
        // 读xlsx
        if let Some(sheet_names) = crate::xlsx::xlsx_get_sheet_names(path) {
            for sheet_name in sheet_names {
                if let std::result::Result::Ok(sheet_data) =
                    crate::xlsx::xlsx_to_csv(path, sheet_name.clone())
                {
                    btree_map.insert(sheet_name, sheet_data);
                }
            }
        }
        std::result::Result::Ok(btree_map)
    }
    pub fn xlsx_to_csv_and_write(
        xlsx_path: impl ToString,
        sheet_name: impl ToString,
        csv_path: impl ToString,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let csv_path = csv_path.to_string();
        let csv: Vec<Vec<String>> = xlsx_to_csv(xlsx_path, sheet_name).unwrap();
        let mut csv_string: String = csv
            .iter()
            .map(|s| s.join(","))
            .collect::<Vec<_>>()
            .join("\n");
        std::fs::write(csv_path, csv_string).unwrap();
        std::result::Result::Ok(())
    }
    /// xlsx replace values and save new xlsx file
    /// ```ignore
    ///use doe::xlsx::*;
    /// //xlsx replace [A] to andrew in the xlsx file
    ///let _ = xlsx_replace_values_save("demo.xlsx".into(), vec![("[A]".into(),"andrew".into())], "new_demo.xlsx".into()).unwrap();
    ///````
    ///
    pub fn xlsx_replace_values_save<T>(
        xlsx_path: PathBuf,
        values: Vec<(T, T)>,
        new_xlsx_path: PathBuf,
    ) -> Result<(), Box<dyn std::error::Error>>
    where
        T: ToString,
    {
        use std::fs::File;
        use std::io::prelude::*;
        use zip::read::ZipArchive;
        use zip::write::FileOptions;
        use zip::CompressionMethod;

        // Open the .docx file as a zip
        let file = File::open(xlsx_path.clone())?;
        let mut archive = ZipArchive::new(file)?;
        let new_archive_path = "new_archive.zip";

        let options = FileOptions::default()
            .compression_method(CompressionMethod::Stored)
            .unix_permissions(0o755);

        let file = File::create(&new_archive_path).unwrap();
        let mut new_zip = zip::ZipWriter::new(file);

        // Loop over all of the files in the .docx archive
        for i in 0..archive.len() {
            let mut file_in_archive = archive.by_index(i).unwrap();
            let file_in_archive_name = &file_in_archive.name().to_string();
            if file_in_archive_name.to_string().ends_with(".xml") {
                let mut contents = String::new();
                file_in_archive.read_to_string(&mut contents).unwrap();
                let mut new_contents = contents.to_string();
                for value in &values {
                    let (target, new_target) = value;
                    // Perform text replacement
                    new_contents =
                        new_contents.replace(&target.to_string(), &new_target.to_string());
                }
                new_zip.start_file(file_in_archive_name, options)?;
                new_zip.write_all(new_contents.as_bytes())?;
            } else {
                new_zip.start_file(file_in_archive_name.to_string(), options)?;
                let mut buffer = Vec::new();
                file_in_archive.read_to_end(&mut buffer)?;
                new_zip.write_all(&buffer)?;
            }
        }
        std::fs::rename(new_archive_path, new_xlsx_path).unwrap();
        std::result::Result::Ok(())
    }

    use anyhow::*; // 导入anyhow库,用于错误处理
                   // use doe::{
                   //     // 导入doe库中的相关模块
                   //     Str,                                                              // 导入Str类型
                   //     xlsx::{xlsx_get_sheet_names, xlsx_to_csv, xlsx_to_csv_and_write}, // 导入xlsx模块中的函数
                   // };
    use std::{collections::BTreeMap, path::Path}; // 导入Path类型,用于处理文件路径

    // 以下代码片段导入了多个库和模块,主要用于处理Excel文件(xlsx格式)的读取和转换操作。
    // 具体功能包括获取Excel文件中的工作表名称、将Excel文件转换为CSV格式,以及将转换后的CSV数据写入文件。
    // 这些操作依赖于`doe`库中的`xlsx`模块,并且使用了`anyhow`库进行错误处理。

    /// 将CSV格式的数据转换为Markdown表格格式的字符串。
    ///
    /// # 参数
    /// - `csv`: 一个二维字符串向量,表示CSV数据。每一行是一个字符串向量,表示CSV的一行数据。
    ///
    /// # 返回值
    /// 返回一个字符串,表示转换后的Markdown表格。如果输入的CSV数据为空,则返回空字符串。
    pub fn csv_to_markdown(csv: &Vec<Vec<String>>) -> String {
        // 如果CSV数据为空,直接返回空字符串
        if csv.is_empty() {
            return String::new();
        }

        // 获取CSV的表头行
        let header_row = &csv[0];
        // 生成Markdown表格的分隔行,格式为 "|---|...|---|"
        let separator = format!("|{}|", vec!["---"; header_row.len()].join("|"));
        let mut md_table = Vec::new();

        // 添加表头行到Markdown表格中
        md_table.push(format!("| {} |", header_row.join(" | ")));

        // 添加分隔行到Markdown表格中
        md_table.push(separator);

        // 遍历CSV数据行(跳过表头行),并将每一行添加到Markdown表格中
        for data_row in csv.iter().skip(1) {
            md_table.push(format!("| {} |", data_row.join(" | ")));
        }

        // 将Markdown表格的每一行用换行符连接,形成最终的Markdown表格字符串
        md_table.join("\n")
    }

    /// 将 XLSX 文件转换为 Markdown 格式的字符串列表。
    ///
    /// 该函数读取指定的 XLSX 文件,并将其中的每个工作表转换为 Markdown 格式的字符串。
    /// 每个工作表的内容将被转换为一个 Markdown 字符串,并返回包含所有工作表 Markdown 字符串的 `BTreeMap`。
    ///
    /// # 参数
    /// - `xlsx_path`: XLSX 文件的路径,可以是任何实现了 `AsRef<Path>` 的类型。
    ///
    /// # 返回值
    /// - 返回 `Result<BTreeMap<String, String>>`,如果转换成功则返回 `Ok`,其中包含一个 `BTreeMap`:
    ///   - 键为工作表的名称。
    ///   - 值为对应工作表的 Markdown 格式字符串。
    /// - 如果转换过程中出现错误,则返回包含错误信息的 `Err`。
    pub fn xlsx_to_markdown(xlsx_path: impl AsRef<Path>) -> Result<BTreeMap<String, String>> {
        // 获取 XLSX 文件中的所有工作表名称
        let sheet_names = xlsx_get_sheet_names(xlsx_path.as_ref().to_string_lossy())
            .context("Failed to get sheet names from XLSX file")?;
        let mut res = BTreeMap::new();

        // 遍历每个工作表,将其转换为 Markdown 格式
        for sheet_name in sheet_names.iter() {
            // 将当前工作表转换为 CSV 格式的二维向量
            let csv: Vec<Vec<String>> =
                xlsx_to_csv(xlsx_path.as_ref().to_string_lossy(), sheet_name.to_string())
                    .map_err(|s| anyhow!(s.to_string()))?
                    .into_iter()
                    .map(|s| {
                        s.iter()
                            .map(|s| {
                                if s.is_empty() {
                                    // 如果单元格为空,则用 "-" 代替
                                    "-".to_string()
                                } else {
                                    // 去除单元格内容的前后空白字符
                                    s.trim().to_string()
                                }
                            })
                            .collect()
                    })
                    .filter(|s: &Vec<String>| {
                        let ss = s.clone().join("").replace("-", "");
                        !ss.is_empty()
                    })
                    .collect();

            // 将 CSV 格式的数据转换为 Markdown 格式的字符串
            let markdown_string = csv_to_markdown(&csv);

            // 将工作表名称和对应的 Markdown 字符串插入到结果映射中
            res.insert(sheet_name.to_string(), markdown_string);
        }

        // 转换成功,返回包含 Markdown 字符串和工作表名称的映射
        Ok(res)
    }

    /// 将 XLSX 文件转换为 Markdown 文件。
    ///
    /// 该函数读取指定的 XLSX 文件,并将其中的每个工作表转换为 Markdown 格式的文件。
    /// 每个工作表将生成一个对应的 `.md` 文件,文件名为工作表的名称。
    ///
    /// # 参数
    /// - `xlsx_path`: XLSX 文件的路径,可以是任何实现了 `AsRef<Path>` 的类型。
    /// - `output_path`: 输出 Markdown 文件的路径,可以是任何实现了 `AsRef<Path>` 的类型。
    ///
    /// # 返回值
    /// - 返回 `Result<()>`,如果转换成功则返回 `Ok(())`,否则返回包含错误信息的 `Err`。
    pub fn xlsx_to_markdown_write(
        xlsx_path: impl AsRef<Path>,
        output_path: impl AsRef<Path>,
    ) -> Result<()> {
        // 获取 XLSX 文件中的所有工作表名称
        let sheet_names = xlsx_get_sheet_names(xlsx_path.as_ref().to_string_lossy())
            .context("Failed to get sheet names from XLSX file")?;

        // 遍历每个工作表,将其转换为 Markdown 格式并保存为 `.md` 文件
        for sheet_name in sheet_names {
            // 将当前工作表转换为 CSV 格式的二维向量
            let csv: Vec<Vec<String>> =
                xlsx_to_csv(xlsx_path.as_ref().to_string_lossy(), sheet_name.to_string())
                    .map_err(|s| anyhow!(s.to_string()))?
                    .into_iter()
                    .map(|s| {
                        s.iter()
                            .map(|s| {
                                if s.is_empty() {
                                    // 如果单元格为空,则用 "-" 代替
                                    "-".to_string()
                                } else {
                                    // 去除单元格内容的前后空白字符
                                    s.trim().to_string()
                                }
                            })
                            .collect()
                    })
                    .filter(|s: &Vec<String>| {
                        let ss = s.clone().join("").replace("-", "");
                        !ss.is_empty()
                    })
                    .collect();

            // 将 CSV 格式的数据转换为 Markdown 格式的字符串
            let csv_string = csv_to_markdown(&csv);

            // 将 Markdown 字符串写入以工作表名称命名的 `.md` 文件
            if !output_path.as_ref().to_path_buf().exists() {
                std::fs::create_dir(output_path.as_ref().to_path_buf())?;
            }
            use crate::traits::traits::Str;
            let path = output_path
                .as_ref()
                .to_path_buf()
                .join(sheet_name.to_string().push_back(".md"));
            std::fs::write(path, csv_string)?;
        }

        // 转换成功,返回 `Ok(())`
        Ok(())
    }
}
#[cfg(feature = "xlsx")]
pub use xlsx::*;