Classic ASP - How to preserve commas while parsing a CSV file

孤人 提交于 2019-12-25 05:29:32

问题


The Scenario

4 columns, ID, ParentID, Category, OrderNo and Category can have commas in it e.g "Sales, Manager" or "HR, Recruitment" so I would have to handle that without being able to know that the words have quotes around them as the files they use don't so I would need to handle rows with odd number of commas and then treat those rows as ones with categories with commas inside so it's a little more complicated.


回答1:


I'd personally use the Microsoft Text Driver to parse CSV files, makes dealing with the data alot easier.

First create a text.dsn file and save it somewhere in your web app (in the example i'll assume its where the CSV file is located)

[ODBC]
DRIVER=Microsoft Text Driver (*.txt; *.csv)
UID=admin
UserCommitSync=Yes
Threads=3
SafeTransactions=0
PageTimeout=5
MaxScanRows=25
MaxBufferSize=512
ImplicitCommitSync=Yes
FIL=text
Extensions=txt,csv,tab,asc
DriverId=27

Then treat it as a normal db connection eg:

strPath = server.mappath("/csv/")
sDSNFile = "text.dsn"
strCSVFile = "test.csv"

sDSN = "FileDSN=" & strPath & sDSNFile & ";DefaultDir=" & strPath & ";DBQ=" & strPath & ";"
Set Conn = CreateObject("ADODB.Connection")
Conn.Open sDSN
sql = "SELECT * FROM [" & strCSVFile & "]"

set rs = conn.execute(sql)

do until rs.eof
    id = rs("ID")
    ParentID = rs("ParentID")
    Category = rs("Category")
    OrderNo = rs("orderno")
    ' do something cool here
loop

This way you could pull say all developers out using standard sql

sql = "SELECT * FROM [" & strCSVFile & "] where Category='Developer'"

Hope this helps.

ps. If you don't have it installed, I think the text driver is included as part of Microsoft Access Database Engine redistributable, but it has been a while so may be wrong :)



来源:https://stackoverflow.com/questions/28374540/classic-asp-how-to-preserve-commas-while-parsing-a-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!