在C#中使用Oledb将新值写入xls文件

时间:2019-02-26 16:34:55

标签: c# excel oledbconnection oledbcommand

我正在构建一个简单的程序,该程序读取一个具有更多工作表的XLS文件,其中一个工作表具有一个列,并且我想复制第一工作表中所有工作表的第一列,因此将第二工作表的第一列插入到第一张纸的第二列,等等。

这是代码:

private void Button_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var FD = new System.Windows.Forms.OpenFileDialog();
                DialogResult dr = FD.ShowDialog();
                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    string fileToOpen = FD.FileName;

                    string szConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source = '" + fileToOpen + 
                       "';Extended Properties=\"Excel 8.0;HDR=NO;\"";


                    List<string> listaFogli = ToExcelsSheetList(fileToOpen);
                    String nomeSheet1 = listaFogli[0];
                    listaFogli.Remove(nomeSheet1);

                    //CODICE DI PROVA
                    OleDbConnection oleDbConnection = new System.Data.OleDb.OleDbConnection(szConnectionString);
                    oleDbConnection.Open();
                    OleDbCommand oledbCmd = new OleDbCommand();
                    oledbCmd.Connection = oleDbConnection;

                    oledbCmd.CommandText = "SELECT * FROM [" + nomeSheet1 + "$]";
                    DataTable dtDataTable = new DataTable();
                    using (OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(oledbCmd))
                        oledbAdapter.Fill(dtDataTable);

                    int nColonna = 2;

                    foreach(string nomeSheet in listaFogli)
                    {
                        int stRowNumber = 1;
                        List<string> newRows = ReadRowBySheet(fileToOpen, nomeSheet);

                        foreach(string nuovoValore in newRows)
                        {
                            String text  = nuovoValore.Replace("'", "");
                            //string stRowNumber = (dtDataTable.Rows.Count + 1).ToString();
                            string stRowID = "" + stRowNumber + ":" + nColonna+"";
                            oledbCmd.CommandText = "UPDATE [" + nomeSheet1 + "$" + stRowID + "] SET F"+nColonna+"='"+ text + "'";
                            oledbCmd.ExecuteNonQuery();

                            stRowNumber++;
                        }



                        nColonna++;

                    }


                    oleDbConnection.Close();
                    oleDbConnection.Dispose();



                }


            }
            catch (Exception exc)
            {
                Console.WriteLine("pippo");
            }
        }

如果我尝试启动此应用程序,则第二张纸的列正确插入了第一张纸的第二列,但是当我尝试将第三张纸的列插入第一张纸的第三列时,此错误:

No value specified for some necessary parameters.

0 个答案:

没有答案