2010-11-10 45 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 

玩得开心!