如何将标题行插入csv文件

时间:2011-06-02 15:18:21

标签: .net vb.net

我有一个.csv文件,其中包含数据但不包含列标题。我可以用oldcsv文件的内容创建新的.csv文件。但我需要在第一行和第二行添加列标题,现有数据应该出现。

这是我写的代码:

 Dim ioFile As New System.IO.StreamReader("C:\sample.csv")      
 Dim ioLine As String      Dim ioLines As String      
 ioLine = ioFile.ReadLine     
 ioLines = ioLine     
 While Not ioLine = ""         
    ioLine = ioFile.ReadLine         
    ioLines = ioLines & vbCrLf & ioLine      
 End While     
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")     
 ioWriter.WriteLine(ioLines)     
 ioFile.Close()     
 ioWriter.Close() 

现在我需要在new.csv中添加列标题为“ID”,“Name”,“Number”,“Amount”

4 个答案:

答案 0 :(得分:3)

为了好玩,我发布了这个“oneliner”,但请记住,最短的是总是最好的。 (首先导入system.io.file):

Imports system.io.file

然后将此行放在要修复文件的位置:

WriteAllText("c:\new.csv", """ID"",""Name"",""Number"",""Amount""" & vbCrLf & ReadAllText("c:\old.csv"))

答案 1 :(得分:1)

您可以将Reader and Writer设置为在循环内读写,避免创建oiLines构造。

Dim reader as New StreamReader(inputFileName)
Dim writer as New StreamWriter(outputFileName)
Dim line as String

'Do you have a definition of what has to be added here?
writer.WriteLine(headerLine)

While (Nothing <> (line = reader.ReadLine()))
  writer.WriteLine(line)
End While

reader.Dispose()
writer.Dispose()

检查代码,因为我盲目地写了。我更喜欢C#,但这个想法很合理。您只需要提供inputFileName,outputFileName和headerLine。这也允许将其放在一个可重复使用的方法中。 : - )

答案 2 :(得分:0)

试试这个:

Dim ioFile As New System.IO.StreamReader("C:\sample.csv")      
 Dim ioLine As String      Dim ioLines As String      
 ioLine = ioFile.ReadLine     
 ioLines = """ID"",""Name"",""Number"",""Amount"""
 ioLines &= vbCrLf & ioLine 
 While Not ioLine = ""         
    ioLine = ioFile.ReadLine         
    ioLines = ioLines & vbCrLf & ioLine      
 End While     
 Dim ioWriter As New System.IO.StreamWriter("C:\new.csv")     
 ioWriter.WriteLine(ioLines)     
 ioFile.Close()     
 ioWriter.Close() 

答案 3 :(得分:0)

    Using ioFile As New System.IO.StreamReader("C:\sample.csv"), ioWriter As New System.IO.StreamWriter("C:\new.csv")

        ioWriter.WriteLine("ID,Name,Number,Amount")

        Do Until ioFile.Peek = -1

            ioWriter.WriteLine(ioFile.ReadLine)

        Loop

        ioFile.Close()
        ioWriter.Close()

    End Using