I can upload a csv file directly, I am now looking unto how to display it in a data table in the view.
I have written the code but it is not displaying the data table.
Below is my code for better understanding:
[HttpPost]
public ActionResult Index(HttpPostedFileBase FileUpload)
{
// Set up DataTable place holder
DataTable dt = new DataTable();
//check we have a file
if (FileUpload.ContentLength > 0)
{
//Workout our file path
string fileName = Path.GetFileName(FileUpload.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
//Try and upload
try
{
FileUpload.SaveAs(path);
//Process the CSV file and capture the results to our DataTable place holder
dt = ProcessCSV(path);
}
catch (Exception ex)
{
//Catch errors
ViewData["Feedback"] = ex.Message;
}
}
else
{
//Catch errors
ViewData["Feedback"] = "Please select a file";
}
return View("Index", ViewData["Feedback"]);
}
private static DataTable ProcessCSV(string fileName)
{
//Set up our variables
string Feedback = string.Empty;
string line = string.Empty;
string[] strArray;
DataTable dt = new DataTable();
DataRow row;
// work out where we should split on comma, but not in a sentence
Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
//Set the filename in to our stream
StreamReader sr = new StreamReader(fileName);
//Read the first line and split the string at , with our regular expression in to an array
line = sr.ReadLine();
strArray = r.Split(line);
//For each item in the new split array, dynamically builds our Data columns. Save us having to worry about it.
Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));
//Read each line in the CVS file until it’s empty
while ((line = sr.ReadLine()) != null)
{
row = dt.NewRow();
//add our current value to our data row
row.ItemArray = r.Split(line);
dt.Rows.Add(row);
}
//Tidy Streameader up
sr.Dispose();
//return a the new DataTable
return dt;
}
public static DataTable csvToDataTable(string file, bool isRowOneHeader)
{
DataTable csvDataTable = new DataTable();
//no try/catch - add these in yourselfs or let exception happen
String[] csvData = File.ReadAllLines(HttpContext.Current.Server.MapPath(file));
//if no data in file ‘manually’ throw an exception
if (csvData.Length == 0)
{
throw new Exception("CSV File Appears to be Empty");
}
String[] headings = csvData[0].Split(',');
int index = 0; //will be zero or one depending on isRowOneHeader
if (isRowOneHeader) //if first record lists headers
{
index = 1; //so we won’t take headings as data
//for each heading
for (int i = 0; i < headings.Length; i++)
{
//replace spaces with underscores for column names
headings[i] = headings[i].Replace(" ", "_");
//add a column for each heading
csvDataTable.Columns.Add(headings[i], typeof (string));
}
}
else //if no headers just go for col1, col2 etc.
{
for (int i = 0; i < headings.Length; i++)
{
//create arbitary column names
csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof (string));
}
}
//populate the DataTable
for (int i = index; i < csvData.Length; i++)
{
//create new rows
DataRow row = csvDataTable.NewRow();
for (int j = 0; j < headings.Length; j++)
{
//fill them
row[j] = csvData[i].Split(',')[j];
}
//add rows to over DataTable
csvDataTable.Rows.Add(row);
}
//return the CSV DataTable
return csvDataTable;
}
Sorry my mistake. I Didn't notice that you are looking for mvc
Try following example
[HttpPost]
public ActionResult Index(HttpPostedFileBase fileUpload)
{
// Set up DataTable place holder
DataTable dt = new DataTable();
//check we have a file
if (fileUpload.ContentLength > 0)
{
//Workout our file path
string fileName = Path.GetFileName(fileUpload.FileName);
string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
//Try and upload
try
{
fileUpload.SaveAs(path);
//Process the CSV file and capture the results to our DataTable place holder
dt = csvToDataTable(path,false);
}
catch (Exception ex)
{
//Catch errors
ViewData["Feedback"] = ex.Message;
}
}
else
{
//Catch errors
ViewData["Feedback"] = "Please select a file";
}
return View("Index", ViewData["Feedback"]);
}
public DataTable csvToDataTable(string file, bool isRowOneHeader)
{
DataTable csvDataTable = new DataTable();
//no try/catch - add these in yourselfs or let exception happen
String[] csvData = System.IO.File.ReadAllLines(file);
//if no data in file ‘manually’ throw an exception
if (csvData.Length == 0)
{
throw new Exception("CSV File Appears to be Empty");
}
String[] headings = csvData[0].Split(',');
int index = 0; //will be zero or one depending on isRowOneHeader
if (isRowOneHeader) //if first record lists headers
{
index = 1; //so we won’t take headings as data
//for each heading
for (int i = 0; i < headings.Length; i++)
{
//replace spaces with underscores for column names
headings[i] = headings[i].Replace(" ", "_");
//add a column for each heading
csvDataTable.Columns.Add(headings[i], typeof(string));
}
}
else //if no headers just go for col1, col2 etc.
{
for (int i = 0; i < headings.Length; i++)
{
//create arbitary column names
csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string));
}
}
//populate the DataTable
for (int i = index; i < csvData.Length; i++)
{
//create new rows
DataRow row = csvDataTable.NewRow();
for (int j = 0; j < headings.Length; j++)
{
//fill them
row[j] = csvData[i].Split(',')[j];
}
//add rows to over DataTable
csvDataTable.Rows.Add(row);
}
//return the CSV DataTable
return csvDataTable;
}
ayodejib
Member
5 Points
57 Posts
How to Display CSV file Data in a Data Table
Jun 22, 2012 11:44 AM|LINK
I can upload a csv file directly, I am now looking unto how to display it in a data table in the view.
I have written the code but it is not displaying the data table.
Below is my code for better understanding:
[HttpPost] public ActionResult Index(HttpPostedFileBase FileUpload) { // Set up DataTable place holder DataTable dt = new DataTable(); //check we have a file if (FileUpload.ContentLength > 0) { //Workout our file path string fileName = Path.GetFileName(FileUpload.FileName); string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); //Try and upload try { FileUpload.SaveAs(path); //Process the CSV file and capture the results to our DataTable place holder dt = ProcessCSV(path); } catch (Exception ex) { //Catch errors ViewData["Feedback"] = ex.Message; } } else { //Catch errors ViewData["Feedback"] = "Please select a file"; } return View("Index", ViewData["Feedback"]); } private static DataTable ProcessCSV(string fileName) { //Set up our variables string Feedback = string.Empty; string line = string.Empty; string[] strArray; DataTable dt = new DataTable(); DataRow row; // work out where we should split on comma, but not in a sentence Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))"); //Set the filename in to our stream StreamReader sr = new StreamReader(fileName); //Read the first line and split the string at , with our regular expression in to an array line = sr.ReadLine(); strArray = r.Split(line); //For each item in the new split array, dynamically builds our Data columns. Save us having to worry about it. Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn())); //Read each line in the CVS file until it’s empty while ((line = sr.ReadLine()) != null) { row = dt.NewRow(); //add our current value to our data row row.ItemArray = r.Split(line); dt.Rows.Add(row); } //Tidy Streameader up sr.Dispose(); //return a the new DataTable return dt; }And in the view i have;
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Index</h2> <h2>CSV Bulk Upload</h2> <% using (Html.BeginForm("","Home",FormMethod.Post, new {enctype="multipart/form-data"})){ %> <input type="file" name="FileUpload" /> <input type="submit" name="Submit" id="Submit" value="Upload" /> <%} %> <p><%= Html.Encode(ViewData["dt"]) %></p> </asp:Content>I need people to put me through.
Nasser Malik
Star
11228 Points
1720 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 12:14 PM|LINK
Use this method
public static DataTable csvToDataTable(string file, bool isRowOneHeader) { DataTable csvDataTable = new DataTable(); //no try/catch - add these in yourselfs or let exception happen String[] csvData = File.ReadAllLines(HttpContext.Current.Server.MapPath(file)); //if no data in file ‘manually’ throw an exception if (csvData.Length == 0) { throw new Exception("CSV File Appears to be Empty"); } String[] headings = csvData[0].Split(','); int index = 0; //will be zero or one depending on isRowOneHeader if (isRowOneHeader) //if first record lists headers { index = 1; //so we won’t take headings as data //for each heading for (int i = 0; i < headings.Length; i++) { //replace spaces with underscores for column names headings[i] = headings[i].Replace(" ", "_"); //add a column for each heading csvDataTable.Columns.Add(headings[i], typeof (string)); } } else //if no headers just go for col1, col2 etc. { for (int i = 0; i < headings.Length; i++) { //create arbitary column names csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof (string)); } } //populate the DataTable for (int i = index; i < csvData.Length; i++) { //create new rows DataRow row = csvDataTable.NewRow(); for (int j = 0; j < headings.Length; j++) { //fill them row[j] = csvData[i].Split(',')[j]; } //add rows to over DataTable csvDataTable.Rows.Add(row); } //return the CSV DataTable return csvDataTable; }see
http://www.akamarketing.com/blog/256-csv-datatable.html
Skype: maleknasser1
ayodejib
Member
5 Points
57 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 02:02 PM|LINK
What do i need to append in the view?
ayodejib
Member
5 Points
57 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 02:16 PM|LINK
this line below gives me an error even before running the file:
the File in File.ReadAllLines and the HttpContext gives me error.
Nasser Malik
Star
11228 Points
1720 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 02:58 PM|LINK
use following method instead
Skype: maleknasser1
ayodejib
Member
5 Points
57 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 03:43 PM|LINK
still error.
Nasser Malik
Star
11228 Points
1720 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 04:26 PM|LINK
Sorry my mistake. I Didn't notice that you are looking for mvc
Try following example
[HttpPost] public ActionResult Index(HttpPostedFileBase fileUpload) { // Set up DataTable place holder DataTable dt = new DataTable(); //check we have a file if (fileUpload.ContentLength > 0) { //Workout our file path string fileName = Path.GetFileName(fileUpload.FileName); string path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName); //Try and upload try { fileUpload.SaveAs(path); //Process the CSV file and capture the results to our DataTable place holder dt = csvToDataTable(path,false); } catch (Exception ex) { //Catch errors ViewData["Feedback"] = ex.Message; } } else { //Catch errors ViewData["Feedback"] = "Please select a file"; } return View("Index", ViewData["Feedback"]); } public DataTable csvToDataTable(string file, bool isRowOneHeader) { DataTable csvDataTable = new DataTable(); //no try/catch - add these in yourselfs or let exception happen String[] csvData = System.IO.File.ReadAllLines(file); //if no data in file ‘manually’ throw an exception if (csvData.Length == 0) { throw new Exception("CSV File Appears to be Empty"); } String[] headings = csvData[0].Split(','); int index = 0; //will be zero or one depending on isRowOneHeader if (isRowOneHeader) //if first record lists headers { index = 1; //so we won’t take headings as data //for each heading for (int i = 0; i < headings.Length; i++) { //replace spaces with underscores for column names headings[i] = headings[i].Replace(" ", "_"); //add a column for each heading csvDataTable.Columns.Add(headings[i], typeof(string)); } } else //if no headers just go for col1, col2 etc. { for (int i = 0; i < headings.Length; i++) { //create arbitary column names csvDataTable.Columns.Add("col" + (i + 1).ToString(), typeof(string)); } } //populate the DataTable for (int i = index; i < csvData.Length; i++) { //create new rows DataRow row = csvDataTable.NewRow(); for (int j = 0; j < headings.Length; j++) { //fill them row[j] = csvData[i].Split(',')[j]; } //add rows to over DataTable csvDataTable.Rows.Add(row); } //return the CSV DataTable return csvDataTable; }I tried with
one,two,three,four,five
six,seven,eight,nine,ten
eleven,twelve,thirteen,fourteen,fifteen
data in csv file and it successfully added to datatable.
Skype: maleknasser1
ayodejib
Member
5 Points
57 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 04:52 PM|LINK
It is uploading to the directory but it doesn't show in the data table on the browser, didn't I need to specify anything in my view?
below is my view code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Index </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Index</h2> <h2>CSV Bulk Upload</h2> <% using (Html.BeginForm("","Home",FormMethod.Post, new {enctype="multipart/form-data"})){ %> <input type="file" name="FileUpload" /> <input type="submit" name="Submit" id="Submit" value="Upload" /> <%} %> <p><%= Html.Encode(ViewData["Feedback"]) %></p> </asp:Content>Just to see the data table on the browser. or how/where can I see it? because it's not showing.
Nasser Malik
Star
11228 Points
1720 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 05:15 PM|LINK
I put following text n csv file
one,two,three,four,five
six,seven,eight,nine,ten
eleven,twelve,thirteen,fourteen,fifteen
And this data filled in datatable by using above code.
Did you get any exception ?
I think your number of columns for each isn't same.
If number of column for each record isn't' same then you get an index out of range exception.
Skype: maleknasser1
ayodejib
Member
5 Points
57 Posts
Re: How to Display CSV file Data in a Data Table
Jun 22, 2012 05:34 PM|LINK
It's still the same thing.
I copied the text you gave to me (one, two, three...........) to a notepad and saved it as number.csv
so, when i run the application and it comes out in the browser, the screen i got it the one with the file upload and i browse to get the file.
on click of the submit button, the browser need to just redirects and upload the file. no data table is shown.
or is there any or thing to do again to get the table shown on the browser?