Skip to content

Commit

Permalink
Set column width from the first row when headers are not given
Browse files Browse the repository at this point in the history
  • Loading branch information
sax committed Jan 20, 2024
1 parent 2bdfe9a commit d9fb0cf
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/exceed/worksheet.ex
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ defmodule Exceed.Worksheet do
})
]),
Xs.empty_element("sheetFormatPr", %{"baseColWidth" => "8", "defaultRowHeight" => "18"}),
cols(headers, opts),
cols(headers, content, opts),
Xs.element("sheetData", sheet_data(content, headers)),
Xs.empty_element("sheetCalcPr", %{"fullCalcOnLoad" => "1"}),
Xs.empty_element("printOptions", %{
Expand All @@ -89,15 +89,19 @@ defmodule Exceed.Worksheet do

# # #

defp cols(nil, _), do: []
defp cols(nil, content, opts) do
case content |> Stream.take(1) |> Enum.to_list() do
[headers] -> cols(headers, content, opts)
end
end

defp cols(headers, opts) do
defp cols(headers, _content, opts) do
padding = Keyword.get(opts, :col_padding, 4.25)

Xs.element(
"cols",
for {header, i} <- Enum.with_index(headers, 1) do
width = String.length(header) + padding
width = String.length(to_string(header)) + padding
Xs.empty_element("col", %{"min" => i, "max" => i, "width" => width})
end
)
Expand Down
10 changes: 10 additions & 0 deletions test/exceed/worksheet_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,16 @@ defmodule Exceed.WorksheetTest do
assert String.length(header3) == 6
assert Xq.attr(col3, "width") == "8.34"
end

test "uses the first row of the stream to set column width when headers are not given", %{stream: stream} do
ws = Worksheet.new("sheet", nil, Enum.take(stream, 2))
xml = Worksheet.to_xml(ws) |> stream_to_xml()

assert [col1, col2, col3] = Xq.all(xml, "/worksheet/cols/col")
assert Xq.attr(col1, "width") == "16.25"
assert Xq.attr(col2, "width") == "5.25"
assert Xq.attr(col3, "width") == "7.25"
end
end

# # #
Expand Down

0 comments on commit d9fb0cf

Please sign in to comment.