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 defined_names to Workbook #156

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
15 changes: 13 additions & 2 deletions lib/elixlsx/workbook.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@ defmodule Elixlsx.Workbook do

The datetime property can optionally be set to override
the "created at" date. It defaults to the current time.

The defined_names property is a map of defined names in the workbook.
"""
alias Elixlsx.Sheet
alias Elixlsx.Workbook

defstruct sheets: [], datetime: nil
defstruct sheets: [], datetime: nil, defined_names: %{}

@type t :: %Workbook{
sheets: nonempty_list(Sheet.t()),
datetime: String.t() | integer | nil
datetime: String.t() | integer | nil,
defined_names: %{String.t() => String.t()}
}

@doc "Append a sheet at the end."
Expand All @@ -30,4 +33,12 @@ defmodule Elixlsx.Workbook do
def insert_sheet(workbook, sheet, at \\ 0) do
update_in(workbook.sheets, &List.insert_at(&1, at, sheet))
end

@doc """
Add a defined name to the workbook.
"""
@spec add_defined_name(Workbook.t(), String.t(), String.t()) :: Workbook.t()
def add_defined_name(workbook, name, definition) do
update_in(workbook.defined_names, &Map.put(&1, name, definition))
end
end
21 changes: 21 additions & 0 deletions lib/elixlsx/xml_templates.ex
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,24 @@ defmodule Elixlsx.XMLTemplates do
|> Enum.map_join(&make_xl_workbook_xml_sheet_entry/1)
end

defp workbook_defined_names(%{}) do
""
end

defp workbook_defined_names(defined_names) do
"""
<definedNames>
#{Enum.map_join(defined_names, &make_defined_name/1)}
</definedNames>
"""
end

defp make_defined_name({name, definition}) do
"""
<definedName name="#{xml_escape(name)}">#{xml_escape(definition)}</definedName>
"""
end

@doc ~S"""
Return the data for /xl/workbook.xml
"""
Expand All @@ -791,6 +809,9 @@ defmodule Elixlsx.XMLTemplates do
workbook_sheet_entries(data.sheets, sci) <>
~S"""
</sheets>
""" <>
workbook_defined_names(data.defined_names) <>
"""
<calcPr fullCalcOnLoad="1" iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/>
</workbook>
"""
Expand Down
Loading