2016-10-27 23 views
0

如何使用VB.NET代碼在第一行生成.csv頭?下面是我嘗試過的代碼,但它寫在.csv文件的頂部和列上。如何僅在第一行生成.csv頭?

Try 
    My.Computer.FileSystem.WriteAllText("C:\bin\Debug\TimerTest.csv", 
     "Date and Time,Tag Name, Value" & vbCrLf & 
     timeUtc & "," & Tag_name_Read & "," & itemValues(0).Value.ToString, True) 
    'Date and Time, Tag Name, Value are my header. they are suppose to be on the first line 

Catch ex As Exception 
End Try 

If daServerMgt.IsConnected Then 
    daServerMgt.Disconnect() 
End If 

Update Link Showing the csv file)

我只想頭(日期和時間|標籤名稱|值)之上,我不希望它在列。它是由於My.Computer.FileSystem.WriteAllText(文件,文本,真)而附加它

如何解決此問題?

+0

我不認爲你做的是真正的寫csv文件。爲什麼不使用一些既定的代碼,如** lumenworks ** csv庫? –

+0

雖然這似乎應該起作用。 @ Smoky2016,請您更新您的問題,以便在代碼運行後向我們顯示CSV文件的確切內容? – MJH

+0

請不要做'趕上例外' - 這是不好的。如果您正在捕獲可以從中恢復的特定異常,則只能將代碼放在'Try' /'Catch'中。 – Enigmativity

回答

0

我只是通過在Run_Click子文件中添加標題的文本來找到解決方案。反過來,它會將文本附加到現有文件並將其放在第一行(標題行)上,每次運行事件時都會如此。這行得通!

下面是我使用的代碼:

Private Sub Run_Click(sender As Object, e As EventArgs) Handles Run.Click 
    Dim Path As String = "C:\bin\Debug\TimerTest.csv" 

    My.Computer.FileSystem.WriteAllText(Path, "Date and Time, Tag Name, Value", False) 'add 
    Timer1.Enabled = True 
End Sub 
0

除了提到的一個@Enigmativity之類的問題之外,您的代碼似乎沒有任何問題。

我的舊機墜毀最近,我還沒有我的新機器上安裝了Visual Studio,但我創造了我的C:\Temp文件夾中一個名爲TimerTest.vb,具有以下內容:

Imports System 

Module Module1 
    Public Structure Struct1 
     Public Value As Integer 
     Sub New(ByVal _Value As Integer) 
      Value = _Value 
     End Sub 
    End Structure 

    Sub Main() 
     Dim timeUtc As DateTime = DateTime.Now() 
     Dim Tag_name_Read As String = "FortyTwo" 
     Dim itemValues = New Struct1() { New Struct1(42), New Struct1(43), New Struct1(44)} 

     Try 
      'My.Computer.FileSystem.WriteAllText("C:\bin\Debug\TimerTest.csv", 
      My.Computer.FileSystem.WriteAllText("C:\Temp\TimerTest.csv", 
       "Date and Time,Tag Name, Value" & vbCrLf & 
       timeUtc & "," & Tag_name_Read & "," & itemValues(0).Value.ToString, True) 
      'Date and Time, Tag Name, Value are my header. they are suppose to be on the first line 

     Catch ex As Exception 
     End Try 

     'If daServerMgt.IsConnected Then 
     ' daServerMgt.Disconnect() 
     'End If 
    End Sub 
End Module 


我然後在命令窗口中運行下面的語句編譯(vbc.exe的父文件夾已經在我的%PATH%):

vbc C:\Temp\TimerTest.vb 


後,我跑了導致TimerTest.exe文件,在C:\Temp生成一個TimerTest.csv文件,其內容如下:

Date and Time,Tag Name, Value<br> 
10/27/2016 9:07:31 PM,FortyTwo,42 


當我雙擊TimerTest.csv文件,它在Excel中打開沒有任何問題:

enter image description here


因此,親blem必須在代碼中的其他地方。爲了讓我們更容易地爲您提供幫助,請提供一個Minimal, Complete, and Verifiable example來重現此問題。