use std::collections::HashSet;
use std::fmt::Write as _;
use crate::coordinate::{CellRange, Coordinate};
use crate::error::ExcelError;
use crate::spreadsheet::{Spreadsheet, Worksheet};
use crate::style::{Horizontal, Style, Vertical};
use crate::value::Value;
fn escape(text: &str) -> String {
text.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
fn color(color: &str) -> Option<String> {
let color = color.trim_start_matches('#');
if !matches!(color.len(), 6 | 8) || !color.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return None;
}
let color = if color.len() == 8 { &color[2..] } else { color };
Some(format!("#{}", color.to_ascii_uppercase()))
}
fn css_escape(text: &str) -> String {
let mut out = String::new();
for character in text.chars() {
if character.is_alphanumeric() || matches!(character, '_' | '-' | '.' | ' ') {
out.push(character);
} else {
let _ = write!(out, "\\{:x} ", u32::from(character));
}
}
out
}
fn is_safe_url(url: &str) -> bool {
let decoded = url
.replace(""", "\"")
.replace("'", "'")
.replace("'", "'")
.replace("<", "<")
.replace(">", ">")
.replace("&", "&");
let trimmed = decoded.trim_start().to_lowercase();
let scheme: String = trimmed
.chars()
.take_while(|character| {
character.is_alphanumeric()
|| *character == '_'
|| character.is_whitespace()
|| u32::from(*character) < 0x20
})
.collect();
if !trimmed[scheme.len()..].starts_with(':') || scheme.is_empty() {
return true;
}
["http", "https", "file", "ftp", "mailto", "s3"].contains(&scheme.as_str())
}
fn css(style: &Style, value: &Value) -> String {
let mut css = String::new();
let font = &style.font;
if font.bold == Some(true) {
css.push_str("font-weight:bold; ");
}
if font.italic == Some(true) {
css.push_str("font-style:italic; ");
}
match (font.underline == Some(true), font.strikethrough == Some(true)) {
(true, true) => css.push_str("text-decoration:underline line-through; "),
(true, false) => css.push_str("text-decoration:underline; "),
(false, true) => css.push_str("text-decoration:line-through; "),
_ => {}
}
if let Some(value) = font.color.as_deref().and_then(color) {
let _ = write!(css, "color:{value}; ");
}
if let Some(name) = &font.name {
let _ = write!(css, "font-family:'{}'; ", css_escape(name));
}
if let Some(size) = font.size {
let _ = write!(css, "font-size:{}pt; ", crate::value::format_float(size));
}
if let Some(fill) = style.fill.as_deref().and_then(color) {
let _ = write!(css, "background-color:{fill}; ");
}
let horizontal = match style.alignment.horizontal {
Some(Horizontal::Left) => Some("left"),
Some(Horizontal::Right) => Some("right"),
Some(Horizontal::Center | Horizontal::CenterContinuous) => Some("center"),
Some(Horizontal::Justify | Horizontal::Distributed) => Some("justify"),
_ => match value {
Value::Int(_) | Value::Float(_) => Some("right"),
Value::Bool(_) | Value::Error(_) => Some("center"),
_ => None,
},
};
if let Some(horizontal) = horizontal {
let _ = write!(css, "text-align:{horizontal}; ");
}
match style.alignment.vertical {
Some(Vertical::Top) => css.push_str("vertical-align:top; "),
Some(Vertical::Center) => css.push_str("vertical-align:middle; "),
Some(Vertical::Bottom) => css.push_str("vertical-align:bottom; "),
_ => {}
}
if style.alignment.wrap_text == Some(true) {
css.push_str("white-space:pre-wrap; ");
}
css.trim_end().to_owned()
}
fn sheet_html(sheet: &Worksheet, default_style: &Style, out: &mut String) -> Result<(), ExcelError> {
let _ = write!(
out,
"<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" class=\"sheet\">"
);
if sheet.cells().next().is_none() {
out.push_str("</table>\n");
return Ok(());
}
let last_row = sheet.highest_row();
let last_column = sheet.highest_column_index();
let mut spans = std::collections::HashMap::new();
let mut covered = HashSet::new();
for range in sheet.merges() {
if let CellRange::Cells(start, end) = CellRange::parse(range)? {
spans.insert(
(start.row, start.column),
(end.row - start.row + 1, end.column - start.column + 1),
);
for row in start.row..=end.row {
for column in start.column..=end.column {
if (row, column) != (start.row, start.column) {
covered.insert((row, column));
}
}
}
}
}
out.push_str("<colgroup>");
for column in 1..=last_column {
match sheet.column_dimensions().get(&column) {
Some(dimension) if dimension.hidden => out.push_str("<col style=\"display:none\">"),
Some(dimension) if dimension.width.is_some() => {
let width = dimension.width.unwrap_or_default() * 7.0 * 0.75;
let _ = write!(
out,
"<col style=\"width:{}pt\">",
crate::value::format_float(width.round())
);
}
_ => out.push_str("<col>"),
}
}
out.push_str("</colgroup>\n<tbody>\n");
for row in 1..=last_row {
match sheet.row_heights().get(&row) {
Some(height) => {
let _ = write!(out, "<tr style=\"height:{}pt\">", crate::value::format_float(*height));
}
None => out.push_str("<tr>"),
}
for column in 1..=last_column {
if covered.contains(&(row, column)) {
continue;
}
let coordinate = Coordinate::new(column, row);
let value = sheet.value_at(coordinate);
let style = default_style.merged(&sheet.effective_style(coordinate));
let mut content = match sheet.rich_text(coordinate) {
Some(runs) => runs
.iter()
.map(|run| {
let css = css(&style.merged(&run.style), &Value::Null);
let text = escape(&run.text).replace('\n', "<br />");
let text = if run.superscript {
format!("<sup>{text}</sup>")
} else if run.subscript {
format!("<sub>{text}</sub>")
} else {
text
};
format!("<span style=\"{}\">{text}</span>", escape(&css))
})
.collect(),
None => {
let text = match value {
Value::Null => String::new(),
Value::Formula(formula) => format!("={formula}"),
other => crate::number_formatter::format_value(
other,
style.number_format.as_deref().unwrap_or("General"),
),
};
escape(&text).replace('\n', "<br />")
}
};
if let Some(link) = sheet.hyperlink(coordinate)
&& !is_safe_url(&link.url)
{
content = escape(&link.url)
.chars()
.map(|character| {
if u32::from(character) < 0x20 {
format!("&#{};", u32::from(character))
} else {
character.to_string()
}
})
.collect();
} else if let Some(link) = sheet.hyperlink(coordinate) {
let title = link
.tooltip
.as_deref()
.map(|tip| format!(" title=\"{}\"", escape(tip)))
.unwrap_or_default();
content = format!("<a href=\"{}\"{title}>{content}</a>", escape(&link.url));
}
for drawing in sheet
.drawings()
.iter()
.filter(|drawing| drawing.coordinates == coordinate.to_string())
{
let source = match &drawing.content {
Some(bytes) => {
use base64::Engine;
let mime = if bytes.starts_with(b"\x89PNG") {
"image/png"
} else if bytes.starts_with(b"GIF") {
"image/gif"
} else {
"image/jpeg"
};
format!(
"data:{mime};base64,{}",
base64::engine::general_purpose::STANDARD.encode(bytes)
)
}
None => drawing.path.clone(),
};
let height = drawing
.height
.map(|height| format!(" height=\"{height}\""))
.unwrap_or_default();
let alt = drawing
.description
.as_deref()
.or(drawing.name.as_deref())
.unwrap_or_default();
let _ = write!(
content,
"<img src=\"{}\" alt=\"{}\"{height} />",
escape(&source),
escape(alt)
);
}
let mut attributes = String::new();
if let Some((rows, columns)) = spans.get(&(row, column)) {
if *columns > 1 {
let _ = write!(attributes, " colspan=\"{columns}\"");
}
if *rows > 1 {
let _ = write!(attributes, " rowspan=\"{rows}\"");
}
}
let css = css(&style, value);
if !css.is_empty() {
let _ = write!(attributes, " style=\"{}\"", escape(&css));
}
let _ = write!(out, "<td{attributes}>{content}</td>");
}
out.push_str("</tr>\n");
}
out.push_str("</tbody></table>\n");
Ok(())
}
pub(crate) fn html(spreadsheet: &Spreadsheet) -> Result<String, ExcelError> {
let sheet = spreadsheet.sheet(0).ok_or(ExcelError::NoSheetsFound)?;
let title = spreadsheet
.properties
.title
.clone()
.unwrap_or_else(|| sheet.title().to_owned());
let mut out = String::new();
let _ = write!(
out,
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n\
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n<title>{}</title>\n\
<style type=\"text/css\">\nhtml {{ font-family:Calibri, Arial, Helvetica, sans-serif; font-size:11pt; background-color:white }}\n\
table {{ border-collapse:collapse }}\ntd {{ padding:1px 3px; vertical-align:bottom }}\n</style>\n</head>\n<body>\n",
escape(&title)
);
sheet_html(sheet, &spreadsheet.default_style, &mut out)?;
out.push_str("</body>\n</html>\n");
Ok(out)
}
#[cfg(feature = "pdf")]
pub(crate) fn pdf(spreadsheet: &Spreadsheet) -> Result<Vec<u8>, ExcelError> {
let html = html(spreadsheet)?;
laravel_pdf::dompdf::Pdf::load_html(html)
.set_paper("letter", "portrait")
.output()
.map_err(|error| ExcelError::Write(error.to_string()))
}
#[cfg(not(feature = "pdf"))]
pub(crate) fn pdf(_spreadsheet: &Spreadsheet) -> Result<Vec<u8>, ExcelError> {
Err(ExcelError::UnsupportedType(
"PDF (enable the `pdf` feature of laravel-excel)".to_owned(),
"writing",
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::coordinate::Coordinate;
use crate::spreadsheet::Hyperlink;
fn rendered(build: impl FnOnce(&mut crate::spreadsheet::Worksheet)) -> String {
let mut spreadsheet = Spreadsheet::new();
let index = spreadsheet.create_sheet(None);
build(spreadsheet.sheet_mut(index).unwrap());
html(&spreadsheet).unwrap()
}
#[test]
fn links_with_other_schemes_are_written_as_text_like_php() {
let html = rendered(|sheet| {
for (row, url) in [
"javascript:alert(1)",
" JavaScript :alert(1)",
"data:text/html,x",
"https://laravel.com",
"/relative",
]
.into_iter()
.enumerate()
{
let coordinate = Coordinate::new(1, u32::try_from(row).unwrap() + 1);
sheet.set_value_at(coordinate, Value::from("click"));
sheet.set_hyperlink(
coordinate,
Hyperlink {
url: url.to_owned(),
tooltip: None,
},
);
}
});
assert!(
!html.contains("href=\"javascript")
&& !html.contains("href=\" JavaScript")
&& !html.contains("href=\"data:"),
"{html}"
);
assert!(html.contains("<td>javascript:alert(1)</td>"), "{html}");
assert!(html.contains("<a href=\"https://laravel.com\">click</a>"), "{html}");
assert!(html.contains("<a href=\"/relative\">click</a>"), "{html}");
}
#[test]
fn font_names_and_colors_stay_inside_the_style_attribute() {
let html = rendered(|sheet| {
let cell = sheet.cell_mut(Coordinate::new(1, 1));
cell.value = Value::from("x");
cell.style.font.name = Some("Arial\" onmouseover=\"alert(1)".to_owned());
cell.style.font.color = Some("red\" onclick=\"alert(1)".to_owned());
cell.style.fill = Some("FF00FF00".to_owned());
});
assert!(!html.contains("onmouseover=\"") && !html.contains("onclick"), "{html}");
assert!(
html.contains("font-family:'Arial\\22 onmouseover\\3d \\22 alert\\28 1\\29 '"),
"{html}"
);
assert!(html.contains("background-color:#00FF00"), "{html}");
}
}