HOW TO COMPARE TWO EXCEL SHEETS AND DISPLAY THE RESULT IN NEW EXCEL SHEET USING C#.NET?
Consider two excel sheets and specify the data as follows
Excel1.xslx
ID NAME Qualification
1 bindu B-tech
2 Anu Degree
3 Deepthi M-tech
4 indu Mca
5 Amulya Mba
Excel2.xslx
ID NAME Qualification
1 bindu B-tech
2 Anu Degree
3 Deepthi M-tech
Now write the code and it will automatically generates a new Excel sheet as follows
Result.xslx
ID NAME Qualification
4 indu Mca
5 Amulya Mba
Coding:-
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.Runtime.InteropServices;
using System.Data.SqlClient;
using System.IO;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelEg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BtnBrwse_Click(object sender, EventArgs e)
{
OpenFileDialog DialogA = new OpenFileDialog();
DialogA.CheckFileExists = true;
//DialogA.InitialDirectory = "Desktop"
DialogA.Title = "Select a File";
if (DialogA.ShowDialog() == DialogResult.OK)
{
FileTxt1.Text = DialogA.FileName;
}
else if (FileTxt1.Text == "")
{
MessageBox.Show("Please Select a File");
}
}
private void BtnBrwse2_Click(object sender, EventArgs e)
{
OpenFileDialog DialogB = new OpenFileDialog();
DialogB.CheckFileExists = true;
DialogB.Title = "Select a file";
if (DialogB.ShowDialog() == DialogResult.OK)
{
FileTxt2.Text = DialogB.FileName;
}
else if (FileTxt2.Text == "")
{
MessageBox.Show("Please Select a File");
}
}
private void Btn_cmpare_Click(object sender, EventArgs e)
{
string filename1 = FileTxt1.Text;
string filename2 = FileTxt2.Text;
//string filename3 = FileTxt3.Text;
string file1_sheet = GetExcelSheets(filename1);
string file2_sheet = GetExcelSheets(filename2);
//string file3_sheet = GetExcelSheets(filename3);
String sConnectionString1 = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filename1 + ";" +
"Extended Properties=Excel 12.0;";
String sConnectionString2 = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + filename2 + ";" +
"Extended Properties=Excel 12.0;";
// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString1);
// Open connection with the database.
objConn.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [" + file1_sheet + "$]", objConn);
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
//Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1, "XLData");
DataTable dt1 = objDataset1.Tables[0];
objConn.Close();
objConn = new OleDbConnection(sConnectionString2);
// Open connection with the database.
objConn.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
objCmdSelect = new OleDbCommand("SELECT * FROM [" + file2_sheet + "$]", objConn);
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
objDataset1 = new DataSet();
// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");
DataTable dt2 = objDataset1.Tables[0];
// Clean up objects.
objConn.Close();
DataTable dtresult = new DataTable();
dtresult = Comparedata(dt1, dt2);
}
public DataTable Comparedata(DataTable Firsttb, DataTable Secondtb)
{
Firsttb.TableName = "FirstTable";
Secondtb.TableName = "SecondTable";
//Create Empty Table
DataTable table = new DataTable("Difference");
try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[]
{
Firsttb.Copy(), Secondtb.Copy()});
DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];
for (int i = 0; i < firstcolumns.Length; i++)
{
firstcolumns[i] = ds.Tables[0].Columns[i];
}
DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];
for (int i = 0; i < secondcolumns.Length; i++)
{
secondcolumns[i] = ds.Tables[1].Columns[i];
}
//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);
ds.Relations.Add(r);
for (int i = 0; i < Firsttb.Columns.Count; i++)
{
table.Columns.Add(Firsttb.Columns[i].ColumnName, Firsttb.Columns[i].DataType);
}
//If First Row not in Second, Add to return table.
table.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}
table.EndLoadData();
}
}
catch (Exception ex)
{
}
string fileName = "Result";
ExportDataTableToExcel(table, fileName);
return table;
}
private void ExportDataTableToExcel(DataTable dt, string filename)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;
for (i = 0; i < dt.Columns.Count; i++)
{
xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
for (i = 0; i < dt.Rows.Count; i++)
{
for (j = 0; j < dt.Columns.Count; j++)
{
xlWorkSheet.Cells[i + 2, j + 1] = dt.Rows[i][j];
}
}
try
{
xlWorkBook.SaveAs(filename + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public string GetExcelSheets(string excelFileName)
{
Microsoft.Office.Interop.Excel.Application excelFileObject = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workBookObject = null;
workBookObject = excelFileObject.Workbooks.Open(excelFileName, 0, true, 5, "", "", false,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
"",
true,
false,
0,
true,
false,
false);
Excel.Sheets sheets = workBookObject.Worksheets;
// get the first and only worksheet from the collection of worksheets
Excel.Worksheet worksheet = (Excel.Worksheet)sheets.get_Item(1);
MessageBox.Show(worksheet.Name);
return worksheet.Name;
}
}
}