Hi there
I have read a csv file into Julia, as a dataframe, with some columns of type string, some of type integer, and others of type float. I would like to save, or export or write this dataframe as an html file. What is the simplest procedure?
PrettyTables has an HTML backend
I will have a look at this package. Thank you.
I have this MWE.
using DataFrames
df = DataFrame(Name=["Andrew", "Barbara"],Id=[1,2],Exam_1=[3.5,7.0])
using PrettyTables
pt = pretty_table(df; backend = Val(:html), alignment=:c)
When run in a notebook, this gives me a really prettily formatted html output in a new cell, whereas when run in a plain Julia prompt it gives what I assume is the corresponding code for the html file. My problem now is how to save this pt object to an html file, preserving all the beautiful formatting. I have tried:
save("output.html", pt)
but it prints the error:
Error encountered while save FileIO.File{FileIO.DataFormat{:HTML}, String}("output.html").
Fatal error:
ERROR: ArgumentError: Argument does not support conversion to HTML.
...
How do I concretely export or save the a PrettyTable pt object formatted from the html back-end?
There is an optional first argument to the pretty_table
function which is the io::IO
(input/output) argument. (See the first couple paragraphs of the pretty_table documentation.)
The following is untested but should work:
open("output.html", "w") do io
pretty_table(io, df; backend = Val(:html), alignment=:c)
end
The open function with a do
block is the safe way to open and close I/O streams in Julia. (It will close the stream even if the write fails with an error.)
Thanks Nils and Nathan. Nathanβs chunk of code did work. Thanks again!
The same in plain DataFrames.jl:
julia> using DataFrames
julia> df = DataFrame(x=1:2, y=["a", "b"],z = [1.5, 2.5])
2Γ3 DataFrame
Row β x y z
β Int64 String Float64
ββββββΌββββββββββββββββββββββββ
1 β 1 a 1.5
2 β 2 b 2.5
julia> open("output.html", "w") do io
show(io, MIME("text/html"), df)
end