VBscript有模块吗?我需要处理CSV [英] Does VBscript have modules? I need to handle CSV

查看:228
本文介绍了VBscript有模块吗?我需要处理CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要读取一个CSV文件,我唯一可以使用的语言是VBscript。

I have a need to read a CSV file, and the only language I can use is VBscript.

我目前只是打开文件, ,它的工作确定,因为在字段中没有任何引号逗号。但我知道这是一个令人难以置信的脆弱的解决方案。

I'm currently just opening the file and splitting on commas, and it's working OK because there aren't any quoted commas in fields. But I'm aware this is an incredibly fragile solution.

那么,有一个事情作为一个VBscript模块我可以使用?

So, is there such a thing as a VBscript module I can use? Somewhere to get a tried-and-tested regular expression that would only split on commas not in quotes?

任何建议都非常感谢。

推荐答案

VBScript没有与Perl相当的模块系统。不过,您可以使用 ADO 打开CSV文件,像数据库表一样访问它们。代码将如下所示:

VBScript does not have a module system comparable to Perl. However you can open CSV files with ADO and access them like a database table. The code would go something like this:

(有趣的注释仅仅是为了修复破坏的VB语法高亮)
$ b

(The funny comments are solely to fix SO's broken VB syntax highlighting)

Dim conn    ''// As ADODB.Connection
Dim rs      ''// As ADODB.RecordSet
Dim connStr ''// As String
Dim dataDir ''// As String

dataDir = "C:\"                         '"
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dataDir & ";Extended Properties=""text"""

Set conn = CreateObject("ADODB.Connection")
conn.Open(connStr)
Set rs = conn.Execute("SELECT * FROM [data.txt]")

''// do something with the recordset
WScript.Echo rs.Fields.Count & " columns found."
WScript.Echo "---"

WScript.Echo rs.Fields("Col1Name").Value
If Not rs.EOF Then
  rs.MoveNext
  WScript.Echo rs.Fields("Col3Name").Value
End If

''// explicitly closing stuff is somewhat optional
''// in this script, but consider it a good habit
rs.Close
conn.Close

Set rs = Nothing
Set conn = Nothing

创建 schema.ini 文件。如果你没有,你强制文本驱动程序猜测,如果猜测错误的话,所有的赌注都关闭。 schema.ini 必须位于您的数据所在的同一目录中。

Creating a schema.ini file that exactly describes your input is optimal. If you don't, you force the text driver to guess, and all bets are off if it guesses the wrong thing. The schema.ini must reside in the same directory where your data is.

Mine看起来像这样: p>

Mine looked like this:

[data.txt]
Format=Delimited(;)
DecimalSymbol=.
ColNameHeader=True
MaxScanRows=0
Col1=Col1Name Long
Col2=Col2Name Long
Col3=Col3Name Text
Col4=Col4Name Text

与此 data.txt

a;b;c;d
1;2;"foo bar";"yadayada"
1;2;"sample data";"blah"

我得到这个输出:

C:\>cscript -nologo data.vbs
4 columns found.
---
1
sample data

C:\>

在这方面值得阅读:很多ADO关于MSDN的文本文件

这篇关于VBscript有模块吗?我需要处理CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆