Emacs: import a CSV into org-mode

Solution 1:

From the org-mode manual:

C-c | Convert the active region to table. If every line contains at least one TAB character, the function assumes that the material is tab separated. If every line contains a comma, comma-separated values (CSV) are assumed. If not, lines are split at whitespace into fields. You can use a prefix argument to force a specific separator: C-u forces CSV, C-u C-u forces TAB, and a numeric argument N indicates that at least N consecutive spaces, or alternatively a TAB will be the separator. If there is no active region, this command creates an empty Org table.

So just paste the data into an org file, select it, and do C-u C-c | .

Solution 2:

I'm assuming you want to convert your CSV specifically into org-mode tables. If that's not the case, you may want to be more explicit about output format in your question.

Something like this should do it, or at least get you a starting point you can hack on:

  #!/usr/bin/perl

  use strict;
  use warnings;

  use Text::CSV;

  my $csv = Text::CSV->new();

  while ( my $line = <DATA> ) {
    if ( $csv->parse( $line )) {
      my $str = join '|' , $csv->fields();
      print "|$str|\n";
    }
  }


  __DATA__
  1,2,3,4
  1,2,"3,4"

Solution 3:

Have a look at:

C-h f org-table-convert-region

I'm always converting csv so I added this to my .emacs.

(defun org-convert-csv-table (beg end)
  (interactive (list (mark) (point)))
  (org-table-convert-region beg end ",")
  )

(add-hook 'org-mode-hook
      (lambda ()
    (define-key org-mode-map (kbd "<f6>") 'org-convert-csv-table)))

update

Here is another function that considers the quoted commas as well :

 a,"12,12",b --> a | 12,12 |b

feel free to improve it :-).

(defun org-convert-csv-table (beg end)
  ; convert csv to org-table considering "12,12"
  (interactive (list (point) (mark)))
  (replace-regexp "\\(^\\)\\|\\(\".*?\"\\)\\|," (quote (replace-eval-replacement
                            replace-quote (cond ((equal "^" (match-string 1)) "|")
                                                   ((equal "," (match-string 0)) "|")
                                                   ((match-string 2))) ))  nil  beg end)