C# .NET - How to Add Two Excel Sheets into One Single sheet using C#?

Asked By Mohammed Akhtar
04-Dec-09 05:10 AM

Dear All,

            I have to Add two Different Excel Sheets and Make thwm into One Single Excel Sheet using C#.Net. I have the idea to read the Data From and Excel sheets kindly help me in this task.

 

re  re

04-Dec-09 05:45 AM

u can merge two excelsheet into one by using InteropServices.

using Excel;
using System.Runtime.InteropServices;

here this is function which merge more than one excel sheet  u just need to pass excel sheet name in arrReportName array and pass it to function mergeExcel and add referance of InteropServices this works perfectly.

 #region Const
  const int LOGON32_LOGON_INTERACTIVE       = 2;
  const int LOGON32_LOGON_NETWORK           = 3;
  const int LOGON32_LOGON_BATCH             = 4;
  const int LOGON32_LOGON_SERVICE           = 5;
  const int LOGON32_LOGON_UNLOCK            = 7;
  const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
  const int LOGON32_LOGON_NEW_CREDENTIALS   = 9;
  const int LOGON32_PROVIDER_DEFAULT        = 0;

  [DllImport("advapi32.dll", SetLastError=true)]
  public static extern int LogonUser(
   string lpszUsername,
   string lpszDomain,
   string lpszPassword,
   int dwLogonType,
   int dwLogonProvider,
   out IntPtr phToken
   );
  [DllImport("advapi32.dll", SetLastError=true)]
  public static extern int ImpersonateLoggedOnUser(
   IntPtr hToken
   );

  [DllImport("advapi32.dll", SetLastError=true)]
  static extern int RevertToSelf();

  [DllImport("kernel32.dll", SetLastError=true)]
  static extern int CloseHandle(IntPtr hObject);

  #endregion

public void  mergeExcel( string[] arrReportName)
  {
   string dirPath=AppDomain.CurrentDomain.BaseDirectory + "Uploads/Reports";
 
   try
   {
    IntPtr lnToken;
    string Serverusername,Serverpassword,Serverdomain;
    Serverusername = ConfigurationSettings.AppSettings["Serverusername"].ToString();
    Serverpassword = ConfigurationSettings.AppSettings["Serverpassword"].ToString();
    Serverdomain = ConfigurationSettings.AppSettings["Serverdomain"].ToString();
    int TResult = LogonUser(Serverusername,Serverdomain,Serverpassword,LOGON32_LOGON_NETWORK,LOGON32_PROVIDER_DEFAULT, out lnToken);
    if ( TResult > 0 )
    {
     ImpersonateLoggedOnUser(lnToken);
     StringBuilder sb = new StringBuilder(80,80);
  
     uint Size = 79;
    
     Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
     //excelApp.Visible = true;
     string file1,file2,workbookPath,workbookPath2,currentSheet,currentSheet2;
     int RowCount1,RowCount2,TotalRow;
     file1 = arrReportName[0].ToString();
     workbookPath = file1;
     Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
     Excel.Sheets excelSheets = excelWorkbook.Worksheets;
     currentSheet = "rptItemLocationWise";
     Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

     for(int D=1;D<arrReportName.Length;D++)
     {
      file2 = arrReportName[D].ToString();
     
      Excel.Range objR1 = excelWorksheet.UsedRange;
      RowCount1 = objR1.Rows.Count;
      workbookPath2 =file2;
      Excel.Workbook excelWorkbook2 = excelApp.Workbooks.Open(workbookPath2, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
      Excel.Sheets excelSheets2 = excelWorkbook2.Worksheets;

     
      currentSheet2 = "rptItemLocationWise";
      Excel.Worksheet excelWorksheet2 = (Excel.Worksheet)excelSheets2.get_Item(currentSheet2);

      Excel.Range objR2 = excelWorksheet2.UsedRange;
      RowCount2 = objR2.Rows.Count;
      TotalRow = RowCount1 + RowCount2 + 1;
      RowCount1 = RowCount1 + 1;
      RowCount2 = RowCount2 - 1;
      Excel.Range destination = (Excel.Range)excelWorksheet.get_Range("A" + RowCount1.ToString(), "H"+TotalRow.ToString());
      try
      {
       excelWorksheet2.get_Range("A4", "H"+ RowCount2.ToString()).Copy((Excel.Range)destination);
       excelWorkbook2.Close(false,workbookPath2,0);
      }
      catch(Exception ex)
      {
       excelApp.Application.Quit();
       RevertToSelf();
       CloseHandle(lnToken);
       return;
      }
     }
     
     string MergedFile;
     
     MergedFile = dirPath + "\\" + "FinalItemsByLocation.xls";

     if(File.Exists(MergedFile))
      File.Delete(MergedFile);
     //
//     Excel.Range objR3 = excelWorksheet.UsedRange;
//     RowCount1 = objR3.Rows.Count;
//     RowCount1 = RowCount1 + 1;
//     Excel.Range excelCell1 = (Excel.Range)excelWorksheet.get_Range("G" + RowCount1.ToString(),"G" + RowCount1.ToString());
//     Excel.Range excelCell2 = (Excel.Range)excelWorksheet.get_Range("H" + RowCount1.ToString(),"H" + RowCount1.ToString());
//     excelCell1.Value2 = "Grand Total";
//     excelCell1.Font.Bold = true;
//     //string strTotal = "$" + GrandTotal.ToString();
//     excelCell2.Value2 = GrandTotal.ToString();
//     excelCell2.Font.Bold = true;
  
     //

     excelWorkbook.SaveAs(MergedFile,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,0,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
     excelWorkbook.Close(true,workbookPath,0);
     excelApp.Application.Quit();
     RevertToSelf();
     CloseHandle(lnToken);
     //Session["PrintExcelFileName"] = MergedFile;
    }
    else
    {
     //Response.Write("Not logged on: " + Environment.UserName);
    }
   }
   catch(Exception ex)
   {
    string str = ex.Message;
    //    WriteToFile(ex.Message);
    str = "";
   }
  }

How to Add Two Excel Sheets into One Single sheet using C#?  How to Add Two Excel Sheets into One Single sheet using C#?

04-Dec-09 05:49 AM

For that you need to merge excel sheets not add.

Go thru the links,

http://stackoverflow.com/questions/830841/merge-excel-files-into-one

Regards,

http://www.codecollege.net

 

re  re

04-Dec-09 07:53 AM

using Excel = Microsoft.Office.Interop.Excel;

int i = 0;

int j = 0;

Excel.Application xlApp;

object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.Application();

Excel.Workbooks xlBooks = xlApp.Workbooks;

Excel.Workbook xlBook = xlBooks[1];

Excel.Worksheet xlSheet;

OleDbDataReader dr = null;

OleDbCommand myCommand = null;

OleDbConnection myConnection = null;

string fileNameString = "C:\\Temp.xls";

string sConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +

fileNameString + ";Extended Properties=\"Excel 8.0;Readonly=True;HDR=No;IMEX=1;\"";

myConnection = new OleDbConnection(sConn);

myConnection.Open();

 

string dbqury = "Select * From [Sheet1$] ";

 

myCommand = new OleDbCommand(dbqury, myConnection);

dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

xlSheet = (Excel.Worksheet)xlBook.Sheets["Sheet2"];

xlSheet.Name = "Temp";

i = 0;

while (dr.Read())

{

for (j = 0; j <= dr.FieldCount - 1; j++)

{

if (dr[j] != null)

{

xlSheet.Cells[i + 1, j + 1] = dr[j].ToString();

}

}

i = i + 1;

}

dr.Close();

myConnection.Close();

 

OK. Let us see what options we have.  OK. Let us see what options we have.
04-Dec-09 01:08 PM
a) You can simply read the data from the two sheets into datasets using Jet , and create two datasets. and then do a Merge like, 
     DataSet dsOne = ReadFromWorkbook(sheet1);
     DataSet dsTwo = ReadFromWorkbook(sheet2);
     //Final dataset.
     dsOne.Merge(dsTwo);
    Now simply write the dsOne (the merged dataset into a new worksheet. And delete the first two worksheets. 

b) Use Excel Interop (Add a Reference to Microsoft Excel xx Object Library.from the Com tab), and using the Worksheet.GetusedRange method for both the sheets. This would give you the data from the used ranges in the worksheets.  Do a copy on the usedranges from the worksheets - 1 & 2 and Paste these ranges in a new worksheet one after the other. 
As a cleanup procedure, delete the initial two worksheets. 

c) Use Visual Studio Tools for Office (known as 'VSTO') that provides some advanced functionality like Copying worksheets. and much more. 
  John Glenn replied to Mohammed Akhtar
08-Dec-11 04:18 AM
Hi,

you can easily accomplish this task with this http://www.gemboxsoftware.com/spreadsheet/overview library.

Here is an http://www.gemboxsoftware.com/spreadsheet/overview code how to do it:

var excelFile = new ExcelFile();

 

excelFile.LoadXls("MyData.xls");

 

var dataTable1 = excelFile.Worksheets[0].CreateDataTable(ColumnTypeResolution.Auto);

var dataTable2 = excelFile.Worksheets[1].CreateDataTable(ColumnTypeResolution.Auto);

 

var mergedSheet = excelFile.Worksheets.Add("Merged Sheet");

mergedSheet.InsertDataTable(dataTable1, 0, 0, false);

mergedSheet.InsertDataTable(dataTable2, dataTable1.Rows.Count, 0, false);

 

excelFile.SaveXls("MyData.xls");

Create New Account
help
validate excel data before inserting to sql database i want to know how to validate excel data before inserting to sql database May be this will help you; Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value Dim rangeCells As Excel.Range xlApp
Reading Excel I have an excel which has two worksheets. the excel is in xlsx format. I am reading this excel using the following connection string string xConnStr = "Provider = Microsoft.ACE.OLEDB.12.0;" + "Data Source = " + filename + ";" + "Extended Properties = \ "Excel 8.0;IMEX = 1;HDR = NO; \ ""; and having the two worksheet values in two different has 20 rows and Worksheet2 datatable has 10 rows. When i am converting the ablove excel to .xls format and then try to read with the same connectionstring, Worksheet1 datatable has Why is there a difference in reading only one worksheet? Hi you can read the Excel File like this protected void Page_Load(Object Src, EventArgs E) { string strConn; strConn = "Provider = Microsoft
Open Excel File Hi All, I would like to a. open an new excel file from asp.net web application b. write few records to it c. Save the excel file with new name If this is possible please help me Thanks All You wont be able to open excel file in web application. U have to create instance of Excel Application after that u will get particular cell of excel worksheet then & then only u will be able to write in excel file. Hi, try the below one. . Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel
problem Hi, How to attache excel file in vb.net In advance thank you HI use this code Imports Excel = Microsoft.Office.Interop.Excel Public Class Form1 Private Sub Button1_Click( ByVal sender As System. Object , _ ByVal e As System.EventArgs) Handles Button1.Click Dim xlApp As Excel.Application Dim xlWorkBook As Excel.Workbook Dim xlWorkSheet As Excel.Worksheet Dim misValue As Object = System.Reflection.Missing.Value xlApp = New Excel.ApplicationClass xlWorkBook = xlApp.Workbooks.Add(misValue) xlWorkSheet = xlWorkBook.Sheets( "sheet1" ) xlWorkSheet.Cells(1, 1) = " http
IMPORT EXCEL SHEET TO DATABASE USING STORED PROCEDURE Hii, I want know how to import excel sheet data into databse using stored procedure in sql server Use this - INSERT Personal (Name, ID) SELECT Name, ID FROM OPENROWSET('MSDASQL', 'Driver = {Microsoft Excel-Treiber (*.xls)}; DBQ = <filename> ;HDR = NO', 'SELECT * FROM [Tabelle1$]') Exchange <filename> with the filename if the excel-sheet contains header lines set HDR = YES, [Tabelle1$] is the name of the excel-sheet. Follow this link- http: / / www.sqlservercentral.com / Forums / Topic664839-9-1.aspx#bm1093736 hi. . Follow this link . . http: / / www.aspsnippets.com / Articles / Read-and-Import-Excel-Sheet-into-SQL-Server-Database-in-ASP.Net.aspx HI try htis Stored Procedures For this article I have created two stored procedures one to read the Excel 97 – 2003 format and other Excel 2007 format. Though the Microsoft Ace Driver can read