Parse CSV-Data

From NSIS Wiki
Jump to navigationJump to search
Author: Comm@nder21 (talk, contrib)


Introduction

This function extracts all values from a csv string, and stores them on top of stack. Also, the number of values found is pushed to stack, on 1. position.

Usage

(1) Combined with functions to read out textfiles line by line, it's possible to handle csv files exported by database-programms.

(2) Another thing is, that there aren't arrays there in NSIS. The solution is to push the input as csv and call this function. Now it's possible to run a loop to do the same thing with all single values contained by the csv. Example code:

 Push "csv;data"
 Call ReadCSV
 Exch $r1
loop:
 IntCmp $r1 1 0 done  0
 Exch
 Exch $1
 # insert output handling here! $1 contains the csv-data.
 Pop $1
 IntOp $r1 $r1 - 1
 Goto loop
done:
 Pop $r1

The function's source

Function  ReadCSV
  Exch $1  # input string (csv)
  Push $2  # substring of $1: length 1, checked for commata
  Push $3  # substring of $1: single value, returned to stack (below $r2)
  Push $r1 # counter: length of $1, number letters to check
  Push $r2 # counter: values found, returned to top of stack
  Push $r3 # length: to determinate length of current value
  StrLen $r1 $1
  StrCpy $r2 0
  StrLen $r3 $1
 loop:
  IntOp $r1 $r1 - 1
  IntCmp $r1 -1 text done
  StrCpy $2 $1 1 $r1
  StrCmp $2 ";" text
  Goto loop
 text:
  Push $r1
  IntOp $r1 $r1 + 1
  IntOp $r3 $r3 - $r1
  StrCpy $3 $1 $r3 $r1
  Pop $r1
  StrCpy $r3 $r1
  IntOp $r2 $r2 + 1
  Push $3
  Exch 6
  Exch 5
  Exch 4
  Exch 3
  Exch
  Goto loop
 done:
  StrCpy $1 $r2
  Pop $r3
  Pop $r2
  Pop $r1
  Pop $3
  Pop $2
  Exch $1
FunctionEnd

Copyright, terms of usage

This function isn't copyrighted. You may use it or not. For commercial products or not. But use it on your own risk! And remember that i developed it, not you - don't go out and tell them, this is your work!

Feedback

Any suggestions, feature requests or even bug reports? Feel free to send me an email or a private message.

Please post any other question, e.g. about usage and customization at the NSIS forums. Remember: You're not alone ...

Changelog

2004-07-18

  • posted function at NSIS Wiki.

2004-07-19

  • bug fixed: wrong count was pushed on top of stack.
  • changed: counter direction from positive to negative, so first value instead of last is now on second position of stack.
  • some optimizations.
  • NSIS Wiki page cleaned-up: new layout, added some explaining information, added contact information.