2010-11-10 27 views
0
重新設置輸出到CSV

我是新來VB.Net 2008年我一定要解決,它是從regading長串到控制檯提取字符的任務,提取的文本將被重新格式化並保存爲CSV文件。該字符串來自數據庫。提取的字符,並通過使用關鍵字VB.net

它看起來是這樣的:UNH+RAM6957+ORDERS:D:96A:UN:EGC103'BGM+38G::ZEW+REQEST6957+9'DTM+Z05:0:805'DTM+137:20100930154

值由'分隔。

我可以查詢數據庫並在控制檯上顯示字符串,但現在我需要提取 關鍵字'ORDERS'例如,可以說它跟在5個字符之後。所以輸出應該是這樣的:ORDERS:D:96A然後我需要提取的關鍵字'BGM'及其以下五個字符,所以輸出應該是這樣的:BGM+38G:

提取所有關鍵字後,結果應該用逗號分隔,看起來像:

ORDERS:D:96A,BGM+38G:應當文件自動保存到CSV。

我已經試過:

'Lookup for containing KeyWords 
        Dim FoundPosition1 = p_EDI.Contains("ORDERS") 
        Console.WriteLine(FoundPosition1) 

這給關鍵字的起始位置。

我試圖修剪關鍵字「DTM」,圍繞整個事情。 EDI變量包含數據庫中的整個字符串:

Dim FoundPosition2 = EDI 
        FoundPosition2 = Trim(Mid(EDI, InStr(EDI, "DTM"))) 
        Console.WriteLine(FoundPosition2) 

有人可以幫忙嗎? 提前謝謝!

回答

1

爲了說明所涉及的步驟:

' Find the position where ORDERS is in the string.' 
Dim foundPosition = EDI.IndexOf("ORDERS") 
' Start at that position and extract ORDERS + 5 characters = 11 characters in total.' 
Dim ordersData = EDI.SubString(foundPosition, 11) 

' Find the position where BGM is in the string.' 
Dim foundPosition2 = EDI.IndexOf("BGM") 
' Start at that position and extract BGM + 5 characters = 8 characters in total.' 
Dim bgmData = EDI.SubString(foundPosition2, 8) 

' Construct the CVS data.' 
Dim cvsData = ordersData & "," & bgmData 
+0

你好Egrunin和桑蒂,非常感謝你對你的想法。這非常有幫助。我非常喜歡Santi的簡單方法。謝謝!祝你今天愉快。 – Tom 2010-11-11 11:03:25

1

我沒有我的IDE這裏,但像這樣將工作:

dim EDI as string = "UNH+RAM6957+ORDERS:D:96A:UN:EGC103'BGM+38G::ZEW+REQEST6957+9'DTM+Z05:0:805'DTM+137:20100930154" 

dim result as string = KeywordPlus(EDI, "ORDER", 5) + "," _ 
    + KeywordPlus(EDI, "BGM", 5) 

function KeywordPlus(s as string, keyword as string, length as integer) as string 
    dim index as integer = s.IndexOf(keyword) 
    if index = -1 then return "" 
    return s.substring(index, keyword.length + length) 
end function 
0

爲我們之間的interrested的人,我已經把將代碼放在一起,並創建了一個CSV文件,其中包含 。也許它可以幫助別人...

    If EDI.Contains("LOC") Then 
        Dim foundPosition1 = EDI.IndexOf("LOC") 
        ' Start at that position and extract ORDERS + 5 characters = 11 characters in total.' 
        Dim locData = EDI.Substring(foundPosition1, 11) 
        'Console.WriteLine(locData) 

        Dim FoundPosition2 = EDI.IndexOf("QTY") 
        Dim qtyData = EDI.Substring(FoundPosition2, 11) 
        'Console.WriteLine(qtyData) 

        ' Construct the CSV data. 
        Dim csvData = locData & "," & qtyData 
        'Console.WriteLine(csvData) 

        ' Creating the CSV File. 
        Dim csvFile As String = My.Application.Info.DirectoryPath & "\Test.csv" 
        Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True) 

        outFile.WriteLine(csvData) 
        outFile.Close() 
        Console.WriteLine(My.Computer.FileSystem.ReadAllText(csvFile)) 
       End IF 

玩得開心!