Tuesday, April 29, 2014

Bash Script to Convert CSV or TSV to OpenOffice or Excel format file for viewing or emailing

Dependencies:
csvtool (http://forge.ocamlcore.org/projects/csv/)
Libreoffice (https://www.libreoffice.org/)
Unoconv (http://dag.wieers.com/home-made/unoconv/)

Because of work with Data so much, sometimes I need to review table data but the format can be tedious to sort through if the columns aren't fixed width or otherwise aligned.

I created the following script, and dropped it in my bin directory.

Then I modified KDE to have a global shortcut for launch.

Create a link to your shell script by making your own directiry, and pointing it to your new script.



Next, add a global shortcut so it launches automatically.




Note, your can modify your end format by looking at what unoconv offers by executing the command
`unoconv --show`

Source code for script is below.


Cheers!

./Steven



 1 #!/bin/bash
 2 
 3 end_format="xls" #you can get these formats by using the command `unoconv --show`
 4 
 5 pastefile=$(mktemp /tmp/vim.XXXX)
 6 csvfile=${pastefile}.csv
 7 xlsfile=${pastefile}.xls
 8 
 9 function getclip {
10       qdbus org.kde.klipper /klipper org.kde.klipper.klipper.getClipboardContents > ${pastefile}
11 }
12 
13 ##if I'm a file copy it else from clipboard
14 if ! test -z $1; then
15    if test -f $1; then
16       echo File $1 Found
17       cat $1 > ${pastefile}
18    else
19       getclip
20    fi
21 else
22    getclip
23 fi
24 
25 function width {
26    delim=$1
27    width=$(/usr/bin/csvtool -t ${delim} width ${pastefile} 2> /dev/null)
28    if [[ ${width} -gt 1 ]]; then 
29       return 0
30    else 
31       return 1
32    fi
33 }
34 
35 if  width TAB; then
36    sep="TAB"
37    /usr/bin/csvtool -t ${sep} -u COMMA cat ${pastefile} > ${csvfile}
38 elif width COMMA ; then 
39    sep="COMMA"
40    cp ${pastefile} ${csvfile}
41 fi
42 
43 if [ -z ${sep} ]; then
44    rm -f ${pastefile} 
45    echo no separation found  >> ${pastefile}
46    /usr/bin/vim ${pastefile} 
47    rm -f ${pastefile} 
48    exit
49 fi
50 
51 
52 if ! /usr/bin/unoconv -f ${end_format} -o ${xlsfile} ${csvfile} ; then
53    echo "Bad conversion, opening CSV"
54    vim ${csvfile}
55    rm -f ${pastefile} ${csvfile} 
56    exit
57 fi
58 
59 /usr/bin/libreoffice ${xlsfile}
60 rm -f ${pastefile} ${csvfile} ${xlsfile}


You can select, copy and paste the code below



No comments:

Post a Comment