/* # to read excel calamine = "0.23.1" # to write excel xlsxwriter = "0.6.0" */ use calamine::{open_workbook_auto, Reader, Range, DataType, Error}; use text_blind_watermark::TextBlindWM; use xlsxwriter::{format::*, Workbook}; pub struct XlsxWatermark { text_wm: TextBlindWM, } impl XlsxWatermark { pub fn new(pwd: &str) -> Self { Self { text_wm: TextBlindWM::new_with_char(pwd, 0x200b, 0xfeff) } } pub fn embed(&self, filename: &str, file_with_wm: &str, wm: &str) { let mut workbook = open_workbook_auto(filename).unwrap(); let sheet_names = workbook.sheet_names().to_owned(); // println!("the first sheet name {:?}", sheet_names); let sheet_name = &sheet_names[0]; let mut range = workbook.worksheet_range(sheet_name).unwrap(); // 将修改后的数据写入新的 xlsx 文件中 let workbook = Workbook::new(file_with_wm).unwrap(); let mut worksheet = workbook.add_worksheet(None).unwrap(); let mut embed_cnt = 0; for (row_idx, row) in range.rows().enumerate() { for (col_idx, cell) in row.iter().enumerate() { // 这里您可能需要根据 cell 类型进行处理,然后写入相应的数据类型 match cell { calamine::DataType::String(str1) => { if embed_cnt == 0 { // println!("原始:({},{}) [{:?}]", row_idx, col_idx, str1); let str1 = self.text_wm.embed(str1, wm); // println!("打上水印后:[{:?}]", str1); worksheet.write_string(row_idx as u32, col_idx as u16, &str1, None).unwrap(); embed_cnt += 1; } else { worksheet.write_string(row_idx as u32, col_idx as u16, str1, None).unwrap(); } } calamine::DataType::Float(float1) => { worksheet.write_number(row_idx as u32, col_idx as u16, *float1, None).unwrap(); } // 处理其他 calamine::DataType 类型... _ => {} } } } workbook.close().unwrap(); } pub fn extract(&self, file_with_wm: &str) -> String { let mut workbook = open_workbook_auto(file_with_wm).unwrap(); let sheet_names = workbook.sheet_names().to_owned(); // println!("{:?}", sheet_names); let sheet_name = &sheet_names[0]; let mut range = workbook.worksheet_range(sheet_name).unwrap(); for (row_idx, row) in range.rows().enumerate() { for (col_idx, cell) in row.iter().enumerate() { match cell { calamine::DataType::String(str1) => { let wm_extract = self.text_wm.extract(str1); if wm_extract.len() > 0 { println!("水印:{}", String::from_utf8_lossy(&wm_extract)); let a = String::from_utf8_lossy(wm_extract.as_slice()).to_string(); return a; } } calamine::DataType::Float(float1) => {} // 处理其他 calamine::DataType 类型... _ => {} } } } return "".to_string(); } }