use serde::{de::DeserializeOwned, Serialize};
use wordval_core::{Error, Result};
pub enum ExportFormat {
Csv,
Json,
Xlsx,
}
pub struct Export;
impl Export {
pub fn to_csv(
columns: &[&str],
rows: &[std::collections::HashMap<String, String>],
) -> Result<String> {
let mut w = csv::Writer::from_writer(Vec::new());
let headers: Vec<std::borrow::Cow<'_, str>> =
columns.iter().map(|c| sanitize_cell(c)).collect();
w.write_record(headers.iter().map(|h| h.as_ref()))
.map_err(|e| Error::Msg(format!("CSV写入失败: {}", e)))?;
for row in rows {
let vals: Vec<std::borrow::Cow<'_, str>> = columns
.iter()
.map(|c| {
row.get(*c)
.map(|s| sanitize_cell(s))
.unwrap_or(std::borrow::Cow::Borrowed(""))
})
.collect();
w.write_record(vals.iter().map(|v| v.as_ref()))
.map_err(|e| Error::Msg(format!("CSV写入失败: {}", e)))?;
}
let data = w
.into_inner()
.map_err(|e| Error::Msg(format!("CSV输出失败: {}", e)))?;
String::from_utf8(data).map_err(|e| Error::Msg(format!("UTF8转换失败: {}", e)))
}
pub fn to_json<T: Serialize>(items: &[T]) -> Result<String> {
serde_json::to_string_pretty(items)
.map_err(|e| Error::Msg(format!("JSON序列化失败: {}", e)))
}
pub fn to_xlsx(
columns: &[&str],
rows: &[std::collections::HashMap<String, String>],
) -> Result<Vec<u8>> {
let csv_content = Self::to_csv(columns, rows)?;
let bom = vec![0xEFu8, 0xBB, 0xBF];
let mut data = bom;
data.extend(csv_content.as_bytes());
Ok(data)
}
}
fn sanitize_cell(value: &str) -> std::borrow::Cow<'_, str> {
fn is_dangerous(byte: Option<&u8>) -> bool {
matches!(
byte,
Some(b'=') | Some(b'+') | Some(b'-') | Some(b'@') | Some(b'\t') | Some(b'\r')
)
}
if is_dangerous(value.as_bytes().first()) || is_dangerous(value.trim_start().as_bytes().first())
{
std::borrow::Cow::Owned(format!("'{}", value))
} else {
std::borrow::Cow::Borrowed(value)
}
}
pub struct Import;
impl Import {
pub fn from_csv(csv_str: &str) -> Result<Vec<std::collections::HashMap<String, String>>> {
let mut reader = csv::Reader::from_reader(csv_str.as_bytes());
let headers = reader
.headers()
.map_err(|e| Error::Msg(format!("CSV头解析失败: {}", e)))?
.clone();
let mut rows = Vec::new();
for result in reader.records() {
let record = result.map_err(|e| Error::Msg(format!("CSV行解析失败: {}", e)))?;
let mut map = std::collections::HashMap::new();
for (i, val) in record.iter().enumerate() {
if let Some(h) = headers.get(i) {
map.insert(h.to_string(), val.to_string());
}
}
rows.push(map);
}
Ok(rows)
}
pub fn from_json<T: DeserializeOwned>(json_str: &str) -> Result<Vec<T>> {
serde_json::from_str(json_str).map_err(|e| Error::Msg(format!("JSON解析失败: {}", e)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanitize_cell_neutralizes_formula_chars() {
assert_eq!(
sanitize_cell("=HYPERLINK(\"https://evil\")"),
"'=HYPERLINK(\"https://evil\")"
);
assert_eq!(sanitize_cell("+1+1"), "'+1+1");
assert_eq!(sanitize_cell("-1+1"), "'-1+1");
assert_eq!(sanitize_cell("@SUM(A1)"), "'@SUM(A1)");
assert_eq!(sanitize_cell("\tcmd"), "'\tcmd");
assert_eq!(sanitize_cell("\r\n"), "'\r\n");
}
#[test]
fn sanitize_cell_leaves_safe_values() {
assert_eq!(sanitize_cell("hello"), "hello");
assert_eq!(sanitize_cell("123"), "123");
assert_eq!(sanitize_cell("=1=1"), "'=1=1"); assert_eq!(sanitize_cell(""), "");
}
#[test]
fn sanitize_cell_resists_leading_whitespace() {
assert_eq!(sanitize_cell(" =cmd"), "' =cmd");
assert_eq!(sanitize_cell(" +cmd"), "' +cmd");
}
fn rec(id: &str, name: &str) -> std::collections::HashMap<String, String> {
let mut m = std::collections::HashMap::new();
m.insert("id".to_string(), id.to_string());
m.insert("name".to_string(), name.to_string());
m
}
#[test]
fn export_csv_json_xlsx_roundtrip() {
let rows = vec![rec("1", "=evil"), rec("2", "ok")];
let csv = Export::to_csv(&["id", "name", "missing"], &rows).unwrap();
assert!(csv.starts_with("id,name,missing\n"), "{}", csv);
assert!(csv.contains("'=") || csv.contains("\"'="), "危险值应中性化: {}", csv);
let back = Import::from_csv(&csv).unwrap();
assert_eq!(back.len(), 2);
assert_eq!(back[1].get("id").unwrap(), "2");
assert_eq!(back[0].get("name").unwrap(), "'=evil", "中性化前缀随导出落盘");
assert_eq!(back[0].get("missing").unwrap(), "", "缺失列导出为空串");
let json = Export::to_json(&back).unwrap();
let items: Vec<std::collections::HashMap<String, String>> =
Import::from_json(&json).unwrap();
assert_eq!(items.len(), 2);
let x = Export::to_xlsx(&["id", "name"], &rows).unwrap();
assert_eq!(&x[..3], &[0xEF, 0xBB, 0xBF]);
assert!(String::from_utf8_lossy(&x[3..]).starts_with("id,name\n"));
}
#[test]
fn import_error_paths() {
assert!(Import::from_csv("a,b\n1,2,3\n").is_err());
assert!(Import::from_json::<Vec<String>>("not-json").is_err());
}
}