Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add protection #155

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added lib/.DS_Store
Binary file not shown.
17 changes: 14 additions & 3 deletions lib/elixlsx/sheet.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ defmodule Elixlsx.Sheet do
merge_cells: [],
pane_freeze: nil,
show_grid_lines: true,
data_validations: []
data_validations: [],
protected: false

@type t :: %Sheet{
name: String.t(),
Expand All @@ -41,7 +42,8 @@ defmodule Elixlsx.Sheet do
merge_cells: [{String.t(), String.t()}],
pane_freeze: {number, number} | nil,
show_grid_lines: boolean(),
data_validations: list({String.t(), String.t(), list(String.t()) | String.t()})
data_validations: list({String.t(), String.t(), list(String.t()) | String.t()}),
protected: boolean()
}
@type rowcol_group :: Range.t() | {Range.t(), opts :: keyword}

Expand All @@ -55,6 +57,7 @@ defmodule Elixlsx.Sheet do
%Sheet{name: name}
end


defp split_cell_content_props(cell) do
cond do
is_list(cell) ->
Expand Down Expand Up @@ -222,8 +225,16 @@ defmodule Elixlsx.Sheet do
%{sheet | pane_freeze: nil}
end

@spec add_data_validations(Sheet.t(), String.t(), String.t(), String.t() | list(String.t())) :: Sheet.t()
@spec add_data_validations(Sheet.t(), String.t(), String.t(), list(String.t())) :: Sheet.t()
def add_data_validations(sheet, start_cell, end_cell, values) do
%{sheet | data_validations: [{start_cell, end_cell, values} | sheet.data_validations]}
end

@spec set_protected(Sheet.t()) :: Sheet.t()
@doc ~S"""
Set protection on the sheet so that cells may be set to locked (readonly).
"""
def set_protected(sheet) do
%{sheet | protected: true}
end
end
9 changes: 6 additions & 3 deletions lib/elixlsx/style/cell_style.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,26 @@ defmodule Elixlsx.Style.CellStyle do
alias Elixlsx.Style.Font
alias Elixlsx.Style.Fill
alias Elixlsx.Style.BorderStyle
alias Elixlsx.Style.Protection

defstruct font: nil, fill: nil, numfmt: nil, border: nil
defstruct font: nil, fill: nil, numfmt: nil, border: nil, protection: nil

@type t :: %CellStyle{
font: Font.t(),
fill: Fill.t(),
numfmt: NumFmt.t(),
border: BorderStyle.t()
border: BorderStyle.t(),
protection: Protection.t()
}

def from_props(props) do
font = Font.from_props(props)
fill = Fill.from_props(props)
numfmt = NumFmt.from_props(props)
border = BorderStyle.from_props(props[:border])
protection = Protection.from_props(props)

%CellStyle{font: font, fill: fill, numfmt: numfmt, border: border}
%CellStyle{font: font, fill: fill, numfmt: numfmt, border: border, protection: protection}
end

def is_date?(cellstyle) do
Expand Down
24 changes: 24 additions & 0 deletions lib/elixlsx/style/protection.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

defmodule Elixlsx.Style.Protection do
@moduledoc ~S"""
Protection properties.

- locked: boolean
"""
alias __MODULE__

defstruct locked: nil

@type t :: %Protection{
locked: boolean
}

@doc ~S"""
Create a Protection object from a property list.
"""
def from_props(props) do
ft = %Protection{locked: props[:locked]}

if ft == %Protection{}, do: nil, else: ft
end
end
62 changes: 51 additions & 11 deletions lib/elixlsx/xml_templates.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ defmodule Elixlsx.XMLTemplates do
alias Elixlsx.Style.Font
alias Elixlsx.Style.Fill
alias Elixlsx.Style.BorderStyle
alias Elixlsx.Style.Protection
alias Elixlsx.Sheet

# TODO: the xml_text_exape functions belong into Elixlsx.Util,
Expand Down Expand Up @@ -90,7 +91,9 @@ defmodule Elixlsx.XMLTemplates do
def make_xl_rel_sheet(sheet_comp_info) do
# I'd love to use string interpolation here, but unfortunately """< is heredoc notation, so i have to use
# string concatenation or escape all the quotes. Choosing the first.
"<Relationship Id=\"#{sheet_comp_info.rId}\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/#{sheet_comp_info.filename}\"/>"
"<Relationship Id=\"#{sheet_comp_info.rId}\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet\" Target=\"worksheets/#{
sheet_comp_info.filename
}\"/>"
end

@spec make_xl_rel_sheets(nonempty_list(SheetCompInfo.t())) :: String.t()
Expand Down Expand Up @@ -122,7 +125,9 @@ defmodule Elixlsx.XMLTemplates do
end

"""
<sheet name="#{xml_escape(sheet_info.name)}" sheetId="#{sheet_comp_info.sheetId}" state="visible" r:id="#{sheet_comp_info.rId}"/>
<sheet name="#{xml_escape(sheet_info.name)}" sheetId="#{sheet_comp_info.sheetId}" state="visible" r:id="#{
sheet_comp_info.rId
}"/>
"""
end

Expand Down Expand Up @@ -298,7 +303,9 @@ defmodule Elixlsx.XMLTemplates do

defp make_data_validation({start_cell, end_cell, values}) when is_bitstring(values) do
"""
<dataValidation type="list" allowBlank="1" showErrorMessage="1" sqref="#{start_cell}:#{end_cell}">
<dataValidation type="list" allowBlank="1" showErrorMessage="1" sqref="#{start_cell}:#{
end_cell
}">
<formula1>#{values}</formula1>
</dataValidation>
"""
Expand All @@ -313,7 +320,9 @@ defmodule Elixlsx.XMLTemplates do
|> Enum.join("&quot;&amp;&quot;")

"""
<dataValidation type="list" allowBlank="1" showErrorMessage="1" sqref="#{start_cell}:#{end_cell}">
<dataValidation type="list" allowBlank="1" showErrorMessage="1" sqref="#{start_cell}:#{
end_cell
}">
<formula1>&quot;#{joined_values}&quot;</formula1>
</dataValidation>
"""
Expand All @@ -326,17 +335,29 @@ defmodule Elixlsx.XMLTemplates do
defp xl_merge_cells(merge_cells) do
"""
<mergeCells count="#{Enum.count(merge_cells)}">
#{Enum.map(merge_cells, fn {fromCell, toCell} -> "<mergeCell ref=\"#{fromCell}:#{toCell}\"/>" end)}
#{
Enum.map(merge_cells, fn {fromCell, toCell} ->
"<mergeCell ref=\"#{fromCell}:#{toCell}\"/>"
end)
}
</mergeCells>
"""
end

defp xl_sheet_protection(%Sheet{protected: true}) do
"<sheetProtection sheet=\"1\" objects=\"1\" scenarios=\"1\"/>"
end

defp xl_sheet_protection(_), do: ""

defp xl_sheet_rows(data, row_heights, grouping_info, wci) do
rows =
Enum.zip(data, 1..length(data))
|> Enum.map_join(fn {row, rowidx} ->
"""
<row r="#{rowidx}" #{get_row_height_attr(row_heights, rowidx)}#{get_row_grouping_attr(grouping_info, rowidx)}>
<row r="#{rowidx}" #{get_row_height_attr(row_heights, rowidx)}#{
get_row_grouping_attr(grouping_info, rowidx)
}>
#{xl_sheet_cols(row, rowidx, wci)}
</row>
"""
Expand Down Expand Up @@ -409,7 +430,7 @@ defmodule Elixlsx.XMLTemplates do
outline_level_attr = if outline_level, do: " outlineLevel=\"#{outline_level}\"", else: ""
collapsed_attr = if collapsed, do: " collapsed=\"1\"", else: ""

~c'<col min="#{k}" max="#{k}"#{width_attr}#{hidden_attr}#{outline_level_attr}#{collapsed_attr} />'
'<col min="#{k}" max="#{k}"#{width_attr}#{hidden_attr}#{outline_level_attr}#{collapsed_attr} />'
end

defp make_cols(sheet) do
Expand Down Expand Up @@ -464,7 +485,7 @@ defmodule Elixlsx.XMLTemplates do
def make_sheet(sheet, wci) do
grouping_info = get_grouping_info(sheet.group_rows)

~S"""
~S"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheetPr filterMode="false">
Expand Down Expand Up @@ -497,6 +518,7 @@ defmodule Elixlsx.XMLTemplates do
</sheetData>
""" <>
xl_merge_cells(sheet.merge_cells) <>
xl_sheet_protection(sheet) <>
make_data_validations(sheet.data_validations) <>
"""
<pageMargins left="0.75" right="0.75" top="1" bottom="1.0" header="0.5" footer="0.5"/>
Expand Down Expand Up @@ -540,7 +562,9 @@ defmodule Elixlsx.XMLTemplates do
top_left_cell = U.to_excel_coords(row_idx + 1, col_idx + 1)

{"pane=\"#{pane}\"",
"<pane xSplit=\"#{col_idx}\" ySplit=\"#{row_idx}\" topLeftCell=\"#{top_left_cell}\" activePane=\"#{pane}\" state=\"frozen\" />"}
"<pane xSplit=\"#{col_idx}\" ySplit=\"#{row_idx}\" topLeftCell=\"#{top_left_cell}\" activePane=\"#{
pane
}\" state=\"frozen\" />"}

_any ->
{"", ""}
Expand All @@ -559,7 +583,9 @@ defmodule Elixlsx.XMLTemplates do

"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="#{len}" uniqueCount="#{len}">
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="#{len}" uniqueCount="#{
len
}">
""" <>
Enum.map_join(stringlist, fn {_, value} ->
# the only two characters that *must* be replaced for safe XML encoding are & and <:
Expand Down Expand Up @@ -618,15 +644,24 @@ defmodule Elixlsx.XMLTemplates do
alignment ->
{"applyAlignment=\"1\"", alignment}
end
end

{apply_protection, protection_tag} =
case style.protection do
nil ->
{"", ""}

protection -> {"applyProtection=\"1\"", "<protection #{protection_attrs(protection)}/>"}
end

"""
<xf borderId="#{borderid}"
fillId="#{fillid}"
fontId="#{fontid}"
numFmtId="#{numfmtid}"
xfId="0" #{apply_alignment}>
xfId="0" #{apply_alignment} #{apply_protection}>
#{wrap_text_tag}
#{protection_tag}
</xf>
"""
end
Expand Down Expand Up @@ -795,4 +830,9 @@ defmodule Elixlsx.XMLTemplates do
</workbook>
"""
end

@spec protection_attrs(Protection.t()) :: String.t()
defp protection_attrs(%Protection{locked: true}), do: "locked=\"1\" "
defp protection_attrs(%Protection{locked: false}), do: "locked=\"0\" "
defp protection_attrs(_), do: ""
end
Loading