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)
}
}
#[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");
}
}
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)))
}
}