如何使用OLEDB将所选数据粘贴到另一个Excel工作表中?

时间:2010-12-11 10:27:00

标签: c# .net excel oledb

我有2张Excel表格。我的要求是,我必须将所有数据从一张Excel表格复制到另一张表格。下面是相同的代码片段,下面的代码是在Excel中将所有数据从一个工作表复制粘贴到另一个工作表,但它没有粘贴A1范围内的数据。

我希望将选定的数据粘贴到从第1行开始的另一个Excel工作表中。此外,我想在每次单击按钮时删除并插入新数据,而不是附加到同一按钮。请帮忙。

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());
            }

        }

    }
}

1 个答案:

答案 0 :(得分:0)

但它没有粘贴A1范围内的数据,因为第一行被认为是表格(表格)的标题 要么手动创建它们,要么使用getRange来执行此操作。

// 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;

为了在插入之前每次执行删除命令时插入新数据 oleDb不会删除删除命令

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

检查此链接,了解有关Excel文件Here

的更多功能