How can I compare the 2 dataTable in c#
For example
dataTable1
a,a,a,a,1,a,a,a,a,a
a,a,a,a,1,a,a,a,a,a
a,a,a,a,2,a,a,a,a,a
a,a,a,a,2,a,a,a,a,a
a,a,a,a,3,a,a,a,a,a
dataTable2
b,b,b,b,1,b,b,b,b,b
b,b,b,b,1,b,b,b,b,b
b,b,b,b,1,b,b,b,b,b
b,b,b,b,2,b,b,b,b,b
b,b,b,b,2,b,b,b,b,b
How do I run the 1st row in dataTable1 [5] which is = 1, if dataTable2 [5] also consists 1 then print out the line. Continue until finish. Then Continue loop to second one in dataTable1 check with dataTable2
Here is my code
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompareLinuxWithWindow
{
class Program
{
static void Main(string[] args)
{
DataTable dt1 = ConvertToDataTable(#"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(#"C:\Users\manchunl\Desktop\Sample2.txt", 10);
foreach (DataRow row in dt1.AsEnumerable())
{
string temp_dt1 = "";
string[] words = temp_dt1.Split(',');
string.Join(",", row.ItemArray.Select(x => x.ToString()));
temp_Linux = (string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
foreach (DataRow row in dt2.AsEnumerable())
{
string temp_dt2 = "";
string.Join(",", row.ItemArray.Select(x => x.ToString()));
temp_dt2 = (string.Join(",", row.ItemArray.Select(x => x.ToString())));
}
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.Read();
}
public static DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(null);
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
public static DataTable ConvertToDataTable2(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
for (int col = 0; col < numberOfColumns; col++)
tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));
string[] lines = System.IO.File.ReadAllLines(filePath);
foreach (string line in lines)
{
var cols = line.Split(',');
DataRow dr = tbl.NewRow();
for (int cIndex = 0; cIndex < numberOfColumns; cIndex++)
{
dr[cIndex] = cols[cIndex];
}
tbl.Rows.Add(dr);
}
return tbl;
}
}
}
You can try using the loop as below, please pay attention to comments as those are important
// assumption is that both dt1 and dt2 has same number of rows
// otherise while accessing dt2 we can get index out of range exception
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dr1 = dt1.Rows[i];
DataRow dr2 = dt2.Rows[i];
// accessing the column below would return a system.object variable,
// need to convert it to the right type using one of the convert calls, e.g. Convert.ToInt16(dr1["ColumnName"])
if (dr1["ColumnName"] == dr2["ColumnName"])
{
// do whatever you want to do here
}
}
You can return the data table which will be the difference of two input data table and later you can perform operations on the resulting data table.
CODE
/// <summary>
/// Compare two DataTables and return a DataTable with DifferentRecords
/// </summary>
/// <param name="FirstDataTable">FirstDataTable</param>
/// <param name="SecondDataTable">SecondDataTable</param>
/// <returns>DifferentRecords</returns>
public DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable)
{
//Create Empty Table
DataTable ResultDataTable = new DataTable("ResultDataTable");
//use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
var dataTable = new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() };
dataTable[0].TableName = "FirstTable";
dataTable[1].TableName = "SecondTable";
//Add tables
ds.Tables.AddRange(dataTable);
//Get Columns for DataRelation
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 r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false);
ds.Relations.Add(r1);
DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false);
ds.Relations.Add(r2);
//Create columns for return table
for (int i = 0; i < FirstDataTable.Columns.Count; i++)
{
ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName,
FirstDataTable.Columns[i].DataType);
}
//If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable.
ResultDataTable.BeginLoadData();
foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r1);
if (childrows == null || childrows.Length == 0)
{
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
}
//If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable.
foreach (DataRow parentrow in ds.Tables[1].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r2);
if (childrows == null || childrows.Length == 0)
ResultDataTable.LoadDataRow(parentrow.ItemArray, true);
}
ResultDataTable.EndLoadData();
}
return ResultDataTable;
}
You need to first loop on the first data table
Then get row at specific index
Check whether current row exist in second data table
Get row from second data table at same index.
Read the column value from row to string variable.
Check if both value from both row are equal or not.
DataTable dt1 = ConvertToDataTable(#"C:\Users\manchunl\Desktop\Sample1.txt", 10);
DataTable dt2 = ConvertToDataTable2(#"C:\Users\manchunl\Desktop\Sample2.txt", 10);
for (int i = 0; i < dt1.Rows.Count; i++)
{
DataRow dr1 = dt1.Rows[i];
if (dt2.Rows.Count > i)
{
DataRow dr2 = dt2.Rows[i];
string value1 = Convert.ToString(dr1["Column5"]);
string value2 = Convert.ToString(dr2["Column5"]);
if (!string.IsNullOrEmpty(value1) && !string.IsNullOrEmpty(value2) && value1 == value2)
{
Console.WriteLine(value1);
}
else
{
//Do code when no matched.
}
}
}
This is my current code. Open to receive any comments to improve the memory optimization.
When I am taking a sample of 1000000 * 8 with 1000000*8 data its resulting into out of memory exception. Would love to have advice on optimizing memory usage.
Compare The two tables in a data set named "Before" and "After" and fill all result tables.
private bool CompareAndFillResultTable(DataSet ds)
{
Stopwatch stopWatch = new Stopwatch(); stopWatch.Start();
System.Data.DataTable dt_copy;
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Copy();
dt_copy.TableName = "BeforeBackup";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["After"].Copy();
dt_copy.TableName = "AfterBackup";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "BeforeSingular";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "AfterSingular";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "Duplicates";
ds.Tables.Add(dt_copy);
dt_copy = new System.Data.DataTable();
dt_copy = ds.Tables["Before"].Clone();
dt_copy.TableName = "Mismatch";
ds.Tables.Add(dt_copy);
foreach (System.Data.DataTable table in ds.Tables)
{
table.Columns.Add("Source_Label");
}
//Remove identical from before, then after
for (int i = 0; i < ds.Tables["Before"].Rows.Count; i++)
{
string BeforeCompareKeyVal = ds.Tables["Before"].Rows[i][Inputs.SortColumn].ToString();
if (ds.Tables["After"].Rows.Count > 0)
{
for (int j = 0; j < ds.Tables["After"].Rows.Count; j++)
{
string AfterCompareKeyVal = ds.Tables["After"].Rows[j][Inputs.SortColumn].ToString();
if (ds.Tables["Before"].Rows[i].ItemArray.SequenceEqual(ds.Tables["After"].Rows[j].ItemArray))
{
//copy Aftter row to duplicate Table and Remove row from After
DataRow rw = ds.Tables["After"].Rows[j];
rw[ds.Tables["After"].Columns.Count - 1] = "NA";
ds.Tables["Duplicates"].ImportRow(rw);
ds.Tables["After"].Rows.RemoveAt(j);
j--;
break;
}
if (Int64.Parse(BeforeCompareKeyVal) > Int64.Parse(AfterCompareKeyVal))// Review - 7
{
if (true)//all dup after + a before - set logic
{
//Copy After row to AfterSingular Table and Remove row from After
DataRow rw = ds.Tables["After"].Rows[j];
rw[ds.Tables["After"].Columns.Count - 1] = "After";
ds.Tables["AfterSingular"].ImportRow(rw);
ds.Tables["After"].Rows.RemoveAt(j);
j--;
if (ds.Tables["After"].Rows.Count == 0)
{
rw = ds.Tables["Before"].Rows[i];
rw[ds.Tables["Before"].Columns.Count - 1] = "Before";
ds.Tables["BeforeSingular"].ImportRow(rw);
}
continue;
}
}
if (Int64.Parse(BeforeCompareKeyVal) < Int64.Parse(AfterCompareKeyVal))// Review - 7
{
if (true)//all dup after and a before set logic
{
//Copy Before row to BeforeSingular Table
DataRow rw = ds.Tables["Before"].Rows[i];
rw[ds.Tables["Before"].Columns.Count - 1] = "Before";
ds.Tables["BeforeSingular"].ImportRow(rw);
break;
}
}
if (Int64.Parse(BeforeCompareKeyVal) == Int64.Parse(AfterCompareKeyVal))// Review - 7
{
//Copy Before, After row to Mismatch Table and Remove row from After
if (true)//all dup after and a before set logic
{
DataRow rwB = ds.Tables["Before"].Rows[i];
rwB[ds.Tables["Before"].Columns.Count - 1] = "Before";
DataRow rwA = ds.Tables["After"].Rows[j];
rwA[ds.Tables["After"].Columns.Count - 1] = "After";
ds.Tables["Mismatch"].ImportRow(rwB);
ds.Tables["Mismatch"].ImportRow(rwA);
ds.Tables["After"].Rows.RemoveAt(j);
j--;
break;
}
}
}
}
else
{
DataRow rw = ds.Tables["Before"].Rows[i];
rw[ds.Tables["Before"].Columns.Count - 1] = "Before";
ds.Tables["BeforeSingular"].ImportRow(rw);
continue;
}
}
//Add remaining after table rows to AfterSingular table
ds.Tables["AfterSingular"].Merge(ds.Tables["After"]);
//ds.Tables["AfterSingular"].Columns.Add("Source_Label", System.Type.GetType("System.String"), "After_Singular");
//ds.Tables["BeforeSingular"].Columns.Add("Source_Label", System.Type.GetType("System.String"), "Before_Singular");
//foreach (System.Data.DataTable table in ds.Tables)
//{
// DataRow colNames = table.NewRow();
// //foreach (var col in table.Columns)
// //{
// //}
// for (int i = 0; i < table.Columns.Count; i++)
// colNames[i] = table.Columns[i].ColumnName;
// table.Rows.InsertAt(colNames, 0);
//}
foreach (System.Data.DataTable table in ds.Tables)
{
table.Columns.Remove(Inputs.SortColumn);
table.AcceptChanges();
}
stopWatch.Stop(); lbAlert.Text = lbAlert.Text + "\n\n" + "Total Comparison time for B: " + Inputs.RowNoBeforeTable + " x " + Inputs.ColumnNoBeforeTable + " A: " + Inputs.RowNoAfterTable + " x " + Inputs.ColumnNoAfterTable + " is " + stopWatch.ElapsedMilliseconds + " ms, " + stopWatch.ElapsedMilliseconds / 1000 + " s";
return true;
}
Can you not just use a VBA script to do this kind of thing?
Option Explicit
Sub test()
Dim varSheetA As Variant
Dim varSheetB As Variant
Dim strRangeToCheck As String
Dim iRow As Long
Dim iCol As Long
strRangeToCheck = "A1:IV65536"
' If you know the data will only be in a smaller range, reduce the size of the ranges above.
Debug.Print Now
varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
Debug.Print Now
For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
' Cells are identical.
' Do nothing.
Else
' Cells are different.
' Code goes here for whatever it is you want to do.
Cells(iRow, iCol).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 49407
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End If
Next iCol
Next iRow
End Sub
I am using OpenXML for exporting data to Excel (.xlsx)
I am getting following error when I am trying to write Data having 29 columns and 62397 rows
However I have noiced that an xlsx file is created and all the rows have been written into it.
Please let me know if anything is missing.
The code is as follows
private static void ExporttoExcel(DataSet ds, SpreadsheetDocument sheet)
{
try
{
sheet.AddWorkbookPart();
sheet.WorkbookPart.Workbook = new DocumentFormat.OpenXml.sheet.Workbook();
sheet.WorkbookPart.Workbook.Append(new BookViews(new WorkbookView()));
WorkbookStylesPart workbookStylesPart = sheet.WorkbookPart.AddNewPart<WorkbookStylesPart>("rIdStyles");
Stylesheet stylesheet = new Stylesheet();
workbookStylesPart.Stylesheet = stylesheet;
int worksheetNumber = 1;
foreach (DataTable dt in ds.Tables)
{
string workSheetID = "sheet" + worksheetNumber.ToString();
string worksheetName = dt.TableName;
WorksheetPart newWorksheetPart = sheet.WorkbookPart.AddNewPart<WorksheetPart>();
newWorksheetPart.Worksheet = new DocumentFormat.OpenXml.sheet.Worksheet();
newWorksheetPart.Worksheet.AppendChild(new DocumentFormat.OpenXml.sheet.SheetData());
WriteDataTableToExcelWorksheet(dt, newWorksheetPart);
newWorksheetPart.Worksheet.Save();
if (worksheetNumber == 1)
sheet.WorkbookPart.Workbook.AppendChild(new DocumentFormat.OpenXml.sheet.Sheets());
sheet.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.sheet.Sheets>().AppendChild(new DocumentFormat.OpenXml.sheet.Sheet()
{
Id = sheet.WorkbookPart.GetIdOfPart(newWorksheetPart),
SheetId = (int)worksheetNumber,
Name = dt.TableName
});
worksheetNumber++;
}
sheet.WorkbookPart.Workbook.Save();
}
catch (Exception)
{
throw;
}
finally
{
sheet.Dispose();
}
}
private static void WriteDTToExcel(DataTable dt, WorksheetPart worksheet)
{
var worksheet = worksheet.Worksheet;
var sheetData = worksheet.GetFirstChild<SheetData>();
string cellValue = "";
int numberOfColumns = dt.Columns.Count;
bool[] IsNumericColumn = new bool[numberOfColumns];
string[] excelColumnNames = new string[numberOfColumns];
for (int n = 0; n < numberOfColumns; n++)
excelColumnNames[n] = GetExcelColumnName(n);
int rowIndex = 1;
var headerRow = new Row { RowIndex = rowIndex }; // add a row at the top of sheet
sheetData.Append(headerRow);
for (int colInx = 0; colInx < numberOfColumns; colInx++)
{
DataColumn col = dt.Columns[colInx];
AppendTextCell(excelColumnNames[colInx] + "1", col.ColumnName, headerRow);
IsNumericColumn[colInx] = (col.DataType.FullName == "System.Decimal") || (col.DataType.FullName == "System.Int32");
}
double cellNumericValue = 0;
foreach (DataRow dr in dt.Rows)
{
++rowIndex;
var newExcelRow = new Row { RowIndex = rowIndex }; // add a row at the top of sheet
sheetData.Append(newExcelRow);
for (int colInx = 0; colInx < numberOfColumns; colInx++)
{
cellValue = dr.ItemArray[colInx].ToString();
if (IsNumericColumn[colInx])
{
cellNumericValue = 0;
if (double.TryParse(cellValue, out cellNumericValue))
{
cellValue = cellNumericValue.ToString();
AppendNumericCell(excelColumnNames[colInx] + rowIndex.ToString(), cellValue, newExcelRow);
}
}
else
{
AppendTextCell(excelColumnNames[colInx] + rowIndex.ToString(), cellValue, newExcelRow);
}
}
}
}
private static void AppendTextCell(string cellReference, string value, Row excelRow)
{
Cell cell = new Cell() { CellReference = cellReference, DataType = CellValues.String };
CellValue cellValue = new CellValue();
cellValue.Text = value;
cell.Append(cellValue);
excelRow.Append(cell);
}
private static void AppendNumericCell(string cellReference, string value, Row row)
{
Cell cell = new Cell() { CellReference = cellReference };
CellValue cellValue = new CellValue();
cellValue.Text = value;
cell.Append(cellValue);
row.Append(cell);
}
private static string GetExcelColumnName(int columnIndex)
{
if (columnIndex < 26)
return ((char)('A' + columnIndex)).ToString();
char firstChar = (char)('A' + (columnIndex / 26) - 1);
char secondChar = (char)('A' + (columnIndex % 26));
return string.Format("{0}{1}", firstChar, secondChar);
}
Exception is thrown while executing following line of ExporttoExcel method
spreadsheet.WorkbookPart.Workbook.Save();
I'm trying to use a Script Task to export data to Excel because some of the reports I generate simply have too many columns to keep using a template file.
The most annoying part about using a template is: if something as simple as a column header changes, the metadata gets screwed forcing me to recreate my DataFlow. Because I use an OLE DB source, I need to use a Data Transformation task to convert between unicode and non-unicode character sets, then remap my Excel Destination to the "Copy of field x" in order for the Excel document to create properly.
This takes far too long and I need a new approach.
I have the following method in a script task using Excel = Microsoft.Office.Interop.Excel:
private void ExportToExcel(DataTable dataTable, string excelFilePath = null)
{
Excel.Application excelApp = new Excel.Application();
Excel.Worksheet workSheet = null;
try
{
if (dataTable == null || dataTable.Columns.Count == 0)
throw new System.Exception("Null or empty input table!" + Environment.NewLine);
excelApp.Workbooks.Add();
workSheet = excelApp.ActiveSheet;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = dataTable.Columns[i].ColumnName;
}
foreach (DataTable dt in dataSet.Tables)
{
// Copy the DataTable to an object array
object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
// Copy the column names to the first row of the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
rawData[0, col] = dt.Columns[col].ColumnName;
}
// Copy the values to the object array
for (int col = 0; col < dt.Columns.Count; col++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{
rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
}
}
// Calculate the final column letter
string finalColLetter = string.Empty;
string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int colCharsetLen = colCharset.Length;
if (dt.Columns.Count > colCharsetLen)
{
finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1);
}
finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);
workSheet.Name = dt.TableName;
// Fast data export to Excel
string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
//The code crashes here (ONLY in SSIS):
workSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
// Mark the first row as BOLD
((Excel.Range)workSheet.Rows[1, Type.Missing]).Font.Bold = true;
}
List<int> lstColumnsToSum = new List<int>() { 9 };
Dictionary<int, string> dictColSumName = new Dictionary<int, string>() { { 9, "" } };
Dictionary<int, decimal> dictColumnSummation = new Dictionary<int, decimal>() { { 9, 0 } };
// rows
for (int i = 0; i < dataTable.Rows.Count; i++)
{
for (int j = 1; j <= dataTable.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j)] = dataTable.Rows[i][j - 1];
if (lstColumnsToSum.Exists(x => (x == j)))
{
decimal val = 0;
if (decimal.TryParse(dataTable.Rows[i][j - 1].ToString(), out val))
{
dictColumnSummation[j] += val;
}
}
}
}
//Footer
int footerRowIdx = 2 + dataTable.Rows.Count;
foreach (var summablecolumn in dictColSumName)
{
workSheet.Cells[footerRowIdx, summablecolumn.Key] = String.Format("{0}", dictColumnSummation[summablecolumn.Key]);
}
// check fielpath
if (excelFilePath != null && excelFilePath != "")
{
try
{
if (File.Exists(excelFilePath))
File.Delete(excelFilePath);
workSheet.Activate();
workSheet.Application.ActiveWindow.SplitRow = 1;
workSheet.Application.ActiveWindow.FreezePanes = true;
int row = 1;
int column = 1;
foreach (var item in dataTable.Columns)
{
Excel.Range range = workSheet.Cells[row, column] as Excel.Range;
range.NumberFormat = "#";
range.EntireColumn.AutoFit();
range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);
column++;
}
Excel.Range InternalCalculatedAmount = workSheet.Cells[1, 9] as Excel.Range;
InternalCalculatedAmount.EntireColumn.NumberFormat = "#0.00";
InternalCalculatedAmount.Columns.AutoFit();
workSheet.SaveAs(excelFilePath);
}
catch (System.Exception ex)
{
throw new System.Exception("Excel file could not be saved! Check filepath." + Environment.NewLine + ex.Message);
}
}
else // no filepath is given
{
excelApp.Visible = true;
}
}
catch (System.Exception ex)
{
throw new System.Exception("ex.Message + Environment.NewLine, ex.InnerException);
}
}
The exception thrown is a System.OutOfMemoryException when trying to execute the following piece of code:
workSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
My biggest frustration is that this method works 100% in a regular C# application.
The DataTable contains about 435000 rows. I know it's quite a bit of data but I use this very method, modified of course, to split data across multiple Excel worksheets in one of my other applications, and that DataSet contains about 1.1m rows. So less than half of my largest DataSet should be a walk-in-the-park...
Any light shed on this matter would be amazing!
Here is the code below i'm using, how do you trim while doing the convert.ToString()?
while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null)
{
rowIndex = 2 + index;
row = excel_Holding_Table.NewRow();
for (int i = 1; i <= range.Columns.Count; i++)
{
row[i-1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, i]).Value2);
}
excel_Holding_Table.Rows.Add(row);
index++;
}
Just change the below line..Add the Trim() function at the last
row[i-1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, i]).Value2);
to
string temp = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, i]).Value2);
if(temp!=null)
row[i-1] =temp.Trim();
else
row[i-1] = "";