Changeset 1803


Ignore:
Timestamp:
May 4, 2011, 9:53:40 AM (6 years ago)
Author:
s.h.sikkema@…
Message:

Improved CSV export

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/grails-app/services/dbnp/studycapturing/AssayService.groovy

    r1790 r1803  
    523523
    524524        outputStream << rowData.collect { row ->
    525           row.collect{ it ? "\"$it\"" : '""' }.join(',')
     525          row.collect{
     526
     527              // omit quotes in case of numeric values
     528              if (it instanceof Number) return it
     529
     530              def s = it.toString()
     531
     532              def addQuotes = false
     533
     534              // escape double quotes with double quotes if they exist and
     535              // enable surround with quotes
     536              if (s.contains('"')) {
     537                  addQuotes = true
     538                  s = s.replaceAll('"','""')
     539              } else {
     540                  // enable surround with quotes in case of comma's
     541                  if (s.contains(',') || s.contains('\n')) addQuotes = true
     542              }
     543
     544              addQuotes ? "\"$s\"" : s
     545
     546          }.join(',')
    526547        }.join('\n')
    527548
  • trunk/test/unit/dbnp/studycapturing/AssayServiceTests.groovy

    r1790 r1803  
    262262//    }
    263263
    264 
     264    void testCSVOutput() {
     265
     266        // We're testing:
     267        // - strings containing any newlines, comma's, or double quotes should
     268        //   be surrounded with double quotes
     269        // - double quotes should be escaped by double quotes ( " -> "" )
     270        // - other strings and numbers should remain 'quoteless'
     271
     272        def rowData = [["""a
     273b""","a,b","a\"b", "abc"],[1,2.0,"3,1"]]
     274
     275        def baos = new ByteArrayOutputStream()
     276
     277        service.exportRowWiseDataToCSVFile rowData, baos
     278
     279        assertEquals 'CSV Output', '"a\nb","a,b","a""b",abc\n1,2.0,"3,1"', baos.toString()
     280
     281    }
    265282}
Note: See TracChangeset for help on using the changeset viewer.