Thursday, April 25, 2013

Converting Csv to DataTable

Steps:
1. First, by using the File class static method ReadAllLines(path), read all the lines from the csv file  to the string array.
2. In the resulting array, first element contains the column names. using the first line, we should create the Data table columns.
3. Other than the first element, all other elements contains the row's data. Using the same we can create the data table rows.

using System;
using System.Text;
using System.Data;
using System.IO;
namespace ReadData
{
class DataConvert
{
static void Main(string[] args)
{
CsvToDataTable obj = new CsvToDataTable();
DataTable dtData = obj.ConvertCsvToDataTable(@"D:\student.csv");
obj.ShowData(dtData);
}
class CsvToDataTable
{
public DataTable ConvertCsvToDataTable(string filePath)
{
//reading all the lines(rows) from the file.
string[] rows = File.ReadAllLines(filePath);
DataTable dtData = new DataTable();
string[] rowValues = null;
DataRow dr = dtData.NewRow();
//Creating columns
if (rows.Length > 0)
{
foreach (string columnName in rows[0].Split(','))
dtData.Columns.Add(columnName);
}
//Creating row for each line.(except the first line, which contain column names)
for (int row = 1; row < rows.Length; row++)
{
rowValues = rows[row].Split(',');
dr = dtData.NewRow();
dr.ItemArray = rowValues;
dtData.Rows.Add(dr);
}
return dtData;
}
public void ShowData(DataTable dtData)
{
if (dtData != null && dtData.Rows.Count > 0)
{
foreach (DataColumn dc in dtData.Columns)
{
Console.Write(dc.ColumnName + " ");
}
Console.WriteLine("\n-----------------------------------------------");
foreach (DataRow dr in dtData.Rows)
{
foreach (var item in dr.ItemArray)
{
Console.Write(item.ToString() + " ");
}
Console.Write("\n");
}
Console.ReadKey();
}
}
}
}
}
view raw CsvToDataTable hosted with ❤ by GitHub
Output

Creating Csv file from DataTable in C#

Steps:
1. Create a DataTable Schema.
2. Fill the created table with some sample data.
3. Create a StringBuilder, by appending all the data, (using comma delimiter)
    a) Create one new line with data table columns.
    b) Create one line for each data table row.
4. Save the StringBuilder to Csv file, using FileStream.

using System;
using System.Text;
using System.Data;
using System.IO;
namespace Conversion
{
class DataConvert
{
static void Main(string[] args)
{
//converting DataTable to Csv file.
DataTableToCsv obj = new DataTableToCsv();
DataTable dtData = obj.CreateStudentTableSchema();
dtData = obj.FillData(dtData);
StringBuilder data = obj.ConvertDataTableToCsvFile(dtData);
obj.SaveData(data, @"D:\\student.csv");
Console.WriteLine("Data converted successfully from DataTable to Csv file.");
Console.ReadLine();
}
}
class DataTableToCsv
{
//This method creates the DataTable schema (column names and their types).
public DataTable CreateStudentTableSchema()
{
DataTable dtData = new DataTable("Student");
dtData.Columns.Add("StudentId", typeof(int));
dtData.Columns.Add("Name", typeof(string));
dtData.Columns.Add("Course", typeof(string));
dtData.Columns.Add("Age", typeof(int));
return dtData;
}
//This method fill the data table with some sample records.
public DataTable FillData(DataTable dtData)
{
dtData.Rows.Add(1, "Bala", "MCA", 26);
dtData.Rows.Add(2, "Murali", "BCA", 23);
dtData.Rows.Add(3, "Venu", "BSC", 23);
dtData.Rows.Add(4, "Srinivas", "BBM", 22);
dtData.Rows.Add(5, "Srikanth", "MBA", 25);
dtData.Rows.Add(6, "Harsha", "MCA", 26);
return dtData;
}
//This method convertrs the DataTable to Csv (in the form of StringBuilder instance).
public StringBuilder ConvertDataTableToCsvFile(DataTable dtData)
{
StringBuilder data = new StringBuilder();
//Taking the column names.
for (int column = 0; column < dtData.Columns.Count; column++)
{
//Making sure that end of the line, shoould not have comma delimiter.
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";"));
else
data.Append(dtData.Columns[column].ColumnName.ToString().Replace(",", ";") + ',');
}
data.Append(Environment.NewLine);//New line after appending columns.
for (int row = 0; row < dtData.Rows.Count; row++)
{
for (int column = 0; column < dtData.Columns.Count; column++)
{
////Making sure that end of the line, shoould not have comma delimiter.
if (column == dtData.Columns.Count - 1)
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";"));
else
data.Append(dtData.Rows[row][column].ToString().Replace(",", ";") + ',');
}
//Making sure that end of the file, should not have a new line.
if (row != dtData.Rows.Count - 1)
data.Append(Environment.NewLine);
}
return data;
}
//This method saves the data to the csv file.
public void SaveData(StringBuilder data, string filePath)
{
using (StreamWriter objWriter = new StreamWriter(filePath))
{
objWriter.WriteLine(data);
}
}
}
}
view raw DataTableToCsv hosted with ❤ by GitHub

Friday, April 19, 2013

Excel Load To DataTable using OleDb in C#

Here we will try to load Excel sheet  data into the datatable using Jet engine.
First, We need to  Download and install the AccessDatabaseEngine exe from the microsoft web site.

Complete Source Code.
using System;
using System.Data;
using System.Data.OleDb;
namespace ExcelToDataTable
{
class LoadExcel
{
static void Main(string[] args)
{
LoadExcel objExcel = new LoadExcel();
DataTable dtExcelRecords = objExcel.GetDataTableFromExcel(@"D:\StudentRecords.xls");
if (dtExcelRecords != null && dtExcelRecords.Rows.Count > 0)
{
foreach (DataColumn dc in dtExcelRecords.Columns)
{
Console.Write(dc.Caption + " ");
}
Console.WriteLine("\n-----------------------------------------------");
foreach (DataRow dr in dtExcelRecords.Rows)
{
foreach (var item in dr.ItemArray)
{
Console.Write(item.ToString() + " ");
}
Console.Write("\n");
}
Console.ReadKey();
}
}
public DataTable GetDataTableFromExcel(string filePath)
{
string connectionString = string.Empty;
string[] arFile = filePath.Split('.');
string fileExtension = arFile[1];
if (fileExtension.ToLower() == "xls")
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
else if (fileExtension.ToLower() == "xlsx")
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
OleDbConnection objOleDbConnection = new OleDbConnection(connectionString);
OleDbCommand objOleDbCommand = new OleDbCommand();
try
{
objOleDbCommand.CommandType = System.Data.CommandType.Text;
objOleDbCommand.Connection = objOleDbConnection;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(objOleDbCommand);
DataTable dtExcelRecords = new DataTable();
objOleDbConnection.Open();
DataTable dtExcelSheetName = objOleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
objOleDbCommand.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = objOleDbCommand;
dAdapter.Fill(dtExcelRecords);
return dtExcelRecords;
}
catch (Exception ex)
{
throw ex;
}
finally
{
objOleDbConnection.Close();
objOleDbConnection.Dispose();
}
}
}
}

Thursday, April 18, 2013

Program to Add two 50 digit numbers in C#

using System;
namespace BigNumberAddition
{
class Addition
{
static void Main(string[] args)
{
int[] firstNumber = new int[50] {
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5
};
int[] secondNumber = new int[50] {
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5, 6, 7, 8, 9,
1, 2, 3, 4, 5
};
int[] resultNumber = new int[50];
int temp = 0;
for (int i = firstNumber.Length - 1; i >= 0; i--)
{
resultNumber[i] = firstNumber[i] + secondNumber[i] + temp;
if (resultNumber[i] > 9 && i != 0)
{
temp = Convert.ToInt32(resultNumber[i].ToString().Substring(0, resultNumber[i].ToString().Length - 1));
resultNumber[i] = Convert.ToInt32(resultNumber[i].ToString().Remove(0, resultNumber[i].ToString().Length - 1));
}
else
temp = 0;
}
Console.WriteLine("First " + firstNumber.Length + " digits number: ");
foreach (int i in firstNumber)
Console.Write(i);
Console.WriteLine("\n\nSecond " + secondNumber.Length + " digits number: ");
foreach (int i in secondNumber)
Console.Write(i);
Console.WriteLine("\n\nResultant number after addition: ");
foreach (int i in resultNumber)
Console.Write(i);
Console.ReadKey();
}
}
}
Output is: