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 1 commit
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
Next Next commit
Add ability to protect cells
  • Loading branch information
tnyavdc committed Sep 9, 2024
commit f10ec9482c9fbdd9aa7aba38ff5d38208c56f2fb
Binary file added .DS_Store
Binary file not shown.
31 changes: 31 additions & 0 deletions hex_metadata.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{<<"app">>,<<"elixlsx">>}.
{<<"build_tools">>,[<<"mix">>]}.
{<<"description">>,
<<"Elixlsx is a writer for the MS Excel OpenXML format (`.xlsx`).">>}.
{<<"elixir">>,<<"~> 1.12">>}.
{<<"files">>,
[<<"lib">>,<<"lib/elixlsx.ex">>,<<"lib/elixlsx">>,<<"lib/elixlsx/style">>,
<<"lib/elixlsx/style/fill.ex">>,<<"lib/elixlsx/style/cell_style.ex">>,
<<"lib/elixlsx/style/num_fmt.ex">>,<<"lib/elixlsx/style/border.ex">>,
<<"lib/elixlsx/style/font.ex">>,<<"lib/elixlsx/style/border_style.ex">>,
<<"lib/elixlsx/xml.ex">>,<<"lib/elixlsx/compiler">>,
<<"lib/elixlsx/compiler/num_fmt_db.ex">>,
<<"lib/elixlsx/compiler/string_db.ex">>,
<<"lib/elixlsx/compiler/cell_style_db.ex">>,
<<"lib/elixlsx/compiler/fill_db.ex">>,
<<"lib/elixlsx/compiler/border_db.ex">>,
<<"lib/elixlsx/compiler/db_util.ex">>,
<<"lib/elixlsx/compiler/sheet_comp_info.ex">>,
<<"lib/elixlsx/compiler/workbook_comp_info.ex">>,
<<"lib/elixlsx/compiler/font_db.ex">>,<<"lib/elixlsx/writer.ex">>,
<<"lib/elixlsx/workbook.ex">>,<<"lib/elixlsx/xml_templates.ex">>,
<<"lib/elixlsx/compiler.ex">>,<<"lib/elixlsx/sheet.ex">>,
<<"lib/elixlsx/util.ex">>,<<"lib/elixlsx/color.ex">>,<<".formatter.exs">>,
<<"mix.exs">>,<<"README.md">>,<<"LICENSE">>,<<"CHANGELOG.md">>]}.
{<<"licenses">>,[<<"MIT">>]}.
{<<"links">>,
[{<<"Changelog">>,<<"https://hexdocs.pm/elixlsx/changelog.html">>},
{<<"GitHub">>,<<"https://github.com/xou/elixlsx">>}]}.
{<<"name">>,<<"elixlsx">>}.
{<<"requirements">>,[]}.
{<<"version">>,<<"0.6.0">>}.
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
2 changes: 1 addition & 1 deletion lib/elixlsx/util.ex
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ defmodule Elixlsx.Util do

to_string(
:io_lib.format(
~c"~4.10.0b-~2.10.0b-~2.10.0bT~2.10.0b:~2.10.0b:~2.10.0bZ",
'~4.10.0b-~2.10.0b-~2.10.0bT~2.10.0b:~2.10.0b:~2.10.0bZ',
[y, m, d, hours, minutes, seconds]
)
)
Expand Down
16 changes: 8 additions & 8 deletions lib/elixlsx/writer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ defmodule Elixlsx.Writer do
Returns a tuple `{'docProps/app.xml', "XML Data"}`.
"""
def get_docProps_app_xml(_) do
{~c"docProps/app.xml", XMLTemplates.docprops_app()}
{'docProps/app.xml', XMLTemplates.docprops_app()}
end

@spec get_docProps_core_xml(Workbook.t()) :: zip_tuple
def get_docProps_core_xml(workbook) do
timestamp = U.iso_timestamp(workbook.datetime)
{~c"docProps/core.xml", XMLTemplates.docprops_core(timestamp)}
{'docProps/core.xml', XMLTemplates.docprops_core(timestamp)}
end

@spec get_docProps_dir(Workbook.t()) :: list(zip_tuple)
Expand All @@ -53,7 +53,7 @@ defmodule Elixlsx.Writer do
Returns the filename `_rels/.rels` and it's content as a tuple.
"""
def get__rels_dotrels(_) do
{~c"_rels/.rels", XMLTemplates.rels_dotrels()}
{'_rels/.rels', XMLTemplates.rels_dotrels()}
end

@spec get__rels_dir(Workbook.t()) :: list(zip_tuple)
Expand All @@ -67,7 +67,7 @@ defmodule Elixlsx.Writer do
@spec get_xl_rels_dir(any, [SheetCompInfo.t()], non_neg_integer) :: list(zip_tuple)
def get_xl_rels_dir(_, sheetCompInfos, next_rId) do
[
{~c"xl/_rels/workbook.xml.rels",
{'xl/_rels/workbook.xml.rels',
~S"""
<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
Expand All @@ -83,17 +83,17 @@ defmodule Elixlsx.Writer do

@spec get_xl_styles_xml(WorkbookCompInfo.t()) :: zip_tuple
def get_xl_styles_xml(wci) do
{~c"xl/styles.xml", XMLTemplates.make_xl_styles(wci)}
{'xl/styles.xml', XMLTemplates.make_xl_styles(wci)}
end

@spec get_xl_workbook_xml(Workbook.t(), [SheetCompInfo.t()]) :: zip_tuple
def get_xl_workbook_xml(data, sheetCompInfos) do
{~c"xl/workbook.xml", XMLTemplates.make_workbook_xml(data, sheetCompInfos)}
{'xl/workbook.xml', XMLTemplates.make_workbook_xml(data, sheetCompInfos)}
end

@spec get_xl_sharedStrings_xml(any, WorkbookCompInfo.t()) :: zip_tuple
def get_xl_sharedStrings_xml(_, wci) do
{~c"xl/sharedStrings.xml",
{'xl/sharedStrings.xml',
XMLTemplates.make_xl_shared_strings(StringDB.sorted_id_string_tuples(wci.stringdb))}
end

Expand All @@ -113,7 +113,7 @@ defmodule Elixlsx.Writer do
end

def get_contentTypes_xml(_, wci) do
{~c"[Content_Types].xml", XMLTemplates.make_contenttypes_xml(wci)}
{'[Content_Types].xml', XMLTemplates.make_contenttypes_xml(wci)}
end

def get_xl_dir(data, wci) do
Expand Down
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