VBA-tools / VBA-Web

VBA-Web: Connect VBA, Excel, Access, and Office for Windows and Mac to web services and the web
http://vba-tools.github.io/VBA-Web/
MIT License
2.01k stars 494 forks source link

Add a Parser for CSV format #183

Closed SebAlbert closed 8 years ago

SebAlbert commented 8 years ago

Hi

This project looks awesome, especially for a VBA agnostic like me. Question: Is there a simple straightforward "correct" way to parse CSV in the WebResponse? (I always prefer default mechanisms over implementing such things on my own, even in so seemingly easy cases, for not reinventing the wheel and because of possible pitfalls.)

Sebastian

timhall commented 8 years ago

I have not tried to write the parser, but here is how to use it: WebHelpers.RegisterConverter

' 1. Use global module functions for Convert and Parse
' ---
' Module: CSVConverter
Function ParseCSV(Value As String) As Object
  ' Parse response body (Value) as csv
  '
  ' Note: Return value needs to be an Object (e.g. Collection/Dictionary)
  '       May add support for value types in the future
End Function
Function ConvertToCSV(Value As Variant) As String
  ' Convert raw Request.Body to string
  ' (can be empty if only parsing is desired)
End Function

WebHelpers.RegisterConverter "csv", "text/csv", _
  "CSVConverter.ConvertToCSV", "CSVConverter.ParseCSV"

As for the body of ParseCSV, I'd imagine it would look something like the following (converts to Collection of Array):

Function ParseCSV(Value As String) As Object
  Dim Lines() As String
  Dim Row As Long
  Dim Parsed As New Collection

  Lines = VBA.Split(Value, vbCrLf)
  For Row = LBound(Lines) To UBound(Lines)
    Parsed.Add VBA.Split(Lines(Row), ",")
  Next Row

  Set ParseCSV = Parsed
End Function
SebAlbert commented 8 years ago

Thanks!

As for the example code, by looking at it, I'd guess it would not properly ignore commas inside quotation marks - which is basically what I was thinking of by mentioning possible pitfalls - even going further with allowing for escaped quotation marks within quotation marks, maybe even line breaks within fields, etc.

I thought there might be some way to leverage Excel's functionality of importing/opening CSV files, just without the input being a "file" from the filesystem. I'd guess Excel's own mechanism would be quite mature and standards-compliant, but I'm not familiar with Ado/.NET or whatever it's called.

sdkn104 commented 7 years ago

Hi,

The following is a CSV parser which is compliant with RFC4180 standard. It may be used for VBA-Web. https://github.com/sdkn104/VBA-CSV