【问题标题】:Reading specific columns from excel and parsing the data从 excel 中读取特定列并解析数据
【发布时间】:2013-01-02 03:03:36
【问题描述】:

由于记录是不可变的,我无法读取数据并对其进行解析,除非它自己创建一个新实例。此外,我如何能够从许多特定列中读取我的 excel 文件,而不是从第 0 列读取到 EOF。无论如何我可以从第 1 列、第 3 列、第 5 列中读取数据。假设第 1 列将被解析为字符串,第 3 列将解析为整数,第 5 列将解析为长整数。

(defrecord Record [Name Age Index])

(defn read-csv [fname count]
  (with-open [file (io/reader fname)]
    (doall (take count (map (comp first csv/read-csv)
                            (line-seq file))))))
(def records (map #(apply ->Record %) (read-csv "C:/Users/user/Documents/URECA/hi/lib/test.csv" 1)))

这是我所拥有的,但它似乎是逐步阅读列

【问题讨论】:

  • 也许at this site 描述的方法可能会有所帮助?

标签: excel clojure


【解决方案1】:

要保留文本字段的引号,您可以通过正则表达式解析 csv 文件:

(defn read-csv [fname count]
  (with-open [file (io/reader fname)]
    (doall (map #(str/split % #",") ; doesn't work with commas in text fields
                (take count (line-seq file))))))

(defn make-record [idxs types row]
  (apply ->Record
         (map (fn [idx t]
                (let [value (nth row idx)]
                  (case t
                    :string value
                    :int (Integer/parseInt value)
                    :long (Long/parseLong value))))
              idxs types)))

(def records (map (partial make-record
                           [0 2 4]
                           [:string :int :long])
                  (read-csv "/home/mobyte/test.csv" 3)))

(pprint records)
-> ({:Name "\"s1\"", :Age 1, :Index 111}
    {:Name "\"s2\"", :Age 2, :Index 112}
    {:Name "\"s3\"", :Age 3, :Index 113})

(type (:Age (first records)))
->java.lang.Integer

(type (:Index (first records)))
-> java.lang.Long

(type (:Name (first records)))
-> java.lang.String     

【讨论】:

  • 您能否解释一下记录部分,因为我不太清楚它是关于什么的。就 fn [row] 而言,也许更多的 cmets 会受到赞赏,因为我似乎看不到行部分的任何输入。我想它会被认为是一个嵌套函数
  • 我已经更新了帖子。现在嵌套部分在单独的函数make-record中。
猜你喜欢
  • 2019-05-15
  • 2020-07-13
  • 1970-01-01
  • 2019-11-23
  • 2014-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多