如何读取 ods 文档(例如 LibreOffice calc)并将其转换为 Julia 数据框?

Ant*_*llo 0 data-import dataframe julia ods

如何从 Julia DataFrame 中的 ODS 电子表格(由 OpenOffice、LibreOffice 等使用)导入数据?

(这是社区维基问答)

Ant*_*llo 5

如果机器上安装了 python,则 Julia 可以使用PyCall非常直接地使用ezodf模块:

using PyCall
using DataFrames

@pyimport ezodf
doc = ezodf.opendoc("test.ods")
nsheets = length(doc[:sheets])
println("Spreadsheet contains $nsheets sheet(s).")
for sheet in doc[:sheets]
    println("---------")
    println("   Sheet name : $(sheet[:name])")
    println("Size of Sheet : (rows=$(sheet[:nrows]()), cols=$(sheet[:ncols]()))")
end

# convert the first sheet to a dictionary
sheet = doc[:sheets][1]
df_dict = Dict()
col_index = Dict()
for (i, row) in enumerate(sheet[:rows]())
  # row is a list of cells
  # assume the header is on the first row
  if i == 1
      # columns as lists in a dictionary
      [df_dict[cell[:value]] = [] for cell in row]
      # create index for the column headers
      [col_index[j]=cell[:value]  for (j, cell) in enumerate(row)]
      continue
  end
  for (j, cell) in enumerate(row)
      # use header instead of column index
      append!(df_dict[col_index[j]],cell[:value])
  end
end  

# and convert the dictionary to a DataFrame
df = DataFrame(df_dict)
Run Code Online (Sandbox Code Playgroud)

(这只是在这个答案上用 Julia 重写 davidovitch 的 python 代码)

编辑:

我现在根据这段代码编写了一个 Julia 包:OdsIO

它提供了多种从 ods 文件(包括单元格范围)导入数据的功能,希望很快它也将允许导出。

编辑2:

自 v0.1.0 版本起现在支持导出到 Ods