简体   繁体   English

如何使用VB6写入CSV文件

[英]How to write in CSV file using VB6

How can I write per column in .csv file using VB6 ? 如何使用VB6.csv文件中按列写入? I use File System Object .writeline to read and write in .csv file but my problem is it only write in one column only . 我使用File System Object .writeline读取和写入 .csv文件,但是我的问题是它仅写入一列 Can someone please help me. 有人可以帮帮我吗。

Dim fso As New FileSystemObject
Dim fsoStream As TextStream

Set fsoStream = fso.CreateTextFile("C:\Users\Users\Desktop\File\Sample.csv", True)

fsoStream.WriteLine "Like This is what I have tried" 'this must be written in the first column
fsoStream.WriteLine "But this is a sample only" 'this must be written in the first column
fsoStream.WriteLine "Sample 1" 'this must be written in the second column
fsoStream.WriteLine "Sample 1" 'this must be written in the second column
fsoStream.WriteLine "Sample 2" 'this must be written in the third column
fsoStream.WriteLine "Sample 2" 'this must be written in the third column

fsoStream.Close
Set fsoStream = Nothing
Set fso = Nothing

This picture must be the output. 此图片必须是输出。

在此处输入图片说明

but this is what I have got in using the code above 但这是我在上面的代码中得到的 在此处输入图片说明

Assuming you know what columns you want to write in advance, the following can be used (with optional header row: 假设您知道要预先编写的列,则可以使用以下列(带有可选的标题行:

Dim iFileNo As Integer

iFileNo = FreeFile

Open sFileName For Output As #iFileNo
Write #iFileNo, "ID", "Name", "Age", "Address"
Write #iFileNo, 1, "Person #1", 42, "Place #1"
Write #iFileNo, 2, "Person #2", 57, "Place #2"
Close #iFileNo

You read this as follows: 您阅读如下:

Dim sHeaders As String
Dim iFileNo As Integer
Dim lID As Long
Dim sName As String
Dim iAge As Integer
Dim sAddress As String

iFileNo = FreeFile

Open sFileName For Input As #iFileNo
Line Input #iFileNo, sHeaders
Do Until Eof(iFileNo)
    Input #iFileNo, lID, sName, iAge, sAddress
Loop
Close #iFileNo

You can build a string for each row, and when the row-string is complete then write it to file 您可以为每行建立一个字符串,当行字符串完成后,将其写入文件

for example using the code from your post : 例如使用您帖子中的代码:

Dim strLine As String
Dim fso As New FileSystemObject
Dim fsoStream As TextStream

Set fsoStream = fso.CreateTextFile("C:\Users\Users\Desktop\File\Sample.csv", True)

'prepare the first row
strLine = "Like This is what I have tried" 'this must be written in the first column
'write the first row
fsoStream.WriteLine strLine

'prepare the second row
strLine = "But this is a sample only"      'this must be written in the first column
strLine = strLine & "," & "Sample 1"       'this must be written in the second column
'write the seconde row
fsoStream.WriteLine strLine

'prepare the third row
strLine = ""                               'an empty first column
strLine = strLine & "," & "Sample 1"       'this must be written in the second column
strLine = strLine & "," & "Sample 2"       'this must be written in the third column
'write the third row
fsoStream.WriteLine strLine

'prepare the fourth row
strLine = ""                               'an empty first column
strLine = strLine & ","                    'an empty second column
strLine = strLine & "," & "Sample 2"       'this must be written in the third column
'write the fourth row
fsoStream.WriteLine strLine

fsoStream.Close
Set fsoStream = Nothing
Set fso = Nothing

This will not give the result which you posted in your desired output picture, but that is because of the extra write actions you had in your original code as well 这不会给出您在所需输出图片中发布的结果,但这是因为您在原始代码中还具有额外的写操作

Just delete those extra lines in your code, and the result will be as you posted in the picture. 只需删除代码中的多余行,结果将与您在图片中发布的相同。 I am sure you can find which extra lines i am talking about :) 我相信您可以找到我在说的其他几行:)

As the others have pointed out you write an entire line of text at once. 正如其他人指出的那样,您可以一次编写整行文本。 Text files don't have the concept of columns so you need to rethink how you're preparing your data. 文本文件没有列的概念,因此您需要重新考虑如何准备数据。 User tony bd suggested that you use a disconnected recordset and I think he is right. 用户tony bd建议您使用断开连接的记录集,我认为他是正确的。 Recordsets allow you to easily assign data to columns. 记录集使您可以轻松地将数据分配给列。 Once you have processed all of your data into the recordset you can then save it to a csv file. 将所有数据处理到记录集中后,即可将其保存到csv文件中。

Add a reference to Microsoft ActiveX Data Objects 2.8 Library 添加对Microsoft ActiveX数据对象2.8库的引用

Option Explicit

Private mMyRs As ADODB.Recordset

Private Sub Form_Load()

    CreateRecordset

End Sub

Private Sub Command1_Click()

    SaveRecordset

End Sub

Private Sub CreateRecordset()

    Set mMyRs = New ADODB.Recordset
    With mMyRs
        Set .ActiveConnection = Nothing
        .CursorLocation = adUseClient
    End With

    With mMyRs.Fields
        .Append "Column1", adVarChar, 40
        .Append "Column2", adVarChar, 20
        .Append "Column3", adVarChar, 20
    End With
    mMyRs.Open

    mMyRs.AddNew
    mMyRs.Fields("Column1").Value = "Like This is what I have tried"
    mMyRs.AddNew
    mMyRs.Fields("Column1").Value = "But this is a sample only"
    mMyRs.MoveFirst
    mMyRs.Fields("Column2").Value = "Sample 1"
    mMyRs.MoveNext
    mMyRs.Fields("Column2").Value = "Sample 1"
    mMyRs.MoveFirst
    mMyRs.Fields("Column3").Value = "Sample 2"
    mMyRs.MoveNext
    mMyRs.Fields("Column3").Value = "Sample 2"

End Sub

Private Sub SaveRecordset()
    Dim fHndl As Integer
    Dim strCsvFile As String

    strCsvFile = "C:\Temp\MyCSV.csv"
    fHndl = FreeFile

    Open strCsvFile For Output As fHndl
    mMyRs.MoveFirst
    While mMyRs.EOF = False
        Print #fHndl, mMyRs.Fields("Column1").Value & "," & mMyRs.Fields("Column2").Value & "," & mMyRs.Fields("Column3").Value
        mMyRs.MoveNext
    Wend
    Close #fHndl

End Sub

Result 结果

csv结果图片

The other answers are fine, but the simplest modification to your code would be this: 其他答案很好,但是对您的代码的最简单修改是:

fsoStream.WriteLine "Like This is what I have tried, Sample1, Sample2" 
fsoStream.WriteLine "But this is a sample only, Sample1, Sample2" 

in place of this: 代替这个:

fsoStream.WriteLine "Like This is what I have tried" 'this must be written in the first column
fsoStream.WriteLine "But this is a sample only" 'this must be written in the first column
fsoStream.WriteLine "Sample 1" 'this must be written in the second column
fsoStream.WriteLine "Sample 1" 'this must be written in the second column
fsoStream.WriteLine "Sample 2" 'this must be written in the third column
fsoStream.WriteLine "Sample 2" 'this must be written in the third column

The point is that "csv" means "comma-separated values". 关键是“ csv”表示“逗号分隔的值”。 That means that each column has to be separated by a comma, and on the same line. 这意味着每一列必须用逗号分隔,并且在同一行上。 New line means new row, as you have already seen for yourself. 正如您已经亲眼所见,新行意味着新行。

I see no reason though to use the FileSystemObject, it's much easier to use the standard open,close,print functions from VB 我认为没有理由使用FileSystemObject,但使用VB中的标准打开,关闭,打印功能要容易得多

To create the output you want you can use the following code: 要创建所需的输出,可以使用以下代码:

Dim intFile As Integer
Dim strFile As String
Dim strLine As String

'open the file
intFile = FreeFile
strFile = "c:\temp\test.csv"
Open strFile For Output As #intFile

  'prepare the first row
  strLine = "Like This is what I have tried" 'this must be written in the first column
  strLine = strLine & "," & "Sample 1"       'this must be written in the second column
  strLine = strLine & "," & "Sample 2"       'this must be written in the third column
  'write the first row
  Print #intFile, strLine

  'prepare the second row
  strLine = "But this is a sample only"      'this must be written in the first column
  strLine = strLine & "," & "Sample 1"       'this must be written in the second column
  strLine = strLine & "," & "Sample 2"       'this must be written in the third column
  'write the seconde row
  Print #intFile, strLine

'close the file
Close #intFile

Instead of writing each line separately you can also build the whole csv in 1 string by adding a vbCrLF to the previous line and then add the next line to the string 除了单独编写每一行之外,您还可以通过在前一行中添加vbCrLF然后在字符串中添加下一行来在1个字符串中构建整个csv

strTotalLines = strTotalLines & vbCrLf & strNewLine

and write the total lines to file at the end in 1 print statement 并在1条打印语句的末尾将总行写入文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM