C#使用Oledb datagridview更新Excel

时间:2016-05-27 03:08:51

标签: c# excel datagridview oledb

namespace PROCESS_FOLDER_V2
{
    public partial class OrganiZe : Form
    {
        public OrganiZe()
        {
            InitializeComponent();

        }


    int TotalCnt = 0;

    private void Insert(int Col1, string Col2, string Col3, string Col4, int Col5)
    {

        // MessageBox.Show("SNo: " + Col1 + "\n"+"\n" + "Material Code " + Col2 + "\n"+"\n" + "Item Text :" + Col3 +"\n"+"\n"+ "PO Text :" + Col4 + "\n"+"\n"+"PR Number :" + Col5, "OrganiZe");
        while (Col4.Contains("'"))
        {
            Col4 = Col4.Replace("'", "`");
        };
        while (Col3.Contains("'"))
        {
            Col3 = Col3.Replace("'", "`");
        };
        //File.WriteAllText("Char.txt", Col4);
        //MessageBox.Show("SNo: " + Col1 + "\n" + "\n" + "Material Code " + Col2 + "\n" + "\n" + "Item Text :" + Col3 + "\n" + "\n" + "PO Text :" + Col4 + "\n" + "\n" + "PR Number :" + Col5, "OrganiZe");

        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
        string sql = null;
        MyConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0");
        MyConnection.Open();

        myCommand.Connection = MyConnection;
        sql = "INSERT INTO [PR$]"
            + "([SNo],[MATERIAL CODE],[ITEM TEXT],[PO TEXT],[PRNo])"
            + "VALUES('" + Col1 + "','" + Col2 + "','" + Col3 + "','" + Col4 + "','" + Col5 + "')";

        myCommand.CommandText = sql;
        myCommand.ExecuteNonQuery();
        DataSet ds = new DataSet();
        OleDbDataAdapter da;
        da = new OleDbDataAdapter(myCommand);
        DataTable dt = new DataTable();
        da.Update(dt);
        // da.Fill(ds);
        //dgPR.DataSource = ds.Tables[0];
        MyConnection.Close();

    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //  READ TEXT FILE

    string PRtext = "";
    string PRtextEdited = "";

    //***************************************************************
    private void ReadPDF(string getName)
    {
        string strText = null;
        PdfReader reader = new PdfReader(getName);

        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
            string s = PdfTextExtractor.GetTextFromPage(reader, page, its);
            s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
            strText = strText + s;
            // txtFilee.Text = strText;

        }

        PRtext = strText;
        reader.Close();
        //StreamWriter sw = new StreamWriter("PDFtoTEXT.txt");
        File.WriteAllText("PDFtoText.txt", PRtext);
        //sw.Close();

        string lRead;
        lRead = strText;
        txtFilee.Text = strText;

        int IndPrvPage = 0;
        int len = 113;
        //string Page = "";
        if (lRead.Contains("'")) { lRead = lRead.Replace("'", "`"); };
        int IndPage = lRead.IndexOf("Page", IndPrvPage);

        while (lRead.Contains("Page") == true)
        {
            if (lRead.Length < (lRead.IndexOf("Page", 0) + len)) { break; }

            IndPage = lRead.IndexOf("Page", IndPrvPage);

            //Page = lRead.Substring(IndPage, len);
            //string temp;
            if (IndPage > 0) { lRead = lRead.Remove(IndPage, len); };
            if (IndPage < 0) { break; };

            IndPrvPage = IndPage;
            //MessageBox.Show(Page);


        }
        //MessageBox.Show(lRead);
        File.WriteAllText("PDFtoTEXT.txt", lRead);
        PRtextEdited = lRead;
        //MessageBox.Show(PRtextEdited);
    }
    //*******************************************************







    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // FINDING AND ORGANIZING



    private void btnOrganize_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.ShowDialog();
        string NameFolder = fbd.SelectedPath;


        foreach (string getName in Directory.GetFiles(@NameFolder, "*.pdf"))
        {
            ReadPDF(getName);

            int IndInitial = 0;
            int index = 0;
            string tmp = "";

            //*****************

            tmp = PRtextEdited;

            //***********************
            ///find PR No.
            int PRNo = 0;
            int IndPRNo = 0;
            string PRNum;
            IndPRNo = tmp.IndexOf("Purchase Requisition") + 23;
            PRNum = tmp.Substring(IndPRNo, 9);
            // MessageBox.Show("Purchase Requisition No: " + PRNum, "OrganiZe");

            int Finish = 0;
            // string Zeros="000";
            string Zeros3 = "000";
            string Zeros2 = "00";
            string Zeros1 = "0";
            int N = 10;
            string ItemNo = "00000";
            string NxtItemNo = "00000";
            int Cnt = 0;
            string z = "MATERIAL DESCRIPTION & ITEM TEXT";
            int IndZ = 0;
            if ((tmp.IndexOf(z) < 0)) { z = "N & ITEM TEXT"; }
            IndZ = tmp.IndexOf(z, IndInitial) + 25;             // set starting index as MATERIAL DESCRIPTION & ITEM TEXT


            //MessageBox.Show(tmp);
            do
            {
                string txtFindPO = "Material  PO Text";
                string txtFindITEM = "Item Text";
                string txtLast = "Prepared By";
                string matCode = "";
                int indMat = 0;
                int indPO = 0, indItem = 0, indNext = 0;


                if (N < 100) { ItemNo = Zeros3 + N.ToString(); }
                if (N >= 100 && N < 1000) { ItemNo = Zeros2 + N.ToString(); }
                if (N >= 1000 && N < 10000) { ItemNo = Zeros1 + N.ToString(); }

                //find first item
                string Item = ItemNo + " " + "M";

                while (tmp.IndexOf(Item, IndZ) == -1)
                {
                    N = N + 10;

                    if (N < 100) { ItemNo = Zeros3 + N.ToString(); }
                    if (N >= 100 && N < 1000) { ItemNo = Zeros2 + N.ToString(); }
                    if (N >= 1000 && N < 10000) { ItemNo = Zeros1 + N.ToString(); }
                    Item = ItemNo + " " + "M";


                }

                if (N < 90) { NxtItemNo = Zeros3 + (N + 10).ToString(); }
                if (N >= 90 && N < 990) { NxtItemNo = Zeros2 + (N + 10).ToString(); }
                if (N >= 990 && N < 9990) { NxtItemNo = Zeros1 + (N + 10).ToString(); }


                index = tmp.IndexOf(Item, IndZ);

                indMat = index;

                indPO = tmp.IndexOf(txtFindPO, index);
                if (indPO >= 0) { indPO = indPO + 43; };


                indItem = tmp.IndexOf(txtFindITEM, index);
                if (indItem >= 0) { indItem = indItem + 9; };
                //find next item
                string NxtItem = NxtItemNo + " " + "M";


                while (tmp.IndexOf(NxtItem, IndZ) == -1)
                {
                    N = N + 10;

                    if (N < 90) { NxtItemNo = Zeros3 + (N + 10).ToString(); }
                    if (N >= 90 && N < 990) { NxtItemNo = Zeros2 + (N + 10).ToString(); }
                    if (N >= 990 && N < 9990) { NxtItemNo = Zeros1 + (N + 10).ToString(); }

                    NxtItem = NxtItemNo + " " + "M";

                    indNext = tmp.IndexOf(NxtItem, index);
                    if (N >= 990)
                    {
                        int IndLast = 0;
                        IndLast = tmp.IndexOf("Prepared By", 0);
                        IndLast = tmp.IndexOf(txtLast, index);
                        indNext = IndLast;
                        Finish++;
                        break;
                    };


                }

                if (Finish < 1)
                {
                    if (N < 90) { NxtItemNo = Zeros3 + (N + 10).ToString(); }
                    if (N >= 90 && N < 990) { NxtItemNo = Zeros2 + (N + 10).ToString(); }
                    if (N >= 990 && N < 9990) { NxtItemNo = Zeros1 + (N + 10).ToString(); }

                    NxtItem = NxtItemNo + " " + "M";
                    indNext = tmp.IndexOf(NxtItem, index);

                }


                //**********************

                int lenITEM = 0;
                int lenPO = 0;
                string POtxt = "";
                string ITEMtxt = "";


                if (indPO > 0 && indItem > 0) { lenPO = (indItem - indPO) - 9; };
                if (indPO > 0 && indItem < 0) { lenPO = indNext - indPO - 9; };

                if (indItem > 0 && indNext > 0) { lenITEM = (indNext - indItem); }


                if (lenPO > 255) { lenPO = 255; }
                if (lenPO < 0) { lenPO = 0; }

                matCode = tmp.Substring(indMat + 6, 11);                  //material code


                if (indPO > 0) { POtxt = tmp.Substring(indPO, lenPO); };                    //MessageBox.Show(POtxt);

                if (lenITEM > 255) { lenITEM = 255; }
                if (lenITEM < 0) { lenITEM = 0; }

                if (indItem > 0) { ITEMtxt = tmp.Substring(indItem, lenITEM); };              //MessageBox.Show(ITEMtxt);


                Cnt = Cnt + 1;

                PRNo = Convert.ToInt32(PRNum);

                Insert(Cnt, matCode, ITEMtxt, POtxt, PRNo);   // INSERT INTO TABLE


                if (Finish == 1) break;

                N = N + 10;


            } while (N <= 990);
            //sr.Close();




            TotalCnt++;



            //  MessageBox.Show("All Organized", "OrganiZe");
            // MessageBox.Show("Total Items Nos: " + Cnt.ToString(), "OrganiZe");

        }

        MessageBox.Show("All completed.  " + "\n" + "\n" + "No of PR processed: " + TotalCnt.ToString(), "OrganiZe");
    }
















    private void btnShow_Click(object sender, EventArgs e)
    {
        string connetionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0";

        string sql = "SELECT * FROM [PR$]";
        OleDbConnection connection = new OleDbConnection(connetionString);
        connection.ConnectionString = connetionString;
        adap = new OleDbDataAdapter(sql, connection);
        DataSet ds = new DataSet();
        connection.Open();
        adap.Fill(ds);
        dgPR.DataSource = ds.Tables[0];
        connection.Close();
    }











    private void txtFilter_TextChanged(object sender, EventArgs e)
    {
        conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0";
        conn.Open();
        OleDbCommand cmd = conn.CreateCommand();
        cmd.CommandType = CommandType.Text;
        //cmd.CommandText = "SELECT * FROM [PR$] WHERE [MATERIAL CODE] LIKE ('" + txtFilter.Text + "%')";

        /*  if (cbFilter.SelectedItem.ToString() == "ITEM TEXT")
          {
              cmd.CommandText = "SELECT * FROM [PR$] WHERE [ITEM TEXT] LIKE ('%" + txtFilter.Text + "%')";
          }
          if (cbFilter.SelectedItem.ToString() == "PO TEXT")
          {
              cmd.CommandText = "SELECT * FROM [PR$] WHERE [PO TEXT] LIKE ('%" + txtFilter.Text + "%')";
          }
          if (cbFilter.SelectedItem.ToString() == "MATERIAL CODE")
          {
              cmd.CommandText = "SELECT * FROM [PR$] WHERE [MATERIAL CODE] LIKE ('%" + txtFilter.Text + "%')";
          }
          if (cbFilter.SelectedItem.ToString() == "PRNo")
          {
              cmd.CommandText = "SELECT * FROM [PR$] WHERE [PRNo] LIKE ('%" + txtFilter.Text + "%')";
          }

         */

        cmd.CommandText = "SELECT * FROM [PR$] WHERE [ITEM TEXT] LIKE ('%" + txtFilter.Text + "%')";
        cmd.ExecuteNonQuery();
        //OleDbDataAdapter adap = new OleDbDataAdapter("SELECT * FROM [PR$] LIKE '"+txtFilter.Text+"%'", conn);
        DataTable dt = new DataTable();
        adap = new OleDbDataAdapter(cmd);
        adap.Fill(dt);
        dgPR.DataSource = dt;
        //MessageBox.Show(dt.Rows[0][0].ToString());
    }

    //OleDbDataAdapter adap = new OleDbDataAdapter();
    // DataSet ds = new DataSet(@"PRTEXT.XLS");
    // string sql;

    //DataTable dt = new DataTable();

    // OleDbConnection conn = new OleDbConnection();
    // private string contents;
    // OleDbCommandBuilder builder; 

















    // }



    private void btnUpdate_Click(object sender, EventArgs e)
    {

        conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0";
        conn.Open();



        string xlsSheet = "PR$";
        string name = ds.Tables[0].Rows[0][0].ToString();
        DataTable dt = (DataTable)dgPR.DataSource;

        string changeColumns = "";
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            changeColumns += Table.ColumnName[i] + "=@" + Table.ColumnName[i];
            if (Table.ColumnName.Count - 1 != i)
                changeColumns += ",";
        }

        adap.UpdateCommand = new OleDbCommand("UPDATE [" + xlsSheet + "]  SET " + changeColumns +
                                                            " WHERE " + Table.ColumnName[PrimaryColumnIndex] + " = @" + Table.ColumnName[PrimaryColumnIndex], conn);
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            adap.UpdateCommand.Parameters.Add("@" + Table.ColumnName[i], OleDbType.Char, 255).SourceColumn = Table.ColumnName[i];
        }
        foreach (int row in ListOfValues.Keys)
        {
            Table tbl = ListOfValues[row];
            ds.Tables[0].Rows[row][Table.ColumnName[PrimaryColumnIndex]] = ds.Tables[0].Rows[row][PrimaryColumnIndex];
            for (int i = 0; i < tbl.Value.Count; i++)
            {
                ds.Tables[0].Rows[row][Table.ColumnName[tbl.col[i]]] = tbl.Value[i];
            }
            //adap.UpdateCommand.ExecuteNonQuery();
            adap.Update(ds.Tables[0]);
        }
        conn.Close();
        MessageBox.Show("Updated");
    }


    bool isFormLoad = false;
    int PrimaryColumnIndex = 4;
    OleDbDataAdapter adap;
    DataSet ds;
    OleDbConnection conn;
    OleDbCommandBuilder builder;


    Dictionary<int, Table> ListOfValues = new Dictionary<int, Table>();

    public class Table
    {
        public List<string> Value { get; set; }
        public List<int> col { get; set; }
        public static List<string> ColumnName;
    }


    private void OrganiZe_Load_1(object sender, EventArgs e)
    {

        conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0";
        conn.Open();
        adap = new OleDbDataAdapter("SELECT * FROM [PR$]", conn);
        ds = new DataSet();
        adap.Fill(ds, "PR");
        Table.ColumnName = new List<string>();
        foreach (DataColumn str in ds.Tables[0].Columns)
        {
            Table.ColumnName.Add(str.ColumnName);
        }
        dgPR.DataSource = ds.Tables[0];
        conn.Close();
        dgPR.Columns[PrimaryColumnIndex].ReadOnly = true;
        dgPR.RowValidated += new DataGridViewCellEventHandler(dgPR_RowValidated);
        isFormLoad = true;

    }


    private void dgPR_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        if (isFormLoad)
        {
            Table tbl = new Table();
            DataGridView dgv = (DataGridView)sender;
            tbl.Value = new List<string>();
            tbl.col = new List<int>();
            for (int i = 1; i < dgv.ColumnCount; i++)
            {
                tbl.Value.Add(dgv.Rows[e.RowIndex].Cells[i].Value.ToString());
                tbl.col.Add(i);
            }

            if (ListOfValues.Keys.Contains(e.RowIndex))
            {
                ListOfValues[e.RowIndex] = tbl;
            }
            else
                ListOfValues.Add(e.RowIndex, tbl);
        }
    }







}

}

Code fucntion insert在excel中运行良好。但是代码更新不起作用。所以我试着一步一步地运行..在adap.update(ds.tables [0])执行除了停止,在UPDATE语句中声明语法错误。

exception: System.Data.OleDb.OleDbException was unhandled
HResult=-2147217900
Message=Syntax error in UPDATE statement.
Source=Microsoft Office Access Database Engine
ErrorCode=-2147217900

2 个答案:

答案 0 :(得分:0)

假设您的工作表PR

中有以下数据
FirstName LastName     Age
johny     Depp         55
Statham   John         45
Diana     bantley      35

然后您必须在按钮单击中查看此代码以获取更新

 conn= new OleDbConnection();
    conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0";
    conn.Open();
    string xlsSheet = "PR$";
    adap.UpdateCommand = new OleDbCommand("UPDATE [" + xlsSheet + "] SET FirstName = ?, LastName = ?, Age = ?" +

                                                    " WHERE FirstName = "+ ds.Tables[0].Rows[0][0], conn);

    adap.UpdateCommand.Parameters.Add("@FirstName", OleDbType.Char, 255).SourceColumn = "FirstName";

        adap.UpdateCommand.Parameters.Add("@LastName", OleDbType.Char, 255).SourceColumn = "LastName";

        adap.UpdateCommand.Parameters.Add("@Age", OleDbType.Char, 255).SourceColumn = "Age";

        //// Updates the first row

        ds.Tables[0].Rows[0]["FirstName"] = "john";

        ds.Tables[0].Rows[0]["LastName"] = "Statham";

        ds.Tables[0].Rows[0]["Age"] = "55";


        adap.Update(ds.Tables[0]);
        conn.Close();
    MessageBox.Show("Updated");

我们给出整个查询更新以及在哪里条件我们传递第一个索引的值(i-e(零索引)值),这个更新值成功地通过改变我们的数据DataTable零索引行。

答案 1 :(得分:0)

以下是您所提供条件的全部工作,请从您的最终检查。

private void btnUpdate_Click(object sender, EventArgs e)
    {
        conn.Open();
        string xlsSheet = "PR$";
        string name = ds.Tables[0].Rows[0][0].ToString();
        DataTable dt = (DataTable)dgPR.DataSource;

        string changeColumns = "";
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            changeColumns += Table.ColumnName[i] + "=@" + Table.ColumnName[i];
            if (Table.ColumnName.Count - 1 != i)
                changeColumns += ",";
        }

        adap.UpdateCommand = new OleDbCommand("UPDATE [" + xlsSheet + "]  SET " + changeColumns +
                                                            " WHERE " + Table.ColumnName[PrimaryColumnIndex] + " = @" + Table.ColumnName[PrimaryColumnIndex], conn);
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            adap.UpdateCommand.Parameters.Add("@" + Table.ColumnName[i], OleDbType.Char, 255).SourceColumn = Table.ColumnName[i];
        }
        foreach (int row in ListOfValues.Keys)
        {
            Table tbl = ListOfValues[row];
            ds.Tables[0].Rows[row][Table.ColumnName[PrimaryColumnIndex]] = ds.Tables[0].Rows[row][PrimaryColumnIndex];
            for (int i = 0; i < tbl.Value.Count; i++)
            {
                ds.Tables[0].Rows[row][Table.ColumnName[tbl.col[i]]] = tbl.Value[i];
            }

            adap.Update(ds.Tables[0]);
        }
        conn.Close();
        MessageBox.Show("Updated");
    }


    bool isFormLoad = false;
    int PrimaryColumnIndex = 0;
    OleDbDataAdapter adap;
    DataSet ds;
    OleDbConnection conn;
    OleDbCommandBuilder builder;


    Dictionary<int, Table> ListOfValues = new Dictionary<int, Table>();

    public class Table
    {
        public List<string> Value { get; set; }
        public List<int> col { get; set; }
        public static List<string> ColumnName;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        conn = new OleDbConnection();
        conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\PRTEXT.xls;Extended Properties=Excel 8.0";
        conn.Open();
        adap = new OleDbDataAdapter("SELECT * FROM [PR$]", conn);
        ds = new DataSet();
        adap.Fill(ds, "PR");
        Table.ColumnName = new List<string>();
        foreach (DataColumn str in ds.Tables[0].Columns)
        {
            Table.ColumnName.Add(str.ColumnName);
        }
        dgPR.DataSource = ds.Tables[0];
        conn.Close();
        dgPR.Columns[PrimaryColumnIndex].ReadOnly = true;
        dgPR.RowValidated += new DataGridViewCellEventHandler(dgPR_RowValidated);
        isFormLoad = true;

    }


    private void dgPR_RowValidated(object sender, DataGridViewCellEventArgs e)
    {
        if (isFormLoad)
        {
            Table tbl = new Table();
            DataGridView dgv = (DataGridView)sender;
            tbl.Value = new List<string>();
            tbl.col = new List<int>();
            for (int i = 1; i < dgv.ColumnCount; i++)
            {
                tbl.Value.Add(dgv.Rows[e.RowIndex].Cells[i].Value.ToString());
                tbl.col.Add(i);
            }

            if (ListOfValues.Keys.Contains(e.RowIndex))
            {
                ListOfValues[e.RowIndex] = tbl;
            }
            else
                ListOfValues.Add(e.RowIndex, tbl);
        }
    }

请在Excel文件中更改您想要更改的PrimaryColumnIndex

<强>更新
 将btnUpdate_Click替换为此内容。

   private void btnUpdate_Click(object sender, EventArgs e)
    {
        conn.Open();
        string xlsSheet = "PR$";

        DataTable dt = (DataTable)dgPR.DataSource;

        string changeColumns = "";
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            changeColumns += "[" + Table.ColumnName[i] + "]"+ "=@" + Table.ColumnName[i];
            if (Table.ColumnName.Count - 1 != i)
                changeColumns += ",";
        }

        adap.UpdateCommand = new OleDbCommand("UPDATE [" + xlsSheet + "]  SET " + changeColumns +
                                                            " WHERE " + "["+ Table.ColumnName[PrimaryColumnIndex] +
                                                            "]"+ " = @" + Table.ColumnName[PrimaryColumnIndex], conn);
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            adap.UpdateCommand.Parameters.Add("@" + Table.ColumnName[i], OleDbType.Char, 255).SourceColumn = Table.ColumnName[i];
        }
        foreach (int row in ListOfValues.Keys)
        {
            Table tbl = ListOfValues[row];
            ds.Tables[0].Rows[row][Table.ColumnName[PrimaryColumnIndex]] = ds.Tables[0].Rows[row][PrimaryColumnIndex];
            for (int i = 0; i < tbl.Value.Count; i++)
            {
                ds.Tables[0].Rows[row][Table.ColumnName[tbl.col[i]]] = tbl.Value[i];
            }

            adap.Update(ds.Tables[0]);
        }
        conn.Close();
        MessageBox.Show("Updated");
    }

更新2:
抛出错误因为,在Feilds Name之间的查询中不支持 Space
再次从以下代码

更新btnUpdate_Click
private void btnUpdate_Click(object sender, EventArgs e)
    {
        conn.Open();
        string xlsSheet = "PR$";

        DataTable dt = (DataTable)dgPR.DataSource;

        string changeColumns = "";
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            changeColumns += "[" + Table.ColumnName[i] + "]"+ "=@" + Table.ColumnName[i].Replace(' ','_');
            if (Table.ColumnName.Count - 1 != i)
                changeColumns += ",";
        }

        adap.UpdateCommand = new OleDbCommand("UPDATE [" + xlsSheet + "]  SET " + changeColumns +
                                                            " WHERE " + "["+ Table.ColumnName[PrimaryColumnIndex] +
                                                            "]"+ " = @" + Table.ColumnName[PrimaryColumnIndex].Replace(' ','_'), conn);
        for (int i = 0; i < Table.ColumnName.Count; i++)
        {
            adap.UpdateCommand.Parameters.Add("@" + Table.ColumnName[i].Replace(' ','_'), OleDbType.Char, 255).SourceColumn = Table.ColumnName[i];
        }
        foreach (int row in ListOfValues.Keys)
        {
            Table tbl = ListOfValues[row];
            ds.Tables[0].Rows[row][Table.ColumnName[PrimaryColumnIndex]] = ds.Tables[0].Rows[row][PrimaryColumnIndex];
            for (int i = 0; i < tbl.Value.Count; i++)
            {
                ds.Tables[0].Rows[row][Table.ColumnName[tbl.col[i]]] = tbl.Value[i];
            }

            adap.Update(ds.Tables[0]);
        }
        conn.Close();
        MessageBox.Show("Updated");
    }