开发者

How can I paste selected data into another Excel sheet using OLEDB?

开发者 https://www.devze.com 2023-01-29 20:13 出处:网络
I have 2 Excel sheets. My requirement is, I have to copy all the data from one Excel sheet to another. Below is code snippet for the same, below code is copying and pasting all the data from one sheet

I have 2 Excel sheets. My requirement is, I have to copy all the data from one Excel sheet to another. Below is code snippet for the same, below code is copying and pasting all the data from one sheet to another in Excel, but its not pasting the data from A1 range.

I want the selected data to be pasted in another Excel sheet starting from 1st row. Also, I want to delete and insert fresh data every time the button is clicked, instead of appending into the same. Please help.

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.Data.Common;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace TestExcelSheet
{
    public partial class Form1 : Form
    {
        string path = @"C:\Users\Bhawesh\Documents\Visual Studio 2010\Projects\TestExcelSheet\DataValidationTest.xlsx";
        string pathdestination = @"C:\Users\Bhawesh\Documents\Visual Studio 2010\Projects\TestExcelSheet\DataValidationTest - updated.xlsx";


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //Source Path
                string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
                DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
                DbDataAdapter adapter = factory.CreateDataAdapter();
                DbCommand selectCommand = factory.CreateCommand();
                selectCommand.CommandText = "SELECT [Job Code], [Job Name],Format([Start Date],'MM-DD-YYYY') as [Start Date], Format([End Date],'MM-DD-YYYY') as [End Date] FROM [Job$]";
                DbConnection connection = factory.CreateConnection();
                connection.ConnectionString = connectionString;
                selectCommand.Connection = connection;
                adapter.SelectCommand = selectCommand;
                DataSet Job = new DataSet();
                adapter.Fill(Job);
                for (int iRowCount = 0; iRowCount <= Job.Tables[0].Rows.Count; iRowCount++)
                {

                        string JobCode = "";
                        string JobName = "";
                        string StartDate = "";
                        string EndDate = "";
                        JobCode = Job.Tables[0].Rows[iRowCount]["Job Code"].ToString().Trim();
                        JobName = Job.Tables[0].Rows[iRowCount]["Job Name"].ToString().Trim();
                        StartDate = Job.Tables[0].Rows[iRowCount]["Start Date"].ToString().Trim();
                        EndDate = Job.Tables[0].Rows[iRowCount]["End Date"].ToString().Trim();

                        //Destination Path
                        string connectionStringdest = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathdestination + ";Extended Properties=Excel 12.0;";
                        DbProviderFactory factorydest = DbProviderFactories.GetFactory("System.Data.OleDb");
                        DbDataAdapter adapterdest = factorydest.CreateDataAdapter();
                        DbCommand insertCommand = factorydest.CreateCommand();
                        DbConnection connectiondest = factorydest.CreateConnection();
                        connectiondest.ConnectionString = connectionStringdest;
                        insertCommand.Connection = connectiondest;
                        adapterdest.InsertCommand = insertCommand;


                        if (connectiondest.State == ConnectionState.Closed)
                        {
                            connectiondest.Open();
                        }
                        if (Job.Tables.Count > 0 && Job.Tables[0].Rows.Count > 0)
                        {

                                insertCommand.CommandText = "Insert into [Job_updated$] values ('" + JobCode + "', '" + JobName + "', '" + StartDate + "', '" + EndDate + "') ";
                                //insertCommand.CommandText = "UPDATE [Job_updated$E1:E1] SET F1='MyNewCol';";
                                insertCommand.ExecuteNonQuery();
                            insertCommand.Dispose();
                        }
                        connectiondest.Close();
                        dataGridView1.DataSource = Job.Tables[0]开发者_开发技巧.DefaultView;
                    }
                }

            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

    }
}


but its not pasting the data from A1 range because first row is considered to be the headers for the table (sheet) either create them manually or use getRange to do that.

// 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.Value = objHeaders;

in order to insert new data each time perform a delete command before inserting oleDb does not sopport the delete command

Excel.Range ran = (Excel.Range)sheet.Rows[5, Type.Missing];
ran.Select();
ran.Delete(Excel.XlDirection.xlUp);

check this link for more functions on excel file Here

0

精彩评论

暂无评论...
验证码 换一张
取 消