Thursday, November 12, 2009

Read from Excel and write to another Excel SpreadSheet using C# Win Forms






My Team Manager has a requirement of getting Email address of a District Managers in a Spread sheet. Where he gave me First and the Last name of the persons. IN one of our application i can go and enter the name and it returns me the person details. So I can pick email address and past in excel spreadsheet. It's kind of time taking process. Because our app is a huge application and it take long time to get the result. So i decided generate a spread sheet with names and their email address in one button click. Read data from excel and write to excel.

So i created a test.xls and added the entire first and last name in both the columns. And created a win form app where Button click Read Excel and another button click is generate excel with names and email address.

Create a table tblemp with columns EMP_PK, EMP_FNAME, EMP_LNAME, and EMP_EMAIL.

You have to reference the Microsoft.Office.Interop.Excel; in your project reference folder. To use the Excel object in you app. I created a database connection in app config.

Create a connection based on your Database provider User ID Password and Data Source and out in App Settings tag in app.config file.

First Name Last Name
James mic
Rick onion
Mic son
Dave hart
Chris moris
Tom Letter
Mark June
Jim teens
Frank juhi
toly budd
Tom berry

Create a table tblemp with columns EMP_PK,EMP_FNAME,EMP_LNAME,EMP_EMAIL.

ce.Interop.Excel;

namespace GenerateEmailAddress
{
public partial class Form1 : Form
{
System.Data.OleDb.OleDbConnection oledbconn;
OleDbCommand oledbcommand;
DataSet ds = new DataSet();
DataSet ds1 = new DataSet();
DataRow dr;
DataColumn dc;
OleDbDataAdapter oledbreader;
System.Data.DataTable dt = new System.Data.DataTable();

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
try
{
string conn = System.Configuration.ConfigurationSettings.AppSettings["ConnString"];
oledbconn = new System.Data.OleDb.OleDbConnection(conn);
oledbconn.Open();


dc = new DataColumn("EMP_PK");
dt.Columns.Add(dc);
dc = new DataColumn("EMP_EMAIL");
dt.Columns.Add(dc);
}
catch (Exception ex)
{ }
}

private void btnReadExcel_Click(object sender, EventArgs e)
{

// Path for the test excel application
string Path = @"c:\Test.xls";
// Initialize the Excel Application class
ApplicationClass app = new ApplicationClass();
// Create the workbook object by opening the excel file.
Workbook workBook = app.Workbooks.Open(Path,
0,
true,
5,
"",
"",
true,
XlPlatform.xlWindows,
"\t",
false,
false,
0,
true,
1,
0);
// Get the active worksheet using sheet name or active sheet
Worksheet workSheet = (Worksheet)workBook.ActiveSheet;

// This row,column index should be changed as per your need.
// i.e. which cell in the excel you are interesting to read.
int index = 1;
object rowIndex = 1;
object colIndex1 = 1;
object colIndex2 = 2;

try
{
while (((Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
// Read the Cells to get the required value.
string firstName = ((Range)workSheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string lastName = ((Range)workSheet.Cells[rowIndex, colIndex2]).Value2.ToString();
//Console.WriteLine("Name : {0},{1} ", firstName, lastName);
index++;
rowIndex = index;

string strSqlEmail = "Select EMP_PK,EMP_EMAIL from tblemp where EMP_FNAME = upper('" + firstName + "') AND EMP_LNAME = upper('" + lastName + "')) order by EMP_PK asc";

oledbreader = new OleDbDataAdapter(strSqlEmail, oledbconn);
oledbreader.Fill(dt);
//oledbreader = oledbcommand.ExecuteReader();
dr = dt.NewRow();
dr["EMP_NAME"] = dt.Rows[0]["EMP_FNAME"].ToString() + dt.Rows[0]["EMP_LNAME"].ToString();
dr["EMP_EMAIL"] = dt.Rows[0]["EMP_EMAIL"].ToString(); ;
dt.Rows.Add(dr);


}
ds1.Tables.Add(dt);
MessageBox.Show("READING COMPLETED");
}
catch (Exception ex)
{
// Log the exception and quit...
app.Quit();
//Console.WriteLine(ex.Message);
}
finally
{
//ds1.Dispose();
}
}

private void btnGenerateExcel_Click(object sender, EventArgs e)
{
//dr = dt.NewRow();
ApplicationClass excel = new ApplicationClass();

excel.Application.Workbooks.Add(true);

//System.Data.DataSet dstable = ds1.Tables[;
int ColumnIndex = 0;
//for (int j = 0; j <= ds1.Tables.Count-1; j++)
//{
foreach (DataColumn col in ds1.Tables[0].Columns)
{
ColumnIndex++;
excel.Cells[1, ColumnIndex] = col.ColumnName;
}
//}

int rowIndex = 0;

foreach (DataRow row in ds1.Tables[0].Rows)
{
rowIndex++;
ColumnIndex = 0;
foreach (DataColumn col in ds1.Tables[0].Columns)
{
ColumnIndex++;
excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName];
}
}
excel.Visible = true;
Worksheet worksheet = (Worksheet)excel.ActiveSheet;
// worksheet.SaveAs("C:\\Family_Details.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);


}
}
}





Monday, November 9, 2009

SMTP Email Application c# ASP.NET





using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;


public partial class _Default : System.Web.UI.Page
{

#region "Private Variables And Constants"
string savePath;
private string[] file;
private string fileName = string.Empty;
private string _fileTypes = string.Empty;
private string _serverpath = string.Empty;
string filePath = string.Empty;
private int _fileSize = 5;
int fileTypeCounter = 0;
SmtpClient smtpClient = new SmtpClient();
MailMessage mMessage = new MailMessage();
ContentType attachType = new ContentType();
#endregion


protected void Page_Load(object sender, EventArgs e)
{
lblErrorMsg.Text = "";

}


protected void btnSend_Click(object sender, EventArgs e)
{

string str;
MailAddress fromAddress = new MailAddress(this.txtFrom.Text);
mMessage.From = fromAddress;
mMessage.To.Add(this.txtTo.Text);
mMessage.Subject = this.txtSubject.Text;
mMessage.Body = this.txtBody.Text;
//Server IP Address
smtpClient.Host = "10.229.86.65";
attachType.Name = UploadFile.PostedFile.FileName;
mMessage.Attachments.Add(new Attachment(savePath + UploadFile.PostedFile.FileName));
smtpClient.Send(mMessage);

}

protected void btnReset_Click(object sender, EventArgs e)
{
this.txtTo.Text = "";
this.txtFrom.Text = "";
this.txtSubject.Text = "";
this.txtBody.Text = "";
}

///


/// Upload files upload to the server
///

///

#region "Upload Files"

public void UploadFiles()
{
try
{
file = _fileTypes.Split(',');
if ((UploadFile.PostedFile != null) && (UploadFile.PostedFile.ContentLength > 0))
{
//Checking for File Size in MegaBytes. 1048576 bytes represents 1 MB.
if (((UploadFile.PostedFile.ContentLength / 1048576) <= this._fileSize)) { for (fileTypeCounter = 0; fileTypeCounter <= file.Length - 1; fileTypeCounter++) { file[fileTypeCounter] = file[fileTypeCounter].ToString(); if (!(UploadFile.PostedFile.ContentType == "application/octet-stream")) { if (!(UploadFile.PostedFile.ContentType == "application/zip")) { if (UploadFile.PostedFile.ContentType == "text/plain" || UploadFile.PostedFile.ContentType == "application/pdf" || UploadFile.PostedFile.ContentType == "application/msword" || UploadFile.PostedFile.ContentType == "application/vnd.ms-excel" || UploadFile.PostedFile.ContentType == "application/vnd.ms-powerpoint" || UploadFile.PostedFile.ContentType == "image/jpg" || UploadFile.PostedFile.ContentType == "image/jpeg" || UploadFile.PostedFile.ContentType == "image/pjpeg") { filePath = Path.GetFullPath(UploadFile.PostedFile.FileName); fileName = Path.GetFileName(UploadFile.PostedFile.FileName); SaveFile(UploadFile.PostedFile); } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "Only File type text,PDF,JPG,MSWord,Excel,PowerPoint are allowed."; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "You cannot upload file type Zip"; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "You cannot upload file type Zip"; } break; // TODO: might not be correct. Was : Exit For } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "The File size cannot be greater than 5MB."; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "There is no file to Upload"; } } catch (Exception ex) { lblErrorMsg.Text = ""; lblErrorMsg.Text = ex.Message; } } #endregion #region "Save File to Server" ///
/// Save File to the Server (upload)
///

///
///

private void SaveFile(HttpPostedFile file1)
{

try
{
// Specify the path to save the uploaded file to.
//Server path
savePath = "\\\\Gvwrsd01\\e$\\UploadFiles\\";
fileName = UploadFile.FileName.ToString();
string pathToCheck = savePath.ToString() + fileName.ToString();
string temperoryfileName = string.Empty;
if ((UploadFile.HasFile))
{
savePath += fileName;
file1.SaveAs(savePath);
lblErrorMsg.Text = "";
lblErrorMsg.Text = "The File has been uploaded successfully.";
}
else
{

}
}
catch (Exception ex)
{
lblErrorMsg.Text = "";
lblErrorMsg.Text = ex.Message;
}
}
#endregion


protected void Button1_Click(object sender, EventArgs e)
{
UploadFiles();
}


}



Upload Files to the server for different file types using vb.net



GoldMoney. The best way to buy gold & silver


Upload files to the server App helps the user upload different file to the Server.
This app allows you to upload all the file types except Exe and zip files.

asp:FileUpload control to upload files to server. When you click on the browse button.it opens the file dialog window and we can select file which we want to upload.

I have written UploadFiles() method this method mainly checks to see if we have really trying to upload the file or not, it also checks to see if file types and also checks the file size which should not be greater than 5mb.And finally saves the file to the server.

This condition is checking to see if there is any file selected to upload if not it displays that "There is no file to Upload

if ((UploadFile.PostedFile != null) && (UploadFile.PostedFile.ContentLength > 0))

This line of code actually checks the size of the file. UploadFile.PostedFile.ContentLength / 1048576 gives the actual size in MB.
'Checking for File Size in MegaBytes. 1048576 bytes represents 1 MB.

_fileSize value is hardcoded as 5 mb. You can make this value configurable.


if (((UploadFile.PostedFile.ContentLength / 1048576) <= this._fileSize))



This particular block of code checks the file types. It will not allow uploading EXE and zip file types to the server. It will allow only file types like text, PDF, MSWORD, JPG, EXCEL,POWER point. I have written jpg, jpeg, pjpeg because some browsers will take jep as pjpeg. So if you don't put the condition image/pipe and upload jpg or jpeg it will assume it as different file type and won’t allow the user to upload the file. So it better to have these 3 conditions.

if (UploadFile.PostedFile.ContentType == "text/plain" || UploadFile.PostedFile.ContentType == "application/pdf" || UploadFile.PostedFile.ContentType == "application/msword" || UploadFile.PostedFile.ContentType == "application/vnd.ms-excel" || UploadFile.PostedFile.ContentType == "application/vnd.ms-powerpoint" || UploadFile.PostedFile.ContentType == "image/jpg" || UploadFile.PostedFile.ContentType == "image/jpeg" || UploadFile.PostedFile.ContentType == "image/pjpeg")

After checking ther file types we are using Path.GetFullPath,Path.GetFileName to get the file name and file path.

SaveFile method save the file to the server. by using the file.SaveAs(savePath). Hope this blog will be use full for the developers. Any questions please post it. I will respond with the answer.



//Default.aspx
1)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>




Untitled Page


Upload Files to the Server.











//Code
using System;
using System.IO;
using System.Web;
using System.Xml;
using System.Web.UI;
using System.Net.Mail;
using Microsoft.VisualBasic;
using System.Web.SessionState;
using System.Web.UI.WebControls;

partial class _Default : System.Web.UI.Page
{
#region "Private Variables And Constants"
private string[] file;
private string fileName = string.Empty;
private string _fileTypes = string.Empty;
private string _serverpath = string.Empty;
string filePath = string.Empty;
private int _fileSize = 5;
#endregion

///
/// Upload files upload to the server
///

///
public void UploadFiles()
{
try
{
int fileTypeCounter = 0;
file = _fileTypes.Split(',');
if ((UploadFile.PostedFile != null) && (UploadFile.PostedFile.ContentLength > 0))
{
//Checking for File Size in MegaBytes. 1048576 bytes represents 1 MB.
if (((UploadFile.PostedFile.ContentLength / 1048576) <= this._fileSize)) { for (fileTypeCounter = 0; fileTypeCounter <= file.Length - 1; fileTypeCounter++) { file[fileTypeCounter] = file[fileTypeCounter].ToString(); if (!(UploadFile.PostedFile.ContentType == "application/octet-stream")) { if (!(UploadFile.PostedFile.ContentType == "application/zip")) { if (UploadFile.PostedFile.ContentType == "text/plain" || UploadFile.PostedFile.ContentType == "application/pdf" || UploadFile.PostedFile.ContentType == "application/msword" || UploadFile.PostedFile.ContentType == "application/vnd.ms-excel" || UploadFile.PostedFile.ContentType == "application/vnd.ms-powerpoint" || UploadFile.PostedFile.ContentType == "image/jpg" || UploadFile.PostedFile.ContentType == "image/jpeg" || UploadFile.PostedFile.ContentType == "image/pjpeg") { filePath = Path.GetFullPath(UploadFile.PostedFile.FileName); fileName = Path.GetFileName(UploadFile.PostedFile.FileName); SaveFile(UploadFile.PostedFile); } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "Only File type text,PDF,JPG,MSWord,Excel,PowerPoint are allowed."; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "You cannot upload file type Zip"; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "You cannot upload file type Zip"; } break; // TODO: might not be correct. Was : Exit For } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "The File size cannot be greater than 5mb"; } } else { lblErrorMsg.Text = ""; lblErrorMsg.Text = "There is no file to Upload"; } } catch (Exception ex) { lblErrorMsg.Text = ""; lblErrorMsg.Text = ex.Message; } } ///
/// Save File to the Server (upload)
///

/// ///
private void SaveFile(HttpPostedFile file)
{
try
{
// Specify the path to save the uploaded file to.
string savePath = null;
if (TextBox2.Text != null & TextBox1.Text != null)
{
savePath = "\\\\" + TextBox2.Text + " \\e$\\" + TextBox1.Text + "\\";
fileName = UploadFile.FileName;
string pathToCheck = savePath.ToString() + fileName.ToString();
string temperoryfileName = string.Empty;
if ((UploadFile.HasFile))
{
savePath += fileName;
file.SaveAs(savePath);
lblErrorMsg.Text = "";
lblErrorMsg.Text = "The File has been uploaded successfully.";
}
}
else
{
lblErrorMsg.Text = "";
lblErrorMsg.Text = "Please enter the correct ServerName or else there is no server name exists with that Name.";
}

}
catch (Exception ex)
{
lblErrorMsg.Text = "";
lblErrorMsg.Text = ex.Message;
}
}

protected void Page_Load(object sender, System.EventArgs e)
{
lblErrorMsg.Text = "";
}

protected void Button1_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("\\\\" + TextBox2.Text + " \\e$\\" + TextBox1.Text);
}

protected void btnuploadFile_Click1(object sender, EventArgs e)
{
UploadFiles();
}
}




Tuesday, November 3, 2009

Parse multiple Flat files and export to Excel Spreadsheet



Untitled Page







I have written a utility which will be use full for parsing a flat file and exporting to an excel spreadsheet. I used Visual studio 2005 with .net 2.0 framework c#.
One of my friend had a requirement in his work location he has to read multiple flat files of similar data and export it to one single spread sheet.



Bacically i have written in a Console App. You can use this code and change accordingly based on the your requirement.


I took a two simple flat files like information regarding firstname,lastname,middlename,address.


Create a text file Name:FlatFile_1.txt
Paste the content in the txt file and save in C:\FlatFiles\

Samual sam Jackson 900 Bethalham rd edison NJ
Gorge Micheal Micheal 300 vartan ct Harrisburgh PA
Micheal jackson Micheal 100 Wlatin rd Los Angeles CA
Demi Moore M 211 Century Park Los Angeles CA

Create a text file Name:FlatFile_2.txt
Paste the content in the txt file and save in C:\FlatFiles\

AlPachino sam son 900 Bethalham rd edison NJ
Rihana heal Micheal 300 vartan ct Harrisburgh PA
Britny Speers al 100 Wlatin rd Los Angeles CA
joel Osteen M 211 Century Park Los Angeles CA



NameSpace
Namespaces required for this app is System.IO is used for get,read and write the files from the directory.System.Data is used to create a temp table of DataTable and DataSet objects.
System.Collections is used for creating the array list.
Microsoft.Office.Interop.Excel is used to creat a Excel object and export to Spreadsheet.

Add reference of Microsoft.Office.Interop.Excel by clicking Add Reference in you project and go to .NET tab and search for Microsoft.Office.Interop.Excel dll. select it and click ok to add it to your project reference.


using System.IO;
using System.Data;
using System.Collections;
using Microsoft.Office.Interop.Excel

I created a class called MyFlatFIleReaderClass and a Main Method where you try to execute the code of your class. THe class consist of a Function ParseFile which takes the input parameter of string inputFile. which returns a dataset.

This function has a tempeory table DataTable dt and a DataColumn dc and DataRow dr.
StreamReader and TextReader class is used to Read the flat file data and puts in the string call SLine. It read's each line and add's it to the array list object.
Once the arraylist object is filled we have to loop through it and adds the rows to the Columns by using subString on the column length and gets the actual column value.

In the Main method DirectoryInfo class is used to get all the files which is of type *.txt by using the GetFiles method and stores it in FIleInfo Array object.
once you hacve all the files from the directory we can loop through the files and make a call to the ParseFile function and pass the path Attached the filename. The Function returns a dataset with all the columns and rows created for numbers of tables.

Next step is to create a ApplicationClass object which is used to add columns and rows in the excel object and opens the Excel spreadsheet.

THe Data Displayed in the Excel Sheet will be sorted by the First Column.
by implementing the
Range rng = worksheet.get_Range("A1", Type.Missing);
rng.Sort Method


// Source Code
// Source Code
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Collections;
using Microsoft.Office.Interop.Excel;
namespace Training
{
class MyFlatFIleReaderClass
{
public DataSet ds = new DataSet();
public DataSet ParseFile(string inputFile)
{
DataRow dr;
DataColumn dc;
System.Data.DataTable dt = new System.Data.DataTable();
dc = new DataColumn("FirstName");
dt.Columns.Add(dc);
dc = new DataColumn("LastName");
dt.Columns.Add(dc);
dc = new DataColumn("MiddleName");
dt.Columns.Add(dc);
dc = new DataColumn("Address");
dt.Columns.Add(dc);
//dr = dt.NewRow();
string sLine = "";
ArrayList arrText = new ArrayList();
using (TextReader reader = new StreamReader(inputFile))
{

while (sLine != null)
{
sLine = reader.ReadLine();
if (sLine != null && sLine != "")
arrText.Add(sLine);
}
reader.Close();

foreach (string sOutput in arrText)
{
dr = dt.NewRow();
if (sOutput != string.Empty)
{
dr["FirstName"] = sOutput.Substring(0, 9);
dr["MiddleName"] = sOutput.Substring(10, 9);
dr["LastName"] = sOutput.Substring(20, 9);
dr["Address"] = sOutput.Substring(30);
dt.Rows.Add(dr);
}
}
ds.Tables.Add(dt);
return ds;
}
}

static void Main(string[] args)
{
MyFlatFIleReaderClass tr = new MyFlatFIleReaderClass();
DirectoryInfo di = new DirectoryInfo("C:\\FlatFiles\\");
FileInfo[] rgFiles = di.GetFiles("*.txt");
DataSet ds1 = new DataSet();
foreach (FileInfo fi in rgFiles)
{
ds1 = tr.ParseFile(@"C:\FlatFiles\" + fi.Name);
}

ApplicationClass excel = new ApplicationClass();
excel.Application.Workbooks.Add(true);

//System.Data.DataSet dstable = ds1.Tables[;
int ColumnIndex = 0;
//for (int j = 0; j <= ds1.Tables.Count-1; j++) //{ foreach (DataColumn col in ds1.Tables[0].Columns) { ColumnIndex++; excel.Cells[1, ColumnIndex] = col.ColumnName; } //} int rowIndex = 0; for (int i = 0; i <= ds1.Tables.Count - 1; i++) { foreach (DataRow row in ds1.Tables[i].Rows) { rowIndex++; ColumnIndex = 0; foreach (DataColumn col in ds1.Tables[0].Columns) { ColumnIndex++; excel.Cells[rowIndex + 1, ColumnIndex] = row[col.ColumnName]; } } } excel.Visible = true; Worksheet worksheet = (Worksheet)excel.ActiveSheet; worksheet.Name = "Family_Details"; Range rng = worksheet.get_Range("A1", Type.Missing); rng.Sort(rng, XlSortOrder.xlAscending, Type.Missing, Type.Missing, XlSortOrder.xlAscending, Type.Missing, XlSortOrder.xlAscending, XlYesNoGuess.xlNo, Type.Missing, Type.Missing, XlSortOrientation.xlSortColumns, XlSortMethod.xlPinYin, XlSortDataOption.xlSortNormal, XlSortDataOption.xlSortNormal, XlSortDataOption.xlSortNormal); worksheet.Activate(); } } }







Alan Johnston banner