|
-
Sep 21st, 2010, 12:14 AM
#1
Thread Starter
New Member
[RESOLVED] Read text file and sum a column of data
Hi,
I am new to the forum and would like some guidance on how I can achieve the following.
I would like to read data from a text file after which I want to do a simple calculation that totals one of the columns.
I have already been able to read the text file into a text box but firstly I'm not quite sure if this method of using the text box is appropriate and secondly how do I sum a column of data?
Thank you in advance,
suprsnipes
-
Sep 21st, 2010, 12:48 AM
#2
Re: Read text file and sum a column of data
You can connect to CSV files the same way you connect to a database and use SQL queries on them.
If this isn't appropriate for you, your task is to read the contents of a file (use IO.StreamReader class), then split each line into tokens using String.Split method or Split function thus isolating the needed data column in it, parse the value using TryParse method to convert string tokens into numeric values, then add them up.
Manual reading (reading C:\somefile.txt and adding up the third column of integer values with comma character as a column separator):
vb Code:
Sub ReadCSV()
Dim filecontents As String() = IO.File.ReadAllLines("c:\somefile.txt")
Dim Sum As Integer = 0 ' This holds the sum
For Each line In filecontents
' Using comma ',' as a separator (you may use other characters)
Dim tokens() As String = line.Split(New Char() {","c})
Dim value As Integer = 0 ' This holds the current value
' Let's suppose you need to add up a third column of integer values:
If tokens.Length >= 2 Then
' Parsing the third column and if successful add it to the sum:
If Integer.TryParse(tokens(2), value) Then
Sum += value
End If
End If
Next
MsgBox(Sum)
End Sub
Last edited by cicatrix; Sep 21st, 2010 at 12:58 AM.
-
Oct 17th, 2014, 08:09 AM
#3
New Member
Re: Read text file and sum a column of data
Last edited by Swati123; Oct 17th, 2014 at 08:58 AM.
Reason: I corrected my answer,i found my answer
-
Oct 17th, 2014, 08:21 AM
#4
Re: [RESOLVED] Read text file and sum a column of data
Hi,
Welcome to the Forum but please do not post to an old thread to ask your own question even though you may have used that thread to try and answer your question. At least you looked first before asking.
So, please create a new thread to ask your question and just as a hint, if you compare the data types of “Sum” and “value” you will have your answer. This also implies that you have Option Strict turned Off, so turn it ON now and it will help you to eradicate these types of issues in the future.
Hope that helps.
Cheers,
Ian
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|