2011-06-02 143 views
1

我有一个.csv文件,其中包含数据但不包含列标题。我可以使用oldcsv文件的内容创建新的.csv文件。但是我需要在第一行添加列标题,第二行应该显示现有的数据。如何将标题行插入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”, “姓名”, “号码”, “金额”

回答

1

您可以设置Reader和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。这也允许把它放在一个可重用的方法中。 :-)

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() 
+0

在行 – Ram 2011-06-02 15:27:15

+0

ioLines = “ID” 抛出一个错误,“名称“,”数量“,”金额“ – Ram 2011-06-02 15:27:20

+0

只需要引号逃脱。 – 2011-06-02 15:28:48

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 
2

只是为了好玩,我发布了这个“oneliner”,但请记住,最短的'allways'是最好的。 (第一进口有System.IO.File):

Imports system.io.file 

然后把这一行,你要修复的文件:

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