Guest User

Untitled

a guest
Jan 2nd, 2018
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 55.05 KB | None | 0 0
  1. #!/bin/bash
  2. #===============================================================================
  3. #
  4. #          FILE:  xlsx2csv.sh
  5. #
  6. #         USAGE:  ./xlsx2csv.sh [-c|--copyleft] [-d|--debug] [-v|--version] -x[|--xlsx] filename
  7. #
  8. #   DESCRIPTION:  Read an MS excel SpreadsheetML document
  9. #                   extract the data to csv
  10. #
  11. #  REQUIREMENTS:  unzip | xsltproc | libxml | sqlite3 | gnu sed | mktemp
  12. #          BUGS:  doesn't read formatting, macros
  13. #         NOTES:  does translate dates correctly! also handles null data
  14. #                 quotes and commas delimited, embedded quotes are doubled
  15. #        AUTHOR:  Kirk Roybal (DBA)
  16. #                 http://kirk.webfinish.com
  17. #       CREATED:  12/02/2009 10:06:45 CST
  18. #      REVISION:  ---
  19. #       CREDITS:
  20. #     openxmldeveloper.org for describing the format of excel date serial
  21. #     http://openxmldeveloper.org/articles/using_Spreadsheet_ML_document__as_datasource_for_heterogenous_applicationss.aspx
  22. #     http://www.ccechile.org/eventos/2007/docs/document/Response-various_Dates.pdf
  23. #     http://www.codeproject.com/KB/XML/ooxml_is_defective.aspx
  24. #     http://openxmldeveloper.org/forums/thread/597.aspx
  25. #     Hugo Mildenberger for a patch submitted on 08/31/2010
  26. #
  27. #    This program is free software: you can redistribute it and/or modify
  28. #    it under the terms of the GNU General Public License as published by
  29. #    the Free Software Foundation, either version 3 of the License, or
  30. #    (at your option) any later version.
  31. #
  32. #    This program is distributed in the hope that it will be useful,
  33. #    but WITHOUT ANY WARRANTY; without even the implied warranty of
  34. #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  35. #    GNU General Public License for more details.
  36. #
  37. #    You should have received a copy of the GNU General Public License
  38. #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  39. #
  40. #     Release notes:
  41. #         1.0 (2009/12/18) -- First release available to the public
  42. #         1.1 (2010/01/12) -- Improved date handling routine to look for all common date formats in Excel.
  43. #         1.2 (2010/08/31) -- Now uses /tmp, supports whitespace in filename, has a --help switch
  44. #===============================================================================
  45. version="1.2"
  46. tmpdir="/tmp"
  47. overwrite="No"
  48.  
  49. function usage () {
  50.   cat <<EOS
  51.   Usage:  $(basename $0) [-h|--help] [-c|--copyleft] [-d|--debug] [-v|--version] [-o|--overwrite]
  52.                          [-t|--tmpdir] tempdir -x[|--xlsx] filename
  53.           -h, --help             display this text
  54.           -c, --copyleft         display copyright
  55.           -d, --debug            show command output
  56.           -o, --overwrite        overwrite already existing output files
  57.           -v, --version          output version of this script
  58.           -t, --tmpdir dirname   specify where temporary files should be created (currently in "${tmpdir}")
  59.           -x, --xlsx filename    name of input file
  60.  
  61. For those of us converting huge spreadsheets (or a lot of them):
  62. Create a ramdisk on OSX with the following code:
  63. NUMSECTORS=262144
  64. # 64mb = 131072 , 128mb = 262144 , 256mb = 524288 , 512mb = 1048576 , 1gb = 2097152
  65. mydev=\$(hdid -nomount ram://\$NUMSECTORS)
  66. newfs_hfs \$mydev
  67. [[ -d ~/sdb ]] || mkdir ~/sdb
  68. mount -t hfs \$mydev ~/sdb
  69.  
  70. Then, use this mounted ramdisk for your temporary storage for $0.
  71. $0 -t ~/sdb -x filename
  72. On ubuntu, just use /dev/shm
  73. $0 -t /dev/shm -x filename
  74.  
  75. Thanks to Hugo Mildeberger for cleaning up the temp dir code to make this work.
  76. EOS
  77.  
  78. }
  79.  
  80. [[ $# -gt 0 ]] || {
  81.   usage
  82.   exit 1
  83. }
  84.  
  85. for arg
  86. do
  87.   delim=""
  88.   case "$arg" in
  89.     #translate --gnu-long-options to -g (short options)
  90.     --copyleft) args="${args}-c ";;
  91.     --xlsx) args="${args}-x ";;
  92.     --debug) args="${args}-d ";;
  93.     --version) args="${args}-v ";;
  94.     --overwrite) args="${args}-o ";;
  95.     --tmpdir) args="${args}-t ";;
  96.     --help) args="${args}-h ";;
  97.     #pass through anything else
  98.     *) leftchar=$(printf %1.1s "$arg")
  99.       [[ ! "$leftchar" == "-" ]] && delim="\""
  100.       args="${args}${delim}${arg}${delim} "
  101.       ;;
  102.   esac
  103. done
  104.  
  105.  
  106. #Reset the positional parameters to the short options
  107. eval set -- $args
  108.  
  109. while getopts ":cdhot:vx:" option 2>/dev/null
  110. do
  111.   case ${option} in
  112.     c) tail -n 650 "$0" | head -n 621 | sed 's/^# //'  #copyleft
  113.        exit ;;
  114.     d) set -x #debug
  115.        debug=true;;
  116.     h) usage; exit 1;;
  117.     o) overwrite="Yes";;
  118.     t) tmpdir="${OPTARG}";; #temporary directory
  119.     v) echo $version; exit;; #version
  120.     x) filename="${OPTARG}";; #xlsx
  121.     *) echo "'"$OPTARG"'" is an unrecognized option;;
  122.   esac
  123. done
  124.  
  125. echo "$0: using tmpdir ${tmpdir}" >&2
  126.  
  127. [[ -d "${tmpdir}"  ]] || {
  128.   cat <<EOS
  129.   the directory ${tmpdir} does not exist. Use, e.g.,  --tempdir '.' to use current directory
  130. EOS
  131.   exit 2
  132. }
  133. [[ -z "$filename" ]] && {
  134.   usage
  135.   cat <<EOS
  136.   Filename is required.
  137. EOS
  138.   exit 2
  139. }
  140.  
  141. [[ -f "$filename" ]] || {
  142.   cat <<EOS
  143.   File not found.
  144. EOS
  145.   exit 2
  146.  
  147. }
  148.  
  149. #find out what inode we're in
  150. appdir=$(dirname $0)
  151. [[ "$appdir" == "." ]] && appdir=$(pwd)
  152. curdir=$(pwd)
  153. appname=$(basename $0)
  154.  
  155. #set up some platform specific utilities
  156. gnused=$(which sed)
  157. platform=$(uname -s)
  158. [[ "${platform}" == "Darwin" ]] && gnused=/opt/local/bin/gsed
  159. [[ -f "$gnused" ]] || {
  160.   echo "Can't find a copy of GNU sed"
  161.   exit
  162. }
  163.  
  164. #Make a working directory based on the filename
  165. filtered=$(echo "$filename" | sed -e 's/\.xlsx$//g' -e 's/[[:space:]]/_/g')
  166. dirname=$(mktemp -d "${tmpdir}/$filtered.XXXXXXXXXXXXXX.tmp")
  167. #copy the source file into it
  168. cp "$filename" "$dirname"
  169. #get in there and push
  170. pushd "$dirname" > /dev/null
  171.  
  172. workfilename="$(basename "$filename")"
  173. # Unpack the xlsx file
  174. unzip -q "$workfilename"
  175. #Did we get the expected structure?
  176. [[ ! -d "xl" ]] && {
  177.   echo $filename is not an xlsx format file
  178.   popd
  179.   rm -rf "$dirname"
  180.   exit 1
  181. }
  182.  
  183. #Make a sqlite3 database to do some relational work
  184. sdbname="$(pwd)/${filtered}.sdb"
  185. [[ $(hostname) == "wsmkroybal.javelin.pvt" ]] && {
  186.     sdbname="/Users/kroybal/sdb/${filtered}.sdb"
  187.     [[ -f "$sdbname" ]] && rm "${filtered}"
  188. }
  189.  
  190. #Create an SQL based string table
  191. sql="CREATE TABLE shared_strings (
  192.  id INTEGER PRIMARY KEY AUTOINCREMENT,
  193.  value string);"
  194. sqlite3 "$sdbname" "$sql"  #The first access of the db will create the file
  195.  
  196. #turn the starting tags directly into newline
  197. newline=$(echo -e '\n\r')
  198.  
  199. #turn the xml for shared strings into sqlite sql
  200. cat "xl/sharedStrings.xml" |
  201.   sed -e "s/<rPr>.*<\/rPr>//g" >  "xl/sharedStrings.sed"
  202. #blow away embedded garbage
  203. $gnused -i -e "s/<r><t>.<\/t><\/r>//g" -e "s/<si>/\\$newline/g" "xl/sharedStrings.sed"
  204. $gnused -i -e "s/<\/t>.$//g" -e "s/<t>//g"  -e "/^[:space:]]*$/d" "xl/sharedStrings.sed"
  205. $gnused -i -e "s/<t xml:space=\"preserve\">//g" -e 's/<r>//g' "xl/sharedStrings.sed"
  206. #remove any non-printable characters, the xml tag line, and the DTD
  207. $gnused -i -e "s/[^[:graph:] ]*//g" -e "1,2d" -e "s/'/''/g" -e 's/amp;//g' "xl/sharedStrings.sed"
  208. #blow off any formatting junk after the closing tag
  209. $gnused -i -e "s/<\/t>.*$//" -e "/^$/d" "xl/sharedStrings.sed"
  210. #trim the result
  211. #sed -i '' -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' "xl/sharedStrings.sed"
  212. #make a sql statement out of the result
  213. $gnused -i -e "s/^/INSERT INTO shared_strings (value) VALUES ('/" -e "s/$/');/" "xl/sharedStrings.sed"
  214. #load the stringtable
  215. sqlite3 "$sdbname" < "xl/sharedStrings.sed"
  216.  
  217. sql="CREATE INDEX idx_ss ON shared_strings(id,value);"
  218. sqlite3 "$sdbname" "$sql"
  219.  
  220. sql="CREATE TABLE sheets (
  221. id INTEGER PRIMARY KEY,
  222. name varchar(200),
  223. ordinal integer,
  224. rid integer);"
  225. sqlite3 "$sdbname" "$sql"
  226.  
  227. #make an xslt file to import the sheet names
  228. xsl="<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">
  229. <xsl:output method=\"text\"/>
  230. <xsl:template match=\"sheets\">
  231.  <xsl:apply-templates select=\"sheet\"/>
  232. </xsl:template>
  233. <xsl:template match=\"sheet\">
  234.    INSERT INTO sheets(name,ordinal,rid) VALUES ('<xsl:value-of select=\"translate(@name,&quot;'&quot;,&quot;&quot;)\"/>',<xsl:value-of select=\"@sheetId\"/>,<xsl:value-of select=\"@rid\"/>);
  235. </xsl:template>
  236. </xsl:stylesheet>"
  237. echo -e "$xsl" > "xl/sheets.xsl"
  238.  
  239. #make a simpler xml file to parse
  240. cat "xl/workbook.xml" |
  241.   sed -e 's/.*<sheets/<sheets/' -e 's/r:id/rid/g' |
  242.   sed -e 's/<\/sheets>.*/<\/sheets>/' -e 's/"rId/"/g' > "xl/sheets.xml"
  243. #import the sheet names
  244. xsltproc "xl/sheets.xsl" "xl/sheets.xml" | sqlite3 "$sdbname"
  245.  
  246. #import the format styles
  247. sql="CREATE TABLE fmt_data (
  248. id INTEGER PRIMARY KEY,
  249. numfmtid integer,
  250. formatcode varchar(200));"
  251. sqlite3 "$sdbname" "$sql"
  252.  
  253. #import the format data
  254. fmtxsl="<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">
  255. <xsl:output method=\"text\"/>
  256. <xsl:template match=\"numFmts\">
  257.  <xsl:apply-templates select=\"numFmt\"/>
  258. </xsl:template>
  259. <xsl:template match=\"numFmt\">
  260.    INSERT INTO fmt_data(numfmtid,formatcode) VALUES ('<xsl:value-of select=\"@numFmtId\"/>','<xsl:value-of select=\"@formatCode\"/>');
  261. </xsl:template>
  262. </xsl:stylesheet>"
  263.  
  264. #create an xsl stylesheet for formats
  265. echo -e "$fmtxsl" > 'xl/fmt.xsl'
  266.  
  267. #simplify the input file
  268. cat "xl/styles.xml" | sed -e 's/^.*<numFmts/<numFmts/' -e 's/<\/numFmts>.*/<\/numFmts>/' > "xl/fmts.xml"
  269. #import the formats
  270. xsltproc "xl/fmt.xsl" "xl/fmts.xml"  | sqlite3 "$sdbname"
  271.  
  272. #associate the formats to cells
  273. sql="CREATE TABLE fmt2cell_data (
  274. id INTEGER PRIMARY KEY,
  275. numfmtid integer);"
  276. sqlite3 "$sdbname" "$sql"
  277.  
  278. #now import the format 2 field mapping table
  279. fmtxsl="<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">
  280. <xsl:output method=\"text\"/>
  281. <xsl:template match=\"cellXfs\">
  282.  <xsl:apply-templates select=\"xf\"/>
  283. </xsl:template>
  284. <xsl:template match=\"xf\">
  285.    INSERT INTO fmt2cell_data(numfmtid) VALUES ('<xsl:value-of select=\"@numFmtId\"/>');
  286. </xsl:template>
  287. </xsl:stylesheet>"
  288.  
  289. #create an xsl stylesheet for formats
  290. echo -e "$fmtxsl" > 'xl/fmt2cell.xsl'
  291.  
  292. #simplify the input file
  293. cat "xl/styles.xml" | sed -e 's/^.*<cellXfs/<cellXfs/' |
  294.     sed -e 's/<\/cellXfs>.*/<\/cellXfs>/' > "xl/fmt2cell.xml"
  295. #import the mapping
  296. xsltproc "xl/fmt2cell.xsl" "xl/fmt2cell.xml"  | sqlite3 "$sdbname"
  297.  
  298. #delete the formats that obviously have nothing to do with dates.
  299. sql="DELETE FROM fmt2cell_data WHERE numfmtid=0;"
  300. sqlite3 "$sdbname" "$sql"
  301.  
  302. #create a table of known date formats
  303. sql="CREATE TABLE date_formats (
  304. id INTEGER PRIMARY KEY,
  305. format varchar(500));"
  306. sqlite3 "$sdbname" "$sql"
  307.  
  308. #Insert all the date formats we know about
  309. insert="INSERT INTO \"date_formats\" (format) VALUES"
  310. sql="
  311. $insert ('[\$-F800]dddd\,\ mmmm\ dd\,\ yyyy');
  312. $insert ('m/d;@');
  313. $insert ('mmm\ d');
  314. $insert ('m/d/yy;@');
  315. $insert ('mm/dd/yy;@');
  316. $insert ('m/d/yyyy;@');
  317. $insert ('m/d/yy\ h:mm;@');
  318. $insert ('[\$-409]mmmmm;@');
  319. $insert ('[\$-409]d\-mmm;@');
  320. $insert ('[\$-409]mmm\-yy;@');
  321. $insert ('[\$-409]mmmm\-yy;@');
  322. $insert ('[\$-409]mmmmm\-yy;@');
  323. $insert ('[\$-409]d\-mmm\-yy;@');
  324. $insert ('[\$-409]d\-mmm\-yyyy;@');
  325. $insert ('[\$-409]mmmm\ d\,\ yyyy;@');
  326. $insert ('[\$-409]m/d/yy\ h:mm\ AM/PM;@');
  327. --$insert ('_(* #,##0_);_(* \(#,##0\);_(* \"-\"_);_(@_)');
  328. --$insert ('_(* #,##0_);_(* \(#,##0\);_(* \"-\"??_);_(@_)');
  329. --$insert ('_(* #,##0.0_);_(* \(#,##0.0\);_(* \"-\"?_);_(@_)');
  330. --$insert ('_(* #,##0.0_);_(* \(#,##0.0\);_(* \"-\"??_);_(@_)');
  331. --$insert ('_(* #,##0.00_);_(* \(#,##0.00\);_(* \"-\"??_);_(@_)');
  332. --$insert ('_(* #,##0.0000_);_(* \(#,##0.0000\);_(* \"-\"??_);_(@_)');
  333. --$insert ('_(\"$\"* #,##0.00_);_(\"$\"* \(#,##0.00\);_(\"$\"* \"-\"??_);_(@_)');
  334. --$insert ('_(\"$\"* #,##0.000_);_(\"$\"* \(#,##0.000\);_(\"$\"* \"-\"??_);_(@_)');
  335. "
  336. sqlite3 "$sdbname" "$sql"
  337.  
  338. #see if anything matches the dates we know about
  339. sql="UPDATE fmt_data SET formatcode = 'date' where formatcode IN
  340.  (SELECT format FROM date_formats);"
  341. sqlite3 "$sdbname" "$sql"
  342.  
  343. #propagate the formats from the fmt_data table
  344. # to the fmt2cell_data table
  345. sql="REPLACE INTO fmt2cell_data (id,numfmtid)
  346.      select fc.id, fd.formatcode
  347.      FROM fmt2cell_data fc INNER JOIN fmt_data fd
  348.      ON fc.numfmtid = fd.numfmtid
  349.      WHERE fd.formatcode='date';"
  350. sqlite3 "$sdbname" "$sql"
  351.  
  352. sql="CREATE TABLE cell_data (
  353.  id INTEGER PRIMARY KEY AUTOINCREMENT,
  354.  sheet varchar(255),
  355.  cell varchar(200),
  356.  style integer,
  357.  type varchar(3),
  358.  value varchar(200),
  359.  row integer,
  360.  col varchar(20)
  361. );"
  362. # Leftovers from date calculation improvements
  363. #  a integer,
  364. #  b integer,
  365. #  c integer,
  366. #  d integer,
  367. #  e integer,
  368. #  f integer,
  369. #  g integer,
  370. #  y integer,
  371. #  m integer,
  372. #  day integer
  373. sqlite3 "$sdbname" "$sql"
  374.  
  375. #extract the data for each sheet to sqlite
  376. cd xl/worksheets/
  377.  
  378. #xsltproc requires the style sheet as a file
  379. tail -n 27 "$appdir/$appname" > data.xsl
  380.  
  381. for file in *.xml
  382. do
  383.   #Remove the formatting we can't read anyway to make the xslt parser simpler.
  384.   # remove any trailing lines after the sheetData
  385.   cat "$file" | sed -e 's/.*<sheetData/<sheetData/' |
  386.     sed -e 's/<\/sheetData>.*/<\/sheetData>/' -e '3,$d' > "${file}.data"
  387.  
  388.   #translate the data into sqlite INSERT statements
  389.   # 3 copies of sed streaming are an intentional speed enhancement.
  390.   xsltproc data.xsl "${file}.data" |
  391.       sed -e "s/'/''/g" -e "s/|/'/g" | sed -e 's/&amp;/&/g' |
  392.       sed -e "/'');[[:space:]]*$/d" | sqlite3 "$sdbname"
  393. # > "${file}.sql"
  394. # < "${file}.sql"
  395.  
  396.   #Add the sheet name to the data we just imported
  397.   bname=$(basename "$file" .xml |  sed -e "s/'//g" -e 's/[[:alpha:]]*//g')
  398.   sql="UPDATE cell_data SET sheet=(SELECT name FROM sheets WHERE rid = ${bname})
  399.       WHERE sheet is null;"
  400.   sqlite3 "$sdbname" "$sql"
  401. done
  402.  
  403. #remove any blank cells
  404. sql="DELETE FROM cell_data WHERE value = '';"
  405. sqlite3 "$sdbname" "$sql"
  406.  
  407. #index the type column
  408. sql="CREATE INDEX idx_cd ON cell_data(type);"
  409. sqlite3 "$sdbname" "$sql"
  410.  
  411. #shared string table is zero based in file, 1 based in sdb
  412. sql="UPDATE cell_data SET value=value+1 WHERE type='s';"
  413. sqlite3 "$sdbname" "$sql"
  414.  
  415. #update the cells with the string data
  416. sql="REPLACE INTO cell_data(id,value,sheet,cell,style,type,row,col)
  417.    SELECT cd.id, ss.value, cd.sheet, cd.cell, 'str', '', cd.row, cd.col
  418.    FROM shared_strings ss INNER JOIN cell_data cd ON ss.id = cd.value
  419.    WHERE cd.type = 's';"
  420. sqlite3 "$sdbname" "$sql"
  421.  
  422. #basic data formats with id<=40 that are dates.
  423. #  these are not supplied in the xlsx file
  424. sql="UPDATE fmt2cell_data SET numfmtid = 'date'
  425.      WHERE numfmtid IN (14,15,16);"
  426. sqlite3 "$sdbname" "$sql"
  427.  
  428. #Other subformats that are also dates.
  429. sql="REPLACE INTO cell_data (id,value,sheet,cell,style,type,row,col)
  430.  SELECT cd.id, cd.value,cd.sheet,cd.cell,'2','d',cd.row,cd.col
  431.  FROM cell_data cd INNER JOIN fmt2cell_data fc ON cd.style+1=fc.id
  432.  WHERE fc.numfmtid = 'date' and cd.style <> '2'
  433.  AND cd.type='' AND cd.value<>'';";
  434. sqlite3 "$sdbname" "$sql"
  435.  
  436. #Fix the Y1900 leap year bug
  437. sql="UPDATE cell_data SET value='1900-02-29 00:00:00',style='s'
  438.     WHERE value=60 AND style='2';"
  439. sqlite3 "$sdbname" "$sql"
  440.  
  441. #Other dates less than 60 are off by 1
  442. sql="UPDATE cell_data SET value=value+1 WHERE value < 60 AND style='2';"
  443. sqlite3 "$sdbname" "$sql"
  444.  
  445. #convert the Julian serial to date
  446. # add days to convert to unix epoch
  447. # convert epoch to ISO date as text
  448. # end up with YYYY-MM-DD
  449. #Much easier and more reliable
  450. sql="UPDATE cell_data SET value=datetime(value+2415017.5)
  451.     WHERE style='2' and value <> '';"
  452. sqlite3 "$sdbname" "$sql"
  453.  
  454. [[ -z "A" ]] && {
  455. #old school date calculation
  456. # this code is a non-buggy implementation of the
  457. #  buggy code found at
  458. #  http://www.codeproject.com/KB/datetime/exceldmy.aspx?print=true
  459. # The basic idea here is to convert the date to a unix epoch
  460. #  add some days to make sure that 1970-01-01 < date < 2038-01-01
  461. #  because MS date functions only work properly within that range
  462. #  then re-implement MS date math logic to find the date
  463. #  then subtract the bias in years from the date.
  464. # We don't do things like that in Linux land.
  465. sql="UPDATE cell_data SET a=value+68569+2415019 WHERE style='2';"
  466. sqlite3 "$sdbname" "$sql"
  467. sql="UPDATE cell_data SET b=cast((4*a)/146097.0 as integer) WHERE style='2';"
  468. sqlite3 "$sdbname" "$sql"
  469. sql="UPDATE cell_data SET c=a-((146097*b+3)/4) WHERE style='2';"
  470. sqlite3 "$sdbname" "$sql"
  471. sql="UPDATE cell_data SET d=cast((4000*(c+1))/1461001.0 as integer) WHERE style='2';"
  472. sqlite3 "$sdbname" "$sql"
  473. sql="UPDATE cell_data SET e=(c-cast(1461.0*d/4 as integer)+31 WHERE style='2';"
  474. sqlite3 "$sdbname" "$sql"
  475. sql="UPDATE cell_data SET f=cast((80*e)/2447 as integer) WHERE style='2';"
  476. sqlite3 "$sdbname" "$sql"
  477. sql="UPDATE cell_data SET g=cast(f/11 as integer) WHERE style='2';"
  478. sqlite3 "$sdbname" "$sql"
  479. sql="UPDATE cell_data SET day=e-cast((2447.0*f)/80 as integer) WHERE style='2';"
  480. sqlite3 "$sdbname" "$sql"
  481. sql="UPDATE cell_data SET m=cast(f+2.0-(12.0*g) as integer) WHERE style='2';"
  482. sqlite3 "$sdbname" "$sql"
  483. sql="UPDATE cell_data SET y=100*(b-49)+d+g WHERE style='2';"
  484. sqlite3 "$sdbname" "$sql"
  485.  
  486. #Finally!  We have a date!
  487. sql="UPDATE cell_data
  488.     SET value=y || '-' || m || '-' || day, style=''  WHERE style='2';"
  489. sqlite3 "$sdbname" "$sql"
  490. }
  491.  
  492. #don't show nulls as '-' (dash)
  493. sql="UPDATE cell_data SET value='', style=''  WHERE style='3';"
  494. sqlite3 "$sdbname" "$sql"
  495.  
  496. #get the row numbers as integers
  497. #Get the column indices as letters [A-ZZ]
  498. sql="UPDATE cell_data
  499.     SET row=CAST(trim(cell,'ABCDEFGHIJKLMNOPQRSTUVWXYZ') as int),
  500.         col=trim(cell,'0123456789');"
  501. sqlite3 "$sdbname" "$sql"
  502.  
  503. #blow away CRLF in the values
  504. sql="UPDATE cell_data SET value=replace(value,x'0d','');"
  505. sql="$sql UPDATE cell_data SET value=replace(value,x'0a','');"
  506. sqlite3 "$sdbname" "$sql"
  507.  
  508. #set up column list from A-ZZ collated in spreadsheet order
  509. sql="CREATE TABLE columns ( id integer primary key, title varchar(3));"
  510. sqlite3 "$sdbname" "$sql"
  511. #create A-Z
  512. for ((i=65;i<=90;i++))
  513. do
  514.      #convert ascii value to char
  515.      char=$(printf "\\$(printf "%03o" $i)")
  516.      #insert into db
  517.      sql="INSERT INTO columns (title) VALUES ('$char');"
  518.      sqlite3 "$sdbname" "$sql"
  519. done
  520. # Create AA-ZZ
  521. for ((i=1;i<=26;i++))
  522. do
  523.   sql="INSERT INTO columns (title)
  524.       SELECT (SELECT title FROM columns WHERE id=$i) || title
  525.       FROM columns where id <= 26;"
  526.   sqlite3 "$sdbname" "$sql"
  527. done
  528.  
  529. #index the sheet name
  530. sql="CREATE INDEX idx_cd_sheet ON cell_data(sheet);"
  531. sqlite3 "$sdbname" "$sql"
  532. # and the sheet with col
  533. sql="CREATE INDEX idx_cd_sheet_col ON cell_data(sheet,col);"
  534. sqlite3 "$sdbname" "$sql"
  535. # and the sheet with row
  536. sql="CREATE INDEX idx_cd_sheet_row ON cell_data(sheet,row);"
  537. sqlite3 "$sdbname" "$sql"
  538. newline="
  539. "
  540. #Change the internal separator to CRLF
  541. IFS=$'\n'
  542. #walk the table and output the results as csv files.
  543. # for each sheet (csv file name); for each row, for each value
  544. sql="SELECT sheet FROM cell_data group by sheet order by sheet;"
  545. sheets=$(sqlite3 "$sdbname" "$sql")
  546. for sheet in $sheets
  547. do
  548.   #the columns.id field now collates the columns in spreadsheet order
  549.   # all we need to know is the maximum number of columns per sheet
  550.   sql="SELECT c.id FROM columns c INNER JOIN cell_data d ON c.title = d.col
  551.        WHERE sheet='$sheet' ORDER by c.id DESC limit 1;"
  552.   maxcol=$(sqlite3 "$sdbname" "$sql")
  553.  
  554.   #no single quotes in filename
  555.   csv=${sheet//\'/}
  556.   csv="${curdir}/${filtered}_${csv// /_}.csv"
  557.   if [[ -e "${csv}" && x"${overwrite}" == "xYes" ]]; then
  558.        #echo "removing preexisting output file ${csv}"
  559.        rm "${csv}"
  560.   else
  561.        echo "output file ${csv} already exists and --overwrite option not given, exiting ..."
  562.        #return to the invocation inode
  563.        popd > /dev/null
  564.  
  565.        #clean up the temp folder
  566.        [[ -z $debug ]] && rm -rf "$dirname"
  567.        exit 1;
  568.   fi;    
  569.  
  570.   #get the rows for the sheet
  571.   sql="SELECT row FROM cell_data WHERE sheet='$sheet'
  572.       GROUP BY row ORDER BY row;"
  573.   rows=$(sqlite3 "$sdbname" "$sql")
  574.   for row in $rows
  575.   do
  576.     #make sure we have a field represented for every column, even if it's empty
  577.     sql="SELECT d.value FROM columns c left join cell_data d
  578.          ON c.title = d.col AND d.sheet='$sheet' AND d.row=$row
  579.          WHERE c.id <= $maxcol;"
  580.     sqlite3 "$sdbname" "$sql" | #extract the data for the row
  581.         sed -e 's/[&]lt;/</g' -e 's/[&]gt;/>/g'   |
  582.         sed -e 's/"/""/g' -e 's/^/"/' -e 's/$/"/' |  #escape embedded quotes
  583.         tr '\n' ',' | sed "s/,$//" >> "$csv" #convert to csv
  584.     echo >> "${csv}"
  585.   done
  586. done
  587.  
  588. [[ $(hostname) == "wsmkroybal.javelin.pvt" ]] && mv "$sdbname" .
  589.  
  590. #return to the invocation inode
  591. popd > /dev/null
  592.  
  593. #clean up the temp folder
  594. [[ -z $debug ]] && rm -rf "$dirname"
  595.  
  596. #clean end
  597. exit
  598.  
  599. #                     GNU GENERAL PUBLIC LICENSE
  600. #                        Version 3, 29 June 2007
  601. #
  602. #  Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
  603. #  Everyone is permitted to copy and distribute verbatim copies
  604. #  of this license document, but changing it is not allowed.
  605. #
  606. #                             Preamble
  607. #
  608. #   The GNU General Public License is a free, copyleft license for
  609. # software and other kinds of works.
  610. #
  611. #   The licenses for most software and other practical works are designed
  612. # to take away your freedom to share and change the works.  By contrast,
  613. # the GNU General Public License is intended to guarantee your freedom to
  614. # share and change all versions of a program--to make sure it remains free
  615. # software for all its users.  We, the Free Software Foundation, use the
  616. # GNU General Public License for most of our software; it applies also to
  617. # any other work released this way by its authors.  You can apply it to
  618. # your programs, too.
  619. #
  620. #   When we speak of free software, we are referring to freedom, not
  621. # price.  Our General Public Licenses are designed to make sure that you
  622. # have the freedom to distribute copies of free software (and charge for
  623. # them if you wish), that you receive source code or can get it if you
  624. # want it, that you can change the software or use pieces of it in new
  625. # free programs, and that you know you can do these things.
  626. #
  627. #   To protect your rights, we need to prevent others from denying you
  628. # these rights or asking you to surrender the rights.  Therefore, you have
  629. # certain responsibilities if you distribute copies of the software, or if
  630. # you modify it: responsibilities to respect the freedom of others.
  631. #
  632. #   For example, if you distribute copies of such a program, whether
  633. # gratis or for a fee, you must pass on to the recipients the same
  634. # freedoms that you received.  You must make sure that they, too, receive
  635. # or can get the source code.  And you must show them these terms so they
  636. # know their rights.
  637. #
  638. #   Developers that use the GNU GPL protect your rights with two steps:
  639. # (1) assert copyright on the software, and (2) offer you this License
  640. # giving you legal permission to copy, distribute and/or modify it.
  641. #
  642. #   For the developers' and authors' protection, the GPL clearly explains
  643. # that there is no warranty for this free software.  For both users' and
  644. # authors' sake, the GPL requires that modified versions be marked as
  645. # changed, so that their problems will not be attributed erroneously to
  646. # authors of previous versions.
  647. #
  648. #   Some devices are designed to deny users access to install or run
  649. # modified versions of the software inside them, although the manufacturer
  650. # can do so.  This is fundamentally incompatible with the aim of
  651. # protecting users' freedom to change the software.  The systematic
  652. # pattern of such abuse occurs in the area of products for individuals to
  653. # use, which is precisely where it is most unacceptable.  Therefore, we
  654. # have designed this version of the GPL to prohibit the practice for those
  655. # products.  If such problems arise substantially in other domains, we
  656. # stand ready to extend this provision to those domains in future versions
  657. # of the GPL, as needed to protect the freedom of users.
  658. #
  659. #   Finally, every program is threatened constantly by software patents.
  660. # States should not allow patents to restrict development and use of
  661. # software on general-purpose computers, but in those that do, we wish to
  662. # avoid the special danger that patents applied to a free program could
  663. # make it effectively proprietary.  To prevent this, the GPL assures that
  664. # patents cannot be used to render the program non-free.
  665. #
  666. #   The precise terms and conditions for copying, distribution and
  667. # modification follow.
  668. #
  669. #                        TERMS AND CONDITIONS
  670. #
  671. #   0. Definitions.
  672. #
  673. #   "This License" refers to version 3 of the GNU General Public License.
  674. #
  675. #   "Copyright" also means copyright-like laws that apply to other kinds of
  676. # works, such as semiconductor masks.
  677. #
  678. #   "The Program" refers to any copyrightable work licensed under this
  679. # License.  Each licensee is addressed as "you".  "Licensees" and
  680. # "recipients" may be individuals or organizations.
  681. #
  682. #   To "modify" a work means to copy from or adapt all or part of the work
  683. # in a fashion requiring copyright permission, other than the making of an
  684. # exact copy.  The resulting work is called a "modified version" of the
  685. # earlier work or a work "based on" the earlier work.
  686. #
  687. #   A "covered work" means either the unmodified Program or a work based
  688. # on the Program.
  689. #
  690. #   To "propagate" a work means to do anything with it that, without
  691. # permission, would make you directly or secondarily liable for
  692. # infringement under applicable copyright law, except executing it on a
  693. # computer or modifying a private copy.  Propagation includes copying,
  694. # distribution (with or without modification), making available to the
  695. # public, and in some countries other activities as well.
  696. #
  697. #   To "convey" a work means any kind of propagation that enables other
  698. # parties to make or receive copies.  Mere interaction with a user through
  699. # a computer network, with no transfer of a copy, is not conveying.
  700. #
  701. #   An interactive user interface displays "Appropriate Legal Notices"
  702. # to the extent that it includes a convenient and prominently visible
  703. # feature that (1) displays an appropriate copyright notice, and (2)
  704. # tells the user that there is no warranty for the work (except to the
  705. # extent that warranties are provided), that licensees may convey the
  706. # work under this License, and how to view a copy of this License.  If
  707. # the interface presents a list of user commands or options, such as a
  708. # menu, a prominent item in the list meets this criterion.
  709. #
  710. #   1. Source Code.
  711. #
  712. #   The "source code" for a work means the preferred form of the work
  713. # for making modifications to it.  "Object code" means any non-source
  714. # form of a work.
  715. #
  716. #   A "Standard Interface" means an interface that either is an official
  717. # standard defined by a recognized standards body, or, in the case of
  718. # interfaces specified for a particular programming language, one that
  719. # is widely used among developers working in that language.
  720. #
  721. #   The "System Libraries" of an executable work include anything, other
  722. # than the work as a whole, that (a) is included in the normal form of
  723. # packaging a Major Component, but which is not part of that Major
  724. # Component, and (b) serves only to enable use of the work with that
  725. # Major Component, or to implement a Standard Interface for which an
  726. # implementation is available to the public in source code form.  A
  727. # "Major Component", in this context, means a major essential component
  728. # (kernel, window system, and so on) of the specific operating system
  729. # (if any) on which the executable work runs, or a compiler used to
  730. # produce the work, or an object code interpreter used to run it.
  731. #
  732. #   The "Corresponding Source" for a work in object code form means all
  733. # the source code needed to generate, install, and (for an executable
  734. # work) run the object code and to modify the work, including scripts to
  735. # control those activities.  However, it does not include the work's
  736. # System Libraries, or general-purpose tools or generally available free
  737. # programs which are used unmodified in performing those activities but
  738. # which are not part of the work.  For example, Corresponding Source
  739. # includes interface definition files associated with source files for
  740. # the work, and the source code for shared libraries and dynamically
  741. # linked subprograms that the work is specifically designed to require,
  742. # such as by intimate data communication or control flow between those
  743. # subprograms and other parts of the work.
  744. #
  745. #   The Corresponding Source need not include anything that users
  746. # can regenerate automatically from other parts of the Corresponding
  747. # Source.
  748. #
  749. #   The Corresponding Source for a work in source code form is that
  750. # same work.
  751. #
  752. #   2. Basic Permissions.
  753. #
  754. #   All rights granted under this License are granted for the term of
  755. # copyright on the Program, and are irrevocable provided the stated
  756. # conditions are met.  This License explicitly affirms your unlimited
  757. # permission to run the unmodified Program.  The output from running a
  758. # covered work is covered by this License only if the output, given its
  759. # content, constitutes a covered work.  This License acknowledges your
  760. # rights of fair use or other equivalent, as provided by copyright law.
  761. #
  762. #   You may make, run and propagate covered works that you do not
  763. # convey, without conditions so long as your license otherwise remains
  764. # in force.  You may convey covered works to others for the sole purpose
  765. # of having them make modifications exclusively for you, or provide you
  766. # with facilities for running those works, provided that you comply with
  767. # the terms of this License in conveying all material for which you do
  768. # not control copyright.  Those thus making or running the covered works
  769. # for you must do so exclusively on your behalf, under your direction
  770. # and control, on terms that prohibit them from making any copies of
  771. # your copyrighted material outside their relationship with you.
  772. #
  773. #   Conveying under any other circumstances is permitted solely under
  774. # the conditions stated below.  Sublicensing is not allowed; section 10
  775. # makes it unnecessary.
  776. #
  777. #   3. Protecting Users' Legal Rights From Anti-Circumvention Law.
  778. #
  779. #   No covered work shall be deemed part of an effective technological
  780. # measure under any applicable law fulfilling obligations under article
  781. # 11 of the WIPO copyright treaty adopted on 20 December 1996, or
  782. # similar laws prohibiting or restricting circumvention of such
  783. # measures.
  784. #
  785. #   When you convey a covered work, you waive any legal power to forbid
  786. # circumvention of technological measures to the extent such circumvention
  787. # is effected by exercising rights under this License with respect to
  788. # the covered work, and you disclaim any intention to limit operation or
  789. # modification of the work as a means of enforcing, against the work's
  790. # users, your or third parties' legal rights to forbid circumvention of
  791. # technological measures.
  792. #
  793. #   4. Conveying Verbatim Copies.
  794. #
  795. #   You may convey verbatim copies of the Program's source code as you
  796. # receive it, in any medium, provided that you conspicuously and
  797. # appropriately publish on each copy an appropriate copyright notice;
  798. # keep intact all notices stating that this License and any
  799. # non-permissive terms added in accord with section 7 apply to the code;
  800. # keep intact all notices of the absence of any warranty; and give all
  801. # recipients a copy of this License along with the Program.
  802. #
  803. #   You may charge any price or no price for each copy that you convey,
  804. # and you may offer support or warranty protection for a fee.
  805. #
  806. #   5. Conveying Modified Source Versions.
  807. #
  808. #   You may convey a work based on the Program, or the modifications to
  809. # produce it from the Program, in the form of source code under the
  810. # terms of section 4, provided that you also meet all of these conditions:
  811. #
  812. #     a) The work must carry prominent notices stating that you modified
  813. #     it, and giving a relevant date.
  814. #
  815. #     b) The work must carry prominent notices stating that it is
  816. #     released under this License and any conditions added under section
  817. #     7.  This requirement modifies the requirement in section 4 to
  818. #     "keep intact all notices".
  819. #
  820. #     c) You must license the entire work, as a whole, under this
  821. #     License to anyone who comes into possession of a copy.  This
  822. #     License will therefore apply, along with any applicable section 7
  823. #     additional terms, to the whole of the work, and all its parts,
  824. #     regardless of how they are packaged.  This License gives no
  825. #     permission to license the work in any other way, but it does not
  826. #     invalidate such permission if you have separately received it.
  827. #
  828. #     d) If the work has interactive user interfaces, each must display
  829. #     Appropriate Legal Notices; however, if the Program has interactive
  830. #     interfaces that do not display Appropriate Legal Notices, your
  831. #     work need not make them do so.
  832. #
  833. #   A compilation of a covered work with other separate and independent
  834. # works, which are not by their nature extensions of the covered work,
  835. # and which are not combined with it such as to form a larger program,
  836. # in or on a volume of a storage or distribution medium, is called an
  837. # "aggregate" if the compilation and its resulting copyright are not
  838. # used to limit the access or legal rights of the compilation's users
  839. # beyond what the individual works permit.  Inclusion of a covered work
  840. # in an aggregate does not cause this License to apply to the other
  841. # parts of the aggregate.
  842. #
  843. #   6. Conveying Non-Source Forms.
  844. #
  845. #   You may convey a covered work in object code form under the terms
  846. # of sections 4 and 5, provided that you also convey the
  847. # machine-readable Corresponding Source under the terms of this License,
  848. # in one of these ways:
  849. #
  850. #     a) Convey the object code in, or embodied in, a physical product
  851. #     (including a physical distribution medium), accompanied by the
  852. #     Corresponding Source fixed on a durable physical medium
  853. #     customarily used for software interchange.
  854. #
  855. #     b) Convey the object code in, or embodied in, a physical product
  856. #     (including a physical distribution medium), accompanied by a
  857. #     written offer, valid for at least three years and valid for as
  858. #     long as you offer spare parts or customer support for that product
  859. #     model, to give anyone who possesses the object code either (1) a
  860. #     copy of the Corresponding Source for all the software in the
  861. #     product that is covered by this License, on a durable physical
  862. #     medium customarily used for software interchange, for a price no
  863. #     more than your reasonable cost of physically performing this
  864. #     conveying of source, or (2) access to copy the
  865. #     Corresponding Source from a network server at no charge.
  866. #
  867. #     c) Convey individual copies of the object code with a copy of the
  868. #     written offer to provide the Corresponding Source.  This
  869. #     alternative is allowed only occasionally and noncommercially, and
  870. #     only if you received the object code with such an offer, in accord
  871. #     with subsection 6b.
  872. #
  873. #     d) Convey the object code by offering access from a designated
  874. #     place (gratis or for a charge), and offer equivalent access to the
  875. #     Corresponding Source in the same way through the same place at no
  876. #     further charge.  You need not require recipients to copy the
  877. #     Corresponding Source along with the object code.  If the place to
  878. #     copy the object code is a network server, the Corresponding Source
  879. #     may be on a different server (operated by you or a third party)
  880. #     that supports equivalent copying facilities, provided you maintain
  881. #     clear directions next to the object code saying where to find the
  882. #     Corresponding Source.  Regardless of what server hosts the
  883. #     Corresponding Source, you remain obligated to ensure that it is
  884. #     available for as long as needed to satisfy these requirements.
  885. #
  886. #     e) Convey the object code using peer-to-peer transmission, provided
  887. #     you inform other peers where the object code and Corresponding
  888. #     Source of the work are being offered to the general public at no
  889. #     charge under subsection 6d.
  890. #
  891. #   A separable portion of the object code, whose source code is excluded
  892. # from the Corresponding Source as a System Library, need not be
  893. # included in conveying the object code work.
  894. #
  895. #   A "User Product" is either (1) a "consumer product", which means any
  896. # tangible personal property which is normally used for personal, family,
  897. # or household purposes, or (2) anything designed or sold for incorporation
  898. # into a dwelling.  In determining whether a product is a consumer product,
  899. # doubtful cases shall be resolved in favor of coverage.  For a particular
  900. # product received by a particular user, "normally used" refers to a
  901. # typical or common use of that class of product, regardless of the status
  902. # of the particular user or of the way in which the particular user
  903. # actually uses, or expects or is expected to use, the product.  A product
  904. # is a consumer product regardless of whether the product has substantial
  905. # commercial, industrial or non-consumer uses, unless such uses represent
  906. # the only significant mode of use of the product.
  907. #
  908. #   "Installation Information" for a User Product means any methods,
  909. # procedures, authorization keys, or other information required to install
  910. # and execute modified versions of a covered work in that User Product from
  911. # a modified version of its Corresponding Source.  The information must
  912. # suffice to ensure that the continued functioning of the modified object
  913. # code is in no case prevented or interfered with solely because
  914. # modification has been made.
  915. #
  916. #   If you convey an object code work under this section in, or with, or
  917. # specifically for use in, a User Product, and the conveying occurs as
  918. # part of a transaction in which the right of possession and use of the
  919. # User Product is transferred to the recipient in perpetuity or for a
  920. # fixed term (regardless of how the transaction is characterized), the
  921. # Corresponding Source conveyed under this section must be accompanied
  922. # by the Installation Information.  But this requirement does not apply
  923. # if neither you nor any third party retains the ability to install
  924. # modified object code on the User Product (for example, the work has
  925. # been installed in ROM).
  926. #
  927. #   The requirement to provide Installation Information does not include a
  928. # requirement to continue to provide support service, warranty, or updates
  929. # for a work that has been modified or installed by the recipient, or for
  930. # the User Product in which it has been modified or installed.  Access to a
  931. # network may be denied when the modification itself materially and
  932. # adversely affects the operation of the network or violates the rules and
  933. # protocols for communication across the network.
  934. #
  935. #   Corresponding Source conveyed, and Installation Information provided,
  936. # in accord with this section must be in a format that is publicly
  937. # documented (and with an implementation available to the public in
  938. # source code form), and must require no special password or key for
  939. # unpacking, reading or copying.
  940. #
  941. #   7. Additional Terms.
  942. #
  943. #   "Additional permissions" are terms that supplement the terms of this
  944. # License by making exceptions from one or more of its conditions.
  945. # Additional permissions that are applicable to the entire Program shall
  946. # be treated as though they were included in this License, to the extent
  947. # that they are valid under applicable law.  If additional permissions
  948. # apply only to part of the Program, that part may be used separately
  949. # under those permissions, but the entire Program remains governed by
  950. # this License without regard to the additional permissions.
  951. #
  952. #   When you convey a copy of a covered work, you may at your option
  953. # remove any additional permissions from that copy, or from any part of
  954. # it.  (Additional permissions may be written to require their own
  955. # removal in certain cases when you modify the work.)  You may place
  956. # additional permissions on material, added by you to a covered work,
  957. # for which you have or can give appropriate copyright permission.
  958. #
  959. #   Notwithstanding any other provision of this License, for material you
  960. # add to a covered work, you may (if authorized by the copyright holders of
  961. # that material) supplement the terms of this License with terms:
  962. #
  963. #     a) Disclaiming warranty or limiting liability differently from the
  964. #     terms of sections 15 and 16 of this License; or
  965. #
  966. #     b) Requiring preservation of specified reasonable legal notices or
  967. #     author attributions in that material or in the Appropriate Legal
  968. #     Notices displayed by works containing it; or
  969. #
  970. #     c) Prohibiting misrepresentation of the origin of that material, or
  971. #     requiring that modified versions of such material be marked in
  972. #     reasonable ways as different from the original version; or
  973. #
  974. #     d) Limiting the use for publicity purposes of names of licensors or
  975. #     authors of the material; or
  976. #
  977. #     e) Declining to grant rights under trademark law for use of some
  978. #     trade names, trademarks, or service marks; or
  979. #
  980. #     f) Requiring indemnification of licensors and authors of that
  981. #     material by anyone who conveys the material (or modified versions of
  982. #     it) with contractual assumptions of liability to the recipient, for
  983. #     any liability that these contractual assumptions directly impose on
  984. #     those licensors and authors.
  985. #
  986. #   All other non-permissive additional terms are considered "further
  987. # restrictions" within the meaning of section 10.  If the Program as you
  988. # received it, or any part of it, contains a notice stating that it is
  989. # governed by this License along with a term that is a further
  990. # restriction, you may remove that term.  If a license document contains
  991. # a further restriction but permits relicensing or conveying under this
  992. # License, you may add to a covered work material governed by the terms
  993. # of that license document, provided that the further restriction does
  994. # not survive such relicensing or conveying.
  995. #
  996. #   If you add terms to a covered work in accord with this section, you
  997. # must place, in the relevant source files, a statement of the
  998. # additional terms that apply to those files, or a notice indicating
  999. # where to find the applicable terms.
  1000. #
  1001. #   Additional terms, permissive or non-permissive, may be stated in the
  1002. # form of a separately written license, or stated as exceptions;
  1003. # the above requirements apply either way.
  1004. #
  1005. #   8. Termination.
  1006. #
  1007. #   You may not propagate or modify a covered work except as expressly
  1008. # provided under this License.  Any attempt otherwise to propagate or
  1009. # modify it is void, and will automatically terminate your rights under
  1010. # this License (including any patent licenses granted under the third
  1011. # paragraph of section 11).
  1012. #
  1013. #   However, if you cease all violation of this License, then your
  1014. # license from a particular copyright holder is reinstated (a)
  1015. # provisionally, unless and until the copyright holder explicitly and
  1016. # finally terminates your license, and (b) permanently, if the copyright
  1017. # holder fails to notify you of the violation by some reasonable means
  1018. # prior to 60 days after the cessation.
  1019. #
  1020. #   Moreover, your license from a particular copyright holder is
  1021. # reinstated permanently if the copyright holder notifies you of the
  1022. # violation by some reasonable means, this is the first time you have
  1023. # received notice of violation of this License (for any work) from that
  1024. # copyright holder, and you cure the violation prior to 30 days after
  1025. # your receipt of the notice.
  1026. #
  1027. #   Termination of your rights under this section does not terminate the
  1028. # licenses of parties who have received copies or rights from you under
  1029. # this License.  If your rights have been terminated and not permanently
  1030. # reinstated, you do not qualify to receive new licenses for the same
  1031. # material under section 10.
  1032. #
  1033. #   9. Acceptance Not Required for Having Copies.
  1034. #
  1035. #   You are not required to accept this License in order to receive or
  1036. # run a copy of the Program.  Ancillary propagation of a covered work
  1037. # occurring solely as a consequence of using peer-to-peer transmission
  1038. # to receive a copy likewise does not require acceptance.  However,
  1039. # nothing other than this License grants you permission to propagate or
  1040. # modify any covered work.  These actions infringe copyright if you do
  1041. # not accept this License.  Therefore, by modifying or propagating a
  1042. # covered work, you indicate your acceptance of this License to do so.
  1043. #
  1044. #   10. Automatic Licensing of Downstream Recipients.
  1045. #
  1046. #   Each time you convey a covered work, the recipient automatically
  1047. # receives a license from the original licensors, to run, modify and
  1048. # propagate that work, subject to this License.  You are not responsible
  1049. # for enforcing compliance by third parties with this License.
  1050. #
  1051. #   An "entity transaction" is a transaction transferring control of an
  1052. # organization, or substantially all assets of one, or subdividing an
  1053. # organization, or merging organizations.  If propagation of a covered
  1054. # work results from an entity transaction, each party to that
  1055. # transaction who receives a copy of the work also receives whatever
  1056. # licenses to the work the party's predecessor in interest had or could
  1057. # give under the previous paragraph, plus a right to possession of the
  1058. # Corresponding Source of the work from the predecessor in interest, if
  1059. # the predecessor has it or can get it with reasonable efforts.
  1060. #
  1061. #   You may not impose any further restrictions on the exercise of the
  1062. # rights granted or affirmed under this License.  For example, you may
  1063. # not impose a license fee, royalty, or other charge for exercise of
  1064. # rights granted under this License, and you may not initiate litigation
  1065. # (including a cross-claim or counterclaim in a lawsuit) alleging that
  1066. # any patent claim is infringed by making, using, selling, offering for
  1067. # sale, or importing the Program or any portion of it.
  1068. #
  1069. #   11. Patents.
  1070. #
  1071. #   A "contributor" is a copyright holder who authorizes use under this
  1072. # License of the Program or a work on which the Program is based.  The
  1073. # work thus licensed is called the contributor's "contributor version".
  1074. #
  1075. #   A contributor's "essential patent claims" are all patent claims
  1076. # owned or controlled by the contributor, whether already acquired or
  1077. # hereafter acquired, that would be infringed by some manner, permitted
  1078. # by this License, of making, using, or selling its contributor version,
  1079. # but do not include claims that would be infringed only as a
  1080. # consequence of further modification of the contributor version.  For
  1081. # purposes of this definition, "control" includes the right to grant
  1082. # patent sublicenses in a manner consistent with the requirements of
  1083. # this License.
  1084. #
  1085. #   Each contributor grants you a non-exclusive, worldwide, royalty-free
  1086. # patent license under the contributor's essential patent claims, to
  1087. # make, use, sell, offer for sale, import and otherwise run, modify and
  1088. # propagate the contents of its contributor version.
  1089. #
  1090. #   In the following three paragraphs, a "patent license" is any express
  1091. # agreement or commitment, however denominated, not to enforce a patent
  1092. # (such as an express permission to practice a patent or covenant not to
  1093. # sue for patent infringement).  To "grant" such a patent license to a
  1094. # party means to make such an agreement or commitment not to enforce a
  1095. # patent against the party.
  1096. #
  1097. #   If you convey a covered work, knowingly relying on a patent license,
  1098. # and the Corresponding Source of the work is not available for anyone
  1099. # to copy, free of charge and under the terms of this License, through a
  1100. # publicly available network server or other readily accessible means,
  1101. # then you must either (1) cause the Corresponding Source to be so
  1102. # available, or (2) arrange to deprive yourself of the benefit of the
  1103. # patent license for this particular work, or (3) arrange, in a manner
  1104. # consistent with the requirements of this License, to extend the patent
  1105. # license to downstream recipients.  "Knowingly relying" means you have
  1106. # actual knowledge that, but for the patent license, your conveying the
  1107. # covered work in a country, or your recipient's use of the covered work
  1108. # in a country, would infringe one or more identifiable patents in that
  1109. # country that you have reason to believe are valid.
  1110. #
  1111. #   If, pursuant to or in connection with a single transaction or
  1112. # arrangement, you convey, or propagate by procuring conveyance of, a
  1113. # covered work, and grant a patent license to some of the parties
  1114. # receiving the covered work authorizing them to use, propagate, modify
  1115. # or convey a specific copy of the covered work, then the patent license
  1116. # you grant is automatically extended to all recipients of the covered
  1117. # work and works based on it.
  1118. #
  1119. #   A patent license is "discriminatory" if it does not include within
  1120. # the scope of its coverage, prohibits the exercise of, or is
  1121. # conditioned on the non-exercise of one or more of the rights that are
  1122. # specifically granted under this License.  You may not convey a covered
  1123. # work if you are a party to an arrangement with a third party that is
  1124. # in the business of distributing software, under which you make payment
  1125. # to the third party based on the extent of your activity of conveying
  1126. # the work, and under which the third party grants, to any of the
  1127. # parties who would receive the covered work from you, a discriminatory
  1128. # patent license (a) in connection with copies of the covered work
  1129. # conveyed by you (or copies made from those copies), or (b) primarily
  1130. # for and in connection with specific products or compilations that
  1131. # contain the covered work, unless you entered into that arrangement,
  1132. # or that patent license was granted, prior to 28 March 2007.
  1133. #
  1134. #   Nothing in this License shall be construed as excluding or limiting
  1135. # any implied license or other defenses to infringement that may
  1136. # otherwise be available to you under applicable patent law.
  1137. #
  1138. #   12. No Surrender of Others' Freedom.
  1139. #
  1140. #   If conditions are imposed on you (whether by court order, agreement or
  1141. # otherwise) that contradict the conditions of this License, they do not
  1142. # excuse you from the conditions of this License.  If you cannot convey a
  1143. # covered work so as to satisfy simultaneously your obligations under this
  1144. # License and any other pertinent obligations, then as a consequence you may
  1145. # not convey it at all.  For example, if you agree to terms that obligate you
  1146. # to collect a royalty for further conveying from those to whom you convey
  1147. # the Program, the only way you could satisfy both those terms and this
  1148. # License would be to refrain entirely from conveying the Program.
  1149. #
  1150. #   13. Use with the GNU Affero General Public License.
  1151. #
  1152. #   Notwithstanding any other provision of this License, you have
  1153. # permission to link or combine any covered work with a work licensed
  1154. # under version 3 of the GNU Affero General Public License into a single
  1155. # combined work, and to convey the resulting work.  The terms of this
  1156. # License will continue to apply to the part which is the covered work,
  1157. # but the special requirements of the GNU Affero General Public License,
  1158. # section 13, concerning interaction through a network will apply to the
  1159. # combination as such.
  1160. #
  1161. #   14. Revised Versions of this License.
  1162. #
  1163. #   The Free Software Foundation may publish revised and/or new versions of
  1164. # the GNU General Public License from time to time.  Such new versions will
  1165. # be similar in spirit to the present version, but may differ in detail to
  1166. # address new problems or concerns.
  1167. #
  1168. #   Each version is given a distinguishing version number.  If the
  1169. # Program specifies that a certain numbered version of the GNU General
  1170. # Public License "or any later version" applies to it, you have the
  1171. # option of following the terms and conditions either of that numbered
  1172. # version or of any later version published by the Free Software
  1173. # Foundation.  If the Program does not specify a version number of the
  1174. # GNU General Public License, you may choose any version ever published
  1175. # by the Free Software Foundation.
  1176. #
  1177. #   If the Program specifies that a proxy can decide which future
  1178. # versions of the GNU General Public License can be used, that proxy's
  1179. # public statement of acceptance of a version permanently authorizes you
  1180. # to choose that version for the Program.
  1181. #
  1182. #   Later license versions may give you additional or different
  1183. # permissions.  However, no additional obligations are imposed on any
  1184. # author or copyright holder as a result of your choosing to follow a
  1185. # later version.
  1186. #
  1187. #   15. Disclaimer of Warranty.
  1188. #
  1189. #   THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
  1190. # APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
  1191. # HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
  1192. # OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
  1193. # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  1194. # PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
  1195. # IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
  1196. # ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
  1197. #
  1198. #   16. Limitation of Liability.
  1199. #
  1200. #   IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
  1201. # WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
  1202. # THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
  1203. # GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
  1204. # USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
  1205. # DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
  1206. # PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
  1207. # EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
  1208. # SUCH DAMAGES.
  1209. #
  1210. #   17. Interpretation of Sections 15 and 16.
  1211. #
  1212. #   If the disclaimer of warranty and limitation of liability provided
  1213. # above cannot be given local legal effect according to their terms,
  1214. # reviewing courts shall apply local law that most closely approximates
  1215. # an absolute waiver of all civil liability in connection with the
  1216. # Program, unless a warranty or assumption of liability accompanies a
  1217. # copy of the Program in return for a fee.
  1218. #
  1219. #                      END OF TERMS AND CONDITIONS
  1220.  
  1221.  
  1222.  
  1223. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  1224. <xsl:output method="text"/>
  1225.  
  1226. <xsl:template match="sheetData">
  1227.   <xsl:apply-templates select="row"/>
  1228. </xsl:template>
  1229.  
  1230. <xsl:template match="row">
  1231.   <xsl:for-each select="*">
  1232.    <xsl:value-of select="'INSERT INTO cell_data (cell,style,type,value) VALUES (|'"/>
  1233.    <xsl:value-of select="@r"/> <!-- cell identifier -->
  1234.    <xsl:value-of select="'|,|'"/>
  1235.    <xsl:value-of select="@s"/> <!-- format -->
  1236.    <xsl:value-of select="'|,|'"/>
  1237.    <xsl:value-of select="@t"/> <!-- data type -->
  1238.    <xsl:value-of select="'|,|'"/>
  1239.    <xsl:value-of select="v"/> <!-- the calculated value -->
  1240.    <xsl:value-of select="'|);'"/>
  1241.    <xsl:if test="position() != last()">
  1242.     <!-- <xsl:value-of select="');'"/> -->
  1243.     <xsl:text>&#10;</xsl:text>
  1244.    </xsl:if>
  1245.   </xsl:for-each>
  1246.   <xsl:text>&#10;</xsl:text>
  1247. </xsl:template>
  1248.  
  1249. </xsl:stylesheet>
Advertisement
Add Comment
Please, Sign In to add comment