Reading Data from CSV to Screen Output

Reading Data from CSV to Screen output

Code below displays results in a DataGridView

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

const string FILENAME = @"c:\temp\test.csv";
private void button1_Click(object sender, EventArgs e)
{
CSVReader csvReader = new CSVReader();
DataSet ds = csvReader.ReadCSVFile(FILENAME, true);
dataGridView1.DataSource = ds.Tables["Table1"];
}
}
public class CSVReader
{

public DataSet ReadCSVFile(string fullPath, bool headerRow)
{

string path = fullPath.Substring(0, fullPath.LastIndexOf("\\") + 1);
string filename = fullPath.Substring(fullPath.LastIndexOf("\\") + 1);
DataSet ds = new DataSet();

try
{
if (File.Exists(fullPath))
{
string ConStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=\"Text;HDR={1};FMT=Delimited\\\"", path, headerRow ? "Yes" : "No");
string SQL = string.Format("SELECT * FROM {0}", filename);
OleDbDataAdapter adapter = new OleDbDataAdapter(SQL, ConStr);
adapter.Fill(ds, "TextFile");
ds.Tables[0].TableName = "Table1";
}
foreach (DataColumn col in ds.Tables["Table1"].Columns)
{
col.ColumnName = col.ColumnName.Replace(" ", "_");
}
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return ds;
}
}
}


how to read the output of csv file and print the output in php

fgetcsv returns an array with each field in it. You can use the list function to get all columns in that array:

while($csv_line = fgetcsv($csv,1024)) {
list($column1, $column2, $column3) = $csv_line;
}

How to extract and display specific rows from CSV file in java?

CSV files are just comma separated files. So you can read the csv file like any other file using the Reader class and then use the split function to seperate the columns.

First, you can read the file and store it in 2-D string array. And then filter the records according to the user input.

Read lines of data from CSV then display data

using System.IO;

static void Main(string[] args)
{
using(var reader = new StreamReader(@"C:\test.csv"))
{
List<string> listA = new List<string>();
List<string> listB = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(';');

listA.Add(values[0]);
listB.Add(values[1]);
}
}
}

https://www.rfc-editor.org/rfc/rfc4180

or

using Microsoft.VisualBasic.FileIO;

var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;

// Skip the row with the column names
csvParser.ReadLine();

while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields();
string Name = fields[0];
string Address = fields[1];
}
}

http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html

or

LINQ way:

var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
select (from piece in line
select piece);

^^Wrong - Edit by Nick

It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

var csv = from line in lines
select (line.Split(',')).ToArray();

This question was fully addressed here:

Reading CSV file and storing values into an array

How To Read and Print Data from CSV file into HTML File as Text

The usual approach is to use Python's built in CSV reader to correctly parse each row into a list of values. The can be done as follows:

import csv

with open('input.csv') as f_input, open('output.html', 'w') as f_output:
csv_input = csv.reader(f_input)
header = next(csv_input) # skip the header

# Write the HTML header
f_output.write("<html>\n<body>\n")

for row in csv_input:
f_output.write(f"Current age of Mr. {row[0]} is {row[1]} Years.<br>\n")

# Write the HTML footer
f_output.write("</body>\n</html>\n")

For your sample CSV data, this would produce the following HTML output:

<html>
<body>
Current age of Mr. abc is 20 Years.<br>
Current age of Mr. xyz is 30 Years.<br>
Current age of Mr. jkl is 40 Years.<br>
</body>
</html>

To create one HTML per row, you would need to rearrange things a bit and also decide on a naming scheme for the output files. This adds the name to each filename:

import csv

with open('input.csv', encoding='utf-8') as f_input:
csv_input = csv.reader(f_input)
header = next(csv_input) # skip the header

for row in csv_input:
with open(f'output_{row[0]}.html', 'w', encoding='utf-8') as f_output:
# Write the HTML header
f_output.write("<html>\n<body>\n")

f_output.write(f"Current age of Mr. {row[0]} is {row[1]} Years.<br>\n")

# Write the HTML footer
f_output.write("</body>\n</html>\n")

An alternative approach would be to parse each line yourself, this could be done as follows:

with open('input.csv') as f_input, open('output.html', 'w') as f_output:
header = next(f_input) # skip the header

# Write the HTML header
f_output.write("<html>\n<body>\n")

for line in f_input:
row = line.strip().split(',')
f_output.write(f"Current age of Mr. {row[0]} is {row[1]} Years.<br>\n")

# Write the HTML footer
f_output.write("</body>\n</html>\n")

This though would not work if your single name column contained commas. e.g. "John, Smith" (which is valid in CSV files, the quotes are used to ignore the commas inside)

Trying to read in a CSV file and print to console c++

I know that my file is opening because I had included a conditional statement, however, when it comes to reading the data rather than getting any actual information I am just getting blank lines.

You never initialize the line variable anywhere inside your code so lineSS is initialized with an empty buffer.

Consequently, reading a stream with an empty buffer using std::getline() will give you an empty string, which is what you are facing.

To fix this, either put std::getline(fin, line); at the beginning of your second loop:

// ...

if (fin.is_open()) {

for (int i = 0; i < 10; i ++) {
getline(fin, line); // Reads each line from the file into the 'line' variable

string Sentiment, id, Date, Query, User, Tweet;
stringstream lineSS(line);

getline(lineSS, Sentiment, ',');
getline(lineSS, id, ',');
getline(lineSS, Date, ',');
getline(lineSS, Query, ',');
getline(lineSS, User, ',');
getline(lineSS, Tweet, '\n');

cout << Sentiment << endl;
cout << id << endl;
cout << Tweet << endl;

}

fin.close();
}

// ...

Or just use the file stream directly without having to use a std::stringstream for mediation:

// ...

if (fin.is_open()) {

for (int i = 0; i < 10; i ++) {
string Sentiment, id, Date, Query, User, Tweet;

getline(fin, Sentiment, ',');
getline(fin, id, ',');
getline(fin, Date, ',');
getline(fin, Query, ',');
getline(fin, User, ',');
getline(fin, Tweet, '\n');

cout << Sentiment << endl;
cout << id << endl;
cout << Tweet << endl;

}

fin.close();
}

// ...

Reading from csv file in C causing input to not print

Since your file contains only two columns, you can write it this way using sscanf():

#include <stdio.h>
#include <string.h>

int main()
{
FILE *fp = fopen("file", "r");
if (!fp) {
fprintf(stderr, "Can't open file\n");
return 1;
}

char line[1024];
int x, y;
while (fgets(line, sizeof line, fp)) {
line[strcspn(line, "\n")] = '\0'; // Replace '\n' read by fgets() by '\0'

if (sscanf(line, "%d, %d", &x, &y) != 2) {
fprintf(stderr, "Bad line\n");
}

printf("x:%d\ty:%d\n", x, y);
}

fclose(fp);
}

Reading a specific CSV row and display in output box

So you just want to read out the csv like:

import csv

var number = 100

with open('names.csv') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
var x = row['order']
if x == number:
print("We have a Match")

You need to asign the number you get from the input to the var number



Related Topics



Leave a reply



Submit