6

I would like to import a CSV into Org-mode. Others have already asked about importing CSV to Org-mode tables. That's not what I am trying to do. I need to import CSV to Org-mode properties.

For example, a CSV like this:

Name,Tel,Mobile,Fax
John,11111,22222,33333

should become:

:PROPERTIES:
:Name: John
:Tel: 11111
:Mobile: 22222
:Fax: 33333
:END:

Do you happen to know a painless way to do it?

lecodesportif
  • 10,737
  • 9
  • 38
  • 58

3 Answers3

4

The easiest approach I can see is to mark the data rows as the region, and then use a regexp search and replace:

M-x replace-regexp RET \(.*\),\(.*\),\(.*\),\(.*\) RET :PROPERTIES: C-q C-j :Name: \1 C-q C-j :Tel: \2 C-q C-j :Mobile: \3 C-q C-j :Fax: \4 C-q C-j :END: RET

If you needed to do this for many variable CSV files with different headers and numbers of columns, then I would probably approach it with keyboard macros.

user310031's answer would make a good basis for that. The macro could narrow the buffer to each row, insert the header row above it, perform the csv-transpose (which appears to require CSV mode) do the search+replace, add in the :PROPERTIES: and :END: lines, widen the buffer again, and leave point on the line before the next data row. Then just mark the remaining data rows as the region, and type C-x C-k r.

Community
  • 1
  • 1
phils
  • 71,335
  • 11
  • 153
  • 198
3

use csv-mode, transpose rows and columns by csv-transpose and format with replace-regexp:

search \(.*\),\(.*\)

replace for: :\1: \2

user310031
  • 61
  • 2
1

You can do something like this. Your example is not too clear. If there is more than one line, it will just set the properties in the same header over and over. you may want to use the Name to create a new heading, and then set properties on the heading. the code below works for pretty well formatted csv files.

(let ((lines (with-temp-buffer
               (insert-file-contents "data.csv")
               (split-string (buffer-string) "\n")))
      (properties)
      (values))

  (setq properties (split-string (car lines) ","))

  (loop for line in (cdr lines)
        do
        (setq values (split-string line ","))
        (loop for property in properties
              for value in values
              do
              (org-entry-put (point) property value))))
phils
  • 71,335
  • 11
  • 153
  • 198
John Kitchin
  • 2,236
  • 1
  • 17
  • 25