!!如何对从txt文件读取的数据进行计算?急……
现在有如附件中两个文件所以的文本文件,现在要把里面的数据读取出来然后进行计算,并将计算结果保存到一个新的txt文件中,弄不下去了,请多帮忙。
文件中第一列为代号,第二列为年分,第三列为月分,第四列开始为每月逐日的数据记录(共31列数据,遇2月或平月时后面用32744补齐),文件中各数据连同其后的空格占八位。
现在要把里面的逐日数据读取出来,然后进行计算,举例来说对逐日对应数据进行加法运算,然后将得到的结果保存到一个新的txt文件中,读取我会了,但如何将读取的数据计算还是弄不明白。
我用的以下方法来读数据:
Sub DataGet1(ByVal Folder As String) 'folder 为aaa和bbb的路径
Using Reader1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(Folder)
Reader1.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
Reader1.SetFieldWidths(9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, -1)
Dim CurrentRow As String()
Dim Temp(34) As String
Dim k As Integer = 0
While Not Reader1.EndOfData
CurrentRow = Reader1.ReadFields()
Dim currentField As String
For Each currentField In CurrentRow
If k <= 2 Or currentField = 32766 Or currentField = 32744 Then
Temp(k) = CInt(currentField)
Else
Temp(k) = CInt(currentField) / 10
End If
k = k + 1
Next
k = 0
End While
End Using
End Sub
现在就是如何将读取的数据进行运算了,请大家多多帮忙吧,另外以上代码有什么不妥之初也请指出。
急切等待中……
[解决办法]
- VB.NET code
Sub DataGet1(ByVal srcFile1 As String, ByVal srcFile2 As String, ByVal destFile As String) Dim Reader1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(srcFile1) Reader1.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth Reader1.SetFieldWidths(9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, -1) Dim Reader2 As New Microsoft.VisualBasic.FileIO.TextFieldParser(srcFile2) Reader2.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth Reader2.SetFieldWidths(9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, -1) 'Dim strResult As String = "" Dim sb As New System.Text.StringBuilder() Dim iSum As Integer Dim k As Integer While Not Reader1.EndOfData AndAlso Not Reader2.EndOfData iSum = 0 k = 0 Dim s1() As String = Reader1.ReadFields() Dim s2() As String = Reader2.ReadFields() For index As Integer = 0 To s1.Length - 1 If index <= 2 Then 'strResult &= s1(index).PadRight(8, " ") sb.Append(s1(index).PadRight(8, " ")) Else Dim i1, i2 As Integer i1 = CInt(s1(index)) i2 = CInt(s2(index)) If i1 <> 32744 Then 'strResult &= (i1 + i2).ToString().PadRight(8, " ") 'strResult &= String.Format("{0}+{1}={2}{3}", i1, i2, i1 + i2, ControlChars.Tab) sb.Append((i1 + i2).ToString().PadRight(8, " ")) Else 'strResult &= "*" & ControlChars.Tab sb.Append("*".PadRight(8, " ")) End If End If Next 'strResult &= ControlChars.NewLine sb.AppendLine() End While Dim fs As New System.IO.FileStream(destFile, IO.FileMode.OpenOrCreate, IO.FileAccess.Write) 'fs.Write(System.Text.Encoding.Default.GetBytes(strResult), 0, strResult.Length) fs.Write(System.Text.Encoding.Default.GetBytes(sb.ToString()), 0, sb.Length) fs.Close() End Sub