read_and_copy/
read_and_copy.rs

1use edit_xlsx::{Workbook, WorkbookResult, WorkSheetCol, Read, Write, WorkSheetRow};
2
3/// **NOTICE**: Reading is an experimental feature,
4/// in the current version it performs better for reading and overwriting text, styles,
5/// and worse for formulas, links, etc.
6
7fn main() -> WorkbookResult<()> {
8    // Read an existed workbook
9    let reading_book = Workbook::from_path("./tests/xlsx/accounting.xlsx")?;
10    let reading_sheet = reading_book.get_worksheet_by_name("worksheet")?;
11    // Create a new workbook to write
12    let mut writing_book = Workbook::new();
13    let writing_sheet = writing_book.get_worksheet_mut(1)?;
14
15    // Synchronous column width and format
16    let columns_map = reading_sheet.get_columns_with_format("A:XFD")?;
17    match reading_sheet.get_default_column() {
18        None => writing_sheet.set_default_column_adaptive(),
19        Some(width) => writing_sheet.set_default_column(width),
20    }
21    columns_map.iter().for_each(|(col_range, (column, format))| {
22        if let Some(format) = format {
23            // if col format exists, write it to writing_sheet
24            writing_sheet.set_columns_with_format(col_range, column, format).unwrap()
25        } else {
26            writing_sheet.set_columns(col_range, column).unwrap()
27        }
28    });
29
30    // Synchronous row height and format
31    writing_sheet.set_default_row(reading_sheet.get_default_row());
32    for row_number in 1..=reading_sheet.max_row() {
33        let (row, format) = reading_sheet.get_row_with_format(row_number)?;
34        if let Some(format) = format {
35            // if col format exists, write it to writing_sheet
36            writing_sheet.set_row_with_format(row_number, &row, &format)?;
37        } else {
38            writing_sheet.set_row(row_number, &row)?;
39        }
40    }
41
42    // Read then write text and format
43    for row in 1..=reading_sheet.max_row() {
44        for col in 1..=reading_sheet.max_column() {
45            if let Ok(cell) = reading_sheet.read_cell((row, col)) {
46                writing_sheet.write_cell((row, col), &cell)?;
47            }
48        }
49    }
50
51    writing_book.save_as("./examples/read_and_copy.xlsx")?;
52    Ok(())
53}