Create an Automation Client for Microsoft Excel

Embed Size (px)

Citation preview

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    1/14

    http://www.dotnetspider.com/resources/43010-How-import-excel-data-into-dataset-using-File.aspx

    Description:

    I have MS excel with more than 100 records in the same time i need to import that data into SQL server. The Excel file path is

    choose from the Client machine using file upload control by user. After user select that file and click the submit button. Then all

    import data from Excel in to DataTable and then bind it in the Grid View control.

    In this below code i have mention two connection strings. If you have 2003 .xls format then use below code or if you have

    2007.xlsx file then change connection string (i put it in comment line check in the source code)

    For example I have excel file with data look like this.

    I need to import that data into dataset. I use the below code for getting records.

    Client side:

    I placed one Grid view, File upload and Button Controls.

    Server side:

    using System.Data;

    http://www.dotnetspider.com/resources/43010-How-import-excel-data-into-dataset-using-File.aspxhttp://www.dotnetspider.com/resources/43010-How-import-excel-data-into-dataset-using-File.aspxhttp://www.dotnetspider.com/resources/43010-How-import-excel-data-into-dataset-using-File.aspx
  • 8/4/2019 Create an Automation Client for Microsoft Excel

    2/14

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

    {

    DataTable dt = new DataTable();

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

    //Check file is available in File upload Control

    if (FileUpload1.HasFile)

    {

    //Store file name in the string variable

    string filename = FileUpload1.FileName;

    //Save file upload file in to server path for temporary

    FileUpload1.SaveAs(Server.MapPath(filename));

    //Export excel data into Gridview using below method

    ExportToGrid(Server.MapPath(filename));

    }

    }

    void ExportToGrid(String path)

    {

    OleDbConnection MyConnection = null;

    DataSet DtSet = null;

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    3/14

    OleDbDataAdapter MyCommand = null;

    //Connection for MS Excel 2003 .xls format

    MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path +

    "';Extended Properties=Excel 8.0;");

    //Connection for .xslx 2007 format

    // MyConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path +

    "';Extended Properties=Excel 12.0;");

    //Select your Excel file

    MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);

    DtSet = new System.Data.DataSet();

    //Bind all excel data in to data set

    MyCommand.Fill(DtSet, "[Sheet1$]");

    dt = DtSet.Tables[0];

    MyConnection.Close();

    //Check datatable have records

    if (dt.Rows.Count > 0)

    {

    GridView1.DataSource = dt;

    GridView1.DataBind();

    }

    //Delete temporary Excel file from the Server path

    if(System.IO.File.Exists(path))

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    4/14

    {

    System.IO.File.Delete(path);

    }

    }

    }

    Source Code Detail:

    Here with I have attached source code download it and try to learn about import data from Excel To Dataset using C# and file

    upload control.Front End : ASP.NET

    Code Behind : C#

    Output:

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    5/14

    OleDbCommand myCommand = new OleDbCommand(CommandText, myConnection);

    myConnection.Open();

    DataGrid1.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

    DataGrid1.DataBind();

    myConnection.Close();}

    Simple Data Report

    Create an Automation Client for Microsoft Excel

    1.Start Microsoft Visual Studio .NET.2.On the File menu, click New, and then click Project. Select Windows Application from the Visual C# Project types. Form1 is created by

    default.

    3.Add a reference to the Microsoft Excel Object Library. To do this, follow these steps:a. On the Project menu, click Add Reference.b. On the COM tab, locate Microsoft Excel Object Library, and click Select.

    Note Microsoft Office 2003 includes Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they

    can be downloaded. For more information about Office XP PIAs, click the following article number to view the article in the

    Microsoft Knowledge Base:

    328912 Microsoft Office XP primary interop assemblies (PIAs) are available for download

    http://support.microsoft.com/kb/328912http://support.microsoft.com/kb/328912http://support.microsoft.com/kb/328912
  • 8/4/2019 Create an Automation Client for Microsoft Excel

    6/14

    c. Click OKin the Add References dialog box to accept your selections. If you are prompted to generate wrappers for thelibraries that you selected, click Yes.

    On the View menu, select Toolbox to display the toolbox, and then add a button to Form1.

    Double-click Button1. The code window for the form appears.

    In the code window, replace the following codeprivate void button1_Click(object sender, System.EventArgs e)

    {

    }

    with:

    private void button1_Click(object sender, System.EventArgs e)

    {

    Excel.Application oXL;

    Excel._Workbook oWB;

    Excel._Worksheet oSheet;

    Excel.Range oRng;

    try

    {

    //Start Excel and get Application object.

    oXL = new Excel.Application();

    oXL.Visible = true;

    //Get a new workbook.

    oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));oSheet = (Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.

    oSheet.Cells[1, 1] = "First Name";

    oSheet.Cells[1, 2] = "Last Name";

    oSheet.Cells[1, 3] = "Full Name";

    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.

    oSheet.get_Range("A1", "D1").Font.Bold = true;

    oSheet.get_Range("A1", "D1").VerticalAlignment =

    Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.

    string[,] saNames = new string[5,2];

    saNames[ 0, 0] = "John";

    saNames[ 0, 1] = "Smith";saNames[ 1, 0] = "Tom";

    saNames[ 1, 1] = "Brown";

    saNames[ 2, 0] = "Sue";

    saNames[ 2, 1] = "Thomas";

    saNames[ 3, 0] = "Jane";

    saNames[ 3, 1] = "Jones";

    saNames[ 4, 0] = "Adam";

    saNames[ 4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).

    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).

    oRng = oSheet.get_Range("C2", "C6");

    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.

    oRng = oSheet.get_Range("D2", "D6");

    oRng.Formula = "=RAND()*100000";oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.

    oRng = oSheet.get_Range("A1", "D1");

    oRng.EntireColumn.AutoFit();

    //Manipulate a variable number of columns for Quarterly Sales Data.

    DisplayQuarterlySales(oSheet);

    //Make sure Excel is visible and give the user control

    //of Microsoft Excel's lifetime.

    oXL.Visible = true;

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    7/14

    oXL.UserControl = true;

    }

    catch( Exception theException )

    {

    String errorMessage;

    errorMessage = "Error: ";

    errorMessage = String.Concat( errorMessage, theException.Message );

    errorMessage = String.Concat( errorMessage, " Line: " );

    errorMessage = String.Concat( errorMessage, theException.Source );

    MessageBox.Show( errorMessage, "Error" );

    }

    }

    private void DisplayQuarterlySales(Excel._Worksheet oWS)

    {

    Excel._Workbook oWB;

    Excel.Series oSeries;

    Excel.Range oResizeRange;

    Excel._Chart oChart;

    String sMsg;

    int iNumQtrs;

    //Determine how many quarters to display data for.

    for( iNumQtrs = 4; iNumQtrs >= 2; iNumQtrs--)

    {

    sMsg = "Enter sales data for ";

    sMsg = String.Concat( sMsg, iNumQtrs );

    sMsg = String.Concat( sMsg, " quarter(s)?");

    DialogResult iRet = MessageBox.Show( sMsg, "Quarterly Sales?",

    MessageBoxButtons.YesNo );

    if (iRet == DialogResult.Yes)

    break;

    }

    sMsg = "Displaying data for ";

    sMsg = String.Concat( sMsg, iNumQtrs );

    sMsg = String.Concat( sMsg, " quarter(s)." );

    MessageBox.Show( sMsg, "Quarterly Sales" );

    //Starting at E1, fill headers for the number of columns selected.

    oResizeRange = oWS.get_Range("E1", "E1").get_Resize( Missing.Value, iNumQtrs);

    oResizeRange.Formula = "=\"Q\" & COLUMN()-4 & CHAR(10) & \"Sales\"";

    //Change the Orientation and WrapText properties for the headers.

    oResizeRange.Orientation = 38;

    oResizeRange.WrapText = true;

    //Fill the interior color of the headers.

    oResizeRange.Interior.ColorIndex = 36;

    //Fill the columns with a formula and apply a number format.

    oResizeRange = oWS.get_Range("E2", "E6").get_Resize( Missing.Value, iNumQtrs);

    oResizeRange.Formula = "=RAND()*100";

    oResizeRange.NumberFormat = "$0.00";

    //Apply borders to the Sales data and headers.

    oResizeRange = oWS.get_Range("E1", "E6").get_Resize( Missing.Value, iNumQtrs);

    oResizeRange.Borders.Weight = Excel.XlBorderWeight.xlThin;

    //Add a Totals formula for the sales data and apply a border.

    oResizeRange = oWS.get_Range("E8", "E8").get_Resize( Missing.Value, iNumQtrs);

    oResizeRange.Formula = "=SUM(E2:E6)";

    oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).LineStyle= Excel.XlLineStyle.xlDouble;

    oResizeRange.Borders.get_Item( Excel.XlBordersIndex.xlEdgeBottom ).Weight

    = Excel.XlBorderWeight.xlThick;

    //Add a Chart for the selected data.

    oWB = (Excel._Workbook)oWS.Parent;

    oChart = (Excel._Chart)oWB.Charts.Add( Missing.Value, Missing.Value,

    Missing.Value, Missing.Value );

    //Use the ChartWizard to create a new chart from the selected data.

    oResizeRange = oWS.get_Range("E2:E6", Missing.Value ).get_Resize(

    Missing.Value, iNumQtrs);

    oChart.ChartWizard( oResizeRange, Excel.XlChartType.xl3DColumn, Missing.Value,

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    8/14

    Excel.XlRowCol.xlColumns, Missing.Value, Missing.Value, Missing.Value,

    Missing.Value, Missing.Value, Missing.Value, Missing.Value );

    oSeries = (Excel.Series)oChart.SeriesCollection(1);

    oSeries.XValues = oWS.get_Range("A2", "A6");

    for( int iRet = 1; iRet

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    9/14

    a. On the NET tab, locate ADODB, and then click Select.Note In Visual Studio 2005, you do not have to click Select.

    b. On the COM tab, locate Microsoft Excel 10.0 Object Library or Microsoft Excel 11.0 Object Library, and then click Select.Note In Visual Studio 2005, you do not have to click Select.

    Note If you are using Microsoft Excel 2002 and you have not already done so, Microsoft recommends that you download

    and then install the Microsoft Office XP Primary Interop Assemblies (PIAs). For more information about Office XP PIAs, clickthe following article number to view the article in the Microsoft Knowledge Base:

    328912 INFO: Microsoft Office XP PIAs Are Available for Download

    c. In the Add References dialog box, click OKto accept your selections.Add a Combo Box control and a Button control to Form1.

    Add event handlers for the Form Load event and the Clickevents of the Button control:

    . In design view for Form1.cs, double-click Form1.The handler for the Form's Load event is created and appears in Form1.cs.

    a. On the View menu, click Designer to switch to design view.b. Double-click Button1.

    The handler for the button's Clickevent is created and appears in Form1.cs.

    In Form1.cs, replace the following code:private void Form1_Load(object sender, System.EventArgs e)

    {

    }

    private void button1_Click(object sender, System.EventArgs e)

    {

    }

    with:

    // Excel object references.

    private Excel.Application m_objExcel = null;

    private Excel.Workbooks m_objBooks = null;

    private Excel._Workbook m_objBook = null;

    private Excel.Sheets m_objSheets = null;private Excel._Worksheet m_objSheet = null;

    private Excel.Range m_objRange = null;

    private Excel.Font m_objFont = null;

    private Excel.QueryTables m_objQryTables = null;

    private Excel._QueryTable m_objQryTable = null;

    // Frequenty-used variable for optional arguments.

    private object m_objOpt = System.Reflection.Missing.Value;

    // Paths used by the sample code for accessing and storing data.

    private object m_strSampleFolder = "C:\\ExcelData\\";

    private string m_strNorthwind = "C:\\Program Files\\Microsoft

    Office\\Office10\\Samples\\Northwind.mdb";

    private void Form1_Load(object sender, System.EventArgs e)

    {

    comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

    comboBox1.Items.AddRange(new object[]{

    "Use Automation to Transfer Data Cell by Cell ",

    "Use Automation to Transfer an Array of Data to a Range

    on a Worksheet ",

    "Use Automation to Transfer an ADO Recordset to a

    Worksheet Range ",

    "Use Automation to Create a QueryTable on a Worksheet",

    "Use the Clipboard",

    "Create a Delimited Text File that Excel Can Parse into

    Rows and Columns",

    "Transfer Data to a Worksheet Using ADO.NET "});

    comboBox1.SelectedIndex = 0;

    button1.Text = "Go!";

    http://support.microsoft.com/kb/328912http://support.microsoft.com/kb/328912http://support.microsoft.com/kb/328912
  • 8/4/2019 Create an Automation Client for Microsoft Excel

    10/14

    }

    private void button1_Click(object sender, System.EventArgs e)

    {

    switch (comboBox1.SelectedIndex)

    {

    case 0 : Automation_CellByCell(); break;

    case 1 : Automation_UseArray(); break;

    case 2 : Automation_ADORecordset(); break;

    case 3 : Automation_QueryTable(); break;case 4 : Use_Clipboard(); break;

    case 5 : Create_TextFile(); break;

    case 6 : Use_ADONET(); break;

    }

    //Clean-up

    m_objFont = null;

    m_objRange = null;

    m_objSheet = null;

    m_objSheets = null;

    m_objBooks = null;

    m_objBook = null;

    m_objExcel = null;

    GC.Collect();

    }

    private void Automation_CellByCell()

    {// Start a new workbook in Excel.

    m_objExcel = new Excel.Application();

    m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;

    m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));

    // Add data to cells of the first worksheet in the new workbook.

    m_objSheets = (Excel.Sheets)m_objBook.Worksheets;

    m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));

    m_objRange = m_objSheet.get_Range("A1", m_objOpt);

    m_objRange.set_Value(m_objOpt,"Last Name");

    m_objRange = m_objSheet.get_Range("B1", m_objOpt);

    m_objRange.set_Value(m_objOpt,"First Name");

    m_objRange = m_objSheet.get_Range("A2", m_objOpt);

    m_objRange.set_Value(m_objOpt,"Doe");

    m_objRange = m_objSheet.get_Range("B2", m_objOpt);

    m_objRange.set_Value(m_objOpt,"John");

    // Apply bold to cells A1:B1.

    m_objRange = m_objSheet.get_Range("A1", "B1");

    m_objFont = m_objRange.Font;

    m_objFont.Bold=true;

    // Save the workbook and quit Excel.

    m_objBook.SaveAs(m_strSampleFolder + "Book1.xls", m_objOpt, m_objOpt,

    m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,

    m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);

    m_objBook.Close(false, m_objOpt, m_objOpt);

    m_objExcel.Quit();

    }

    private void Automation_UseArray()

    {

    // Start a new workbook in Excel.

    m_objExcel = new Excel.Application();

    m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;

    m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));m_objSheets = (Excel.Sheets)m_objBook.Worksheets;

    m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));

    // Create an array for the headers and add it to cells A1:C1.

    object[] objHeaders = {"Order ID", "Amount", "Tax"};

    m_objRange = m_objSheet.get_Range("A1", "C1");

    m_objRange.set_Value(m_objOpt,objHeaders);

    m_objFont = m_objRange.Font;

    m_objFont.Bold=true;

    // Create an array with 3 columns and 100 rows and add it to

    // the worksheet starting at cell A2.

    object[,] objData = new Object[100,3];

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    11/14

    Random rdm = new Random((int)DateTime.Now.Ticks);

    double nOrderAmt, nTax;

    for(int r=0;r

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    12/14

    private void Automation_QueryTable()

    {

    // Start a new workbook in Excel.

    m_objExcel = new Excel.Application();

    m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;

    m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));

    // Create a QueryTable that starts at cell A1.

    m_objSheets = (Excel.Sheets)m_objBook.Worksheets;m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));

    m_objRange = m_objSheet.get_Range("A1", m_objOpt);

    m_objQryTables = m_objSheet.QueryTables;

    m_objQryTable = (Excel._QueryTable)m_objQryTables.Add(

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

    m_strNorthwind + ";", m_objRange, "Select * From Orders");

    m_objQryTable.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;

    m_objQryTable.Refresh(false);

    // Save the workbook and quit Excel.

    m_objBook.SaveAs(m_strSampleFolder + "Book4.xls", m_objOpt, m_objOpt,

    m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt,

    m_objOpt, m_objOpt, m_objOpt);

    m_objBook.Close(false, m_objOpt, m_objOpt);

    m_objExcel.Quit();

    }

    private void Use_Clipboard(){

    // Copy a string to the clipboard.

    string sData = "FirstName\tLastName\tBirthdate\r\n" +

    "Bill\tBrown\t2/5/85\r\n" +

    "Joe\tThomas\t1/1/91";

    System.Windows.Forms.Clipboard.SetDataObject(sData);

    // Start a new workbook in Excel.

    m_objExcel = new Excel.Application();

    m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;

    m_objBook = (Excel._Workbook)(m_objBooks.Add(m_objOpt));

    // Paste the data starting at cell A1.

    m_objSheets = (Excel.Sheets)m_objBook.Worksheets;

    m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));

    m_objRange = m_objSheet.get_Range("A1", m_objOpt);

    m_objSheet.Paste(m_objRange, false);

    // Save the workbook and quit Excel.

    m_objBook.SaveAs(m_strSampleFolder + "Book5.xls", m_objOpt, m_objOpt,

    m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt,

    m_objOpt, m_objOpt, m_objOpt);

    m_objBook.Close(false, m_objOpt, m_objOpt);

    m_objExcel.Quit();

    }

    private void Create_TextFile()

    {

    // Connect to the data source.

    System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(

    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + m_strNorthwind + ";");

    objConn.Open();

    // Execute a command to retrieve all records from the Employees table.

    System.Data.OleDb.OleDbCommand objCmd = new System.Data.OleDb.OleDbCommand(

    "Select * From Employees", objConn);System.Data.OleDb.OleDbDataReader objReader;

    objReader = objCmd.ExecuteReader();

    // Create the FileStream and StreamWriter object to write

    // the recordset contents to file.

    System.IO.FileStream fs = new System.IO.FileStream(

    m_strSampleFolder + "Book6.txt", System.IO.FileMode.Create);

    System.IO.StreamWriter sw = new System.IO.StreamWriter(

    fs, System.Text.Encoding.Unicode);

    // Write the field names (headers) as the first line in the text file.

    sw.WriteLine(objReader.GetName(0) + "\t" + objReader.GetName(1) +

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    13/14

    "\t" + objReader.GetName(2) + "\t" + objReader.GetName(3) +

    "\t" + objReader.GetName(4) + "\t" + objReader.GetName(5));

    // Write the first six columns in the recordset to a text file as

    // tab-delimited.

    while(objReader.Read())

    {

    for(int i=0;i

  • 8/4/2019 Create an Automation Client for Microsoft Excel

    14/14

    " values ('Joe', 'Thomas')";

    objCmd.ExecuteNonQuery();

    // Close the connection.

    objConn.Close();

    }

    } // End Class}// End namespace

    Note You must change the code in Visual Studio 2005. By default, Visual C# adds one form to the project when you create a Windows

    Forms project. The form is named Form1. The two files that represent the form are named Form1.cs and Form1.designer.cs. You write

    the code in Form1.cs. The Form1.designer.cs file is where the Windows Forms Designer writes the code that implements all the actions

    that you performed by dragging and dropping controls from the Toolbox.

    For more information about the Windows Forms Designer in Visual C# 2005, visit the following Microsoft Developer Network (MSDN)

    Web site:

    http://msdn2.microsoft.com/en-us/library/ms173077.aspx

    Note If you did not install Office to the default folder (C:\Program Files\Microsoft Office), modify the m_strNorthwind constant in the

    code sample to match your installation path for Northwind.mdb.

    Add the following to the Using directives in Form1.cs:using System.Reflection;

    using System.Runtime.InteropServices;

    using Excel = Microsoft.Office.Interop.Excel;

    http://msdn2.microsoft.com/en-us/library/ms173077.aspxhttp://msdn2.microsoft.com/en-us/library/ms173077.aspxhttp://msdn2.microsoft.com/en-us/library/ms173077.aspx