import, sort & export a CSV file that has an unknown amount of rows & columns

Post your FreeBASIC source, examples, tips and tricks here. Please don’t post code without including an explanation.
Post Reply
geofs
Posts: 12
Joined: Apr 14, 2020 13:34

import, sort & export a CSV file that has an unknown amount of rows & columns

Post by geofs »

Code: Select all

dim as string temp
dim as integer x, y, z, row, col

'find how many rows & columns are in the csv file to be imported 
row = 1
col = 1
open "data.csv" for input as #1
  line input #1,temp
   for x = 1 to len(temp)
      if mid(temp,x,1) = "," then col = col + 1
    next x
  while not eof(1)
     line input #1,temp
     row = row + 1
  wend
  seek #1, 1

  'import data in csv file into a 2 dimentional array linein(rows,columns)
  dim as string linein(row,col)
  line input #1,temp
  for y = 2 to row
    for x = 1 to col
      input #1, linein(y,x)
     next x
  next y
close #1

'bubble sort csv file by column 1
for z = 1 to row
  for y = 1 to row-1
    if linein(y,1) > linein(y+1,1) then
      for x = 1 to col
        temp = linein(y,x)
        linein(y,x) = linein(y+1,x)
        linein(y+1,x) = temp
      next x   
    end if
  next y
next z

'export a new csv file with selected columns 1, 5, 6 & 9
open "save.csv" for output as #1
  write #1,"Id","Family Name","Given Name","DOB"
  for y = 2 to row
    write #1, linein(y,1),linein(y,5),linein(y,6),linein(y,9)
  next y
close #1
Post Reply