1------------------------------------------------------------------------------
2--  File:            CSV2XLS.adb
3--  Description:     Converts a CSV (text with Comma Separated Values) input
4--                   into Excel file. You can specify the separator.
5--                   E.g. If you open in Excel a CSV with semicolons as
6--                   separators on a PC with comma being the separator,
7--                   and then apply "Text to columns", the eventual commas in
8--                   the text will already have been used as separators and
9--                   you will end up with a total mess. CSV2XLS prevents this
10--                   issue.
11--  Syntax:          csv2xls {option} <data.csv
12--       or          csv2xls {option} data.csv
13--                   Options:
14--                     -c : comma is the separator
15--                     -s : semicolon is the separator
16--                     -t : tab is the separator
17--                     -f : freeze top row (header line)
18--  Date / Version:  14-May-2014; 29-Apr-2014
19--  Author:          Gautier de Montmollin
20------------------------------------------------------------------------------
21
22with CSV;
23with Excel_Out;
24with Ada.Command_Line, Ada.Directories, Ada.Text_IO, Ada.Strings.Fixed;
25
26procedure CSV2XLS is
27  use Ada.Command_Line, Ada.Directories, Ada.Text_IO, Ada.Strings, Excel_Out;
28  input: File_Type;
29  xl: Excel_Out_File;
30  first: Boolean:= True;
31  separator: Character := ',';
32  -- ';', ',' or ASCII.HT
33begin
34  if Argument_Count = 0 then
35    Create(xl, "From_CSV.xls");
36  else
37    declare
38      name: constant String:= Argument(Argument_Count);
39      ext: constant String:= Extension(name);
40    begin
41      Open(input, In_File, name);
42      Set_Input(input);
43      Create(xl, name(name'First..name'Last-ext'Length) & "xls");
44    end;
45  end if;
46  for i in 1..Argument_Count loop
47    if Argument(i)'Length = 2 and then Argument(i)(1)='-' then
48      case Argument(i)(2) is
49        when 'c' =>
50          separator:= ',';
51        when 's' =>
52          separator:= ';';
53        when 't' =>
54          separator:= ASCII.HT;
55        when 'f' =>
56          Freeze_Top_Row(xl);
57        when others =>
58          null;
59      end case;
60    end if;
61  end loop;
62  while not End_Of_File loop
63    declare
64      line: constant String:= Get_Line;
65      bds: constant CSV.Fields_Bounds:= CSV.Get_Bounds( line, separator );
66    begin
67      if first then
68        first:= False;
69      end if;
70      for i in bds'Range loop
71        Put(xl,
72          Ada.Strings.Fixed.Trim(
73            CSV.Unquote(CSV.Extract(line, bds, i)), Both
74          )
75        );
76      end loop;
77    end;
78    New_Line(xl);
79  end loop;
80  Close(xl);
81  if Is_Open(input) then
82    Close(input);
83  end if;
84end CSV2XLS;
85