1use serde::{de::DeserializeOwned, Serialize};
6use wordval_core::{Error, Result};
7
8pub enum ExportFormat {
10 Csv,
11 Json,
12 Xlsx,
13}
14
15pub struct Export;
17
18impl Export {
19 pub fn to_csv(
34 columns: &[&str],
35 rows: &[std::collections::HashMap<String, String>],
36 ) -> Result<String> {
37 let mut w = csv::Writer::from_writer(Vec::new());
38 let headers: Vec<std::borrow::Cow<'_, str>> =
41 columns.iter().map(|c| sanitize_cell(c)).collect();
42 w.write_record(headers.iter().map(|h| h.as_ref()))
43 .map_err(|e| Error::Msg(format!("CSV写入失败: {}", e)))?;
44 for row in rows {
45 let vals: Vec<std::borrow::Cow<'_, str>> = columns
46 .iter()
47 .map(|c| {
48 row.get(*c)
49 .map(|s| sanitize_cell(s))
50 .unwrap_or(std::borrow::Cow::Borrowed(""))
51 })
52 .collect();
53 w.write_record(vals.iter().map(|v| v.as_ref()))
54 .map_err(|e| Error::Msg(format!("CSV写入失败: {}", e)))?;
55 }
56 let data = w
57 .into_inner()
58 .map_err(|e| Error::Msg(format!("CSV输出失败: {}", e)))?;
59 String::from_utf8(data).map_err(|e| Error::Msg(format!("UTF8转换失败: {}", e)))
60 }
61
62 pub fn to_json<T: Serialize>(items: &[T]) -> Result<String> {
64 serde_json::to_string_pretty(items)
65 .map_err(|e| Error::Msg(format!("JSON序列化失败: {}", e)))
66 }
67
68 pub fn to_xlsx(
73 columns: &[&str],
74 rows: &[std::collections::HashMap<String, String>],
75 ) -> Result<Vec<u8>> {
76 let csv_content = Self::to_csv(columns, rows)?;
77 let bom = vec![0xEFu8, 0xBB, 0xBF];
78 let mut data = bom;
79 data.extend(csv_content.as_bytes());
80 Ok(data)
81 }
82}
83
84fn sanitize_cell(value: &str) -> std::borrow::Cow<'_, str> {
94 fn is_dangerous(byte: Option<&u8>) -> bool {
96 matches!(
97 byte,
98 Some(b'=') | Some(b'+') | Some(b'-') | Some(b'@') | Some(b'\t') | Some(b'\r')
99 )
100 }
101 if is_dangerous(value.as_bytes().first()) || is_dangerous(value.trim_start().as_bytes().first())
104 {
105 std::borrow::Cow::Owned(format!("'{}", value))
106 } else {
107 std::borrow::Cow::Borrowed(value)
109 }
110}
111
112pub struct Import;
114
115impl Import {
116 pub fn from_csv(csv_str: &str) -> Result<Vec<std::collections::HashMap<String, String>>> {
118 let mut reader = csv::Reader::from_reader(csv_str.as_bytes());
119 let headers = reader
120 .headers()
121 .map_err(|e| Error::Msg(format!("CSV头解析失败: {}", e)))?
122 .clone();
123 let mut rows = Vec::new();
124 for result in reader.records() {
125 let record = result.map_err(|e| Error::Msg(format!("CSV行解析失败: {}", e)))?;
126 let mut map = std::collections::HashMap::new();
127 for (i, val) in record.iter().enumerate() {
128 if let Some(h) = headers.get(i) {
129 map.insert(h.to_string(), val.to_string());
130 }
131 }
132 rows.push(map);
133 }
134 Ok(rows)
135 }
136
137 pub fn from_json<T: DeserializeOwned>(json_str: &str) -> Result<Vec<T>> {
139 serde_json::from_str(json_str).map_err(|e| Error::Msg(format!("JSON解析失败: {}", e)))
140 }
141}
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 #[test]
148 fn sanitize_cell_neutralizes_formula_chars() {
149 assert_eq!(
150 sanitize_cell("=HYPERLINK(\"https://evil\")"),
151 "'=HYPERLINK(\"https://evil\")"
152 );
153 assert_eq!(sanitize_cell("+1+1"), "'+1+1");
154 assert_eq!(sanitize_cell("-1+1"), "'-1+1");
155 assert_eq!(sanitize_cell("@SUM(A1)"), "'@SUM(A1)");
156 assert_eq!(sanitize_cell("\tcmd"), "'\tcmd");
157 assert_eq!(sanitize_cell("\r\n"), "'\r\n");
158 }
159
160 #[test]
161 fn sanitize_cell_leaves_safe_values() {
162 assert_eq!(sanitize_cell("hello"), "hello");
163 assert_eq!(sanitize_cell("123"), "123");
164 assert_eq!(sanitize_cell("=1=1"), "'=1=1"); assert_eq!(sanitize_cell(""), "");
166 }
167
168 #[test]
169 fn sanitize_cell_resists_leading_whitespace() {
170 assert_eq!(sanitize_cell(" =cmd"), "' =cmd");
172 assert_eq!(sanitize_cell(" +cmd"), "' +cmd");
173 }
174
175 fn rec(id: &str, name: &str) -> std::collections::HashMap<String, String> {
176 let mut m = std::collections::HashMap::new();
177 m.insert("id".to_string(), id.to_string());
178 m.insert("name".to_string(), name.to_string());
179 m
180 }
181
182 #[test]
183 fn export_csv_json_xlsx_roundtrip() {
184 let rows = vec![rec("1", "=evil"), rec("2", "ok")];
185 let csv = Export::to_csv(&["id", "name", "missing"], &rows).unwrap();
186 assert!(csv.starts_with("id,name,missing\n"), "{}", csv);
188 assert!(csv.contains("'=") || csv.contains("\"'="), "危险值应中性化: {}", csv);
189 let back = Import::from_csv(&csv).unwrap();
191 assert_eq!(back.len(), 2);
192 assert_eq!(back[1].get("id").unwrap(), "2");
193 assert_eq!(back[0].get("name").unwrap(), "'=evil", "中性化前缀随导出落盘");
194 assert_eq!(back[0].get("missing").unwrap(), "", "缺失列导出为空串");
195 let json = Export::to_json(&back).unwrap();
197 let items: Vec<std::collections::HashMap<String, String>> =
198 Import::from_json(&json).unwrap();
199 assert_eq!(items.len(), 2);
200 let x = Export::to_xlsx(&["id", "name"], &rows).unwrap();
202 assert_eq!(&x[..3], &[0xEF, 0xBB, 0xBF]);
203 assert!(String::from_utf8_lossy(&x[3..]).starts_with("id,name\n"));
204 }
205
206 #[test]
207 fn import_error_paths() {
208 assert!(Import::from_csv("a,b\n1,2,3\n").is_err());
210 assert!(Import::from_json::<Vec<String>>("not-json").is_err());
212 }
213}