【解決方法】C#でoledbを使用してExcelにデータを挿入する


すでに Excel に大量のデータが入っています。 そのExcelに新しいデータを挿入しようとしていますが、挿入できません。
20 列がありますが、Excel に新しい行 (データのみを含む列はほとんどありません) を挿入しています。

私が試したこと:

  using (OleDbConnection objConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath1 + ";Extended Properties='Excel 12.0;HDR=YES;READONLY=FALSE';"))
                {
                    objConn.Open();
                    int totalSheet = 0;
                    DataTable dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    string sheetName = string.Empty;
                    if (dt != null)
                    {
                        var tempDataTable = (from dataRow in dt.AsEnumerable()
                                             where !dataRow["TABLE_NAME"].ToString().Contains("FilterDatabase")
                                             select dataRow).CopyToDataTable();
                        dt = tempDataTable;
                        totalSheet = dt.Rows.Count;
                        sheetName = dt.Rows[0]["TABLE_NAME"].ToString();
                    }

                    OleDbCommand cmd = new OleDbCommand();
                    cmd.Connection = objConn;
                    cmd.CommandType = CommandType.Text;
                    string SqlCommand = "INSERT INTO [" + sheetName + "] (F2,F3) VALUES(3036,'Sweet')";
cmd.CommandText = SqlCommand;
                    cmd.ExecuteNonQuery();
}

解決策 1

Excel OleDb は ALTER TABLE コマンドをサポートしていないため、列を挿入する必要があります。

SQL INSERT コマンドは列をまったく処理せず、新しい行のみを挿入し、列は挿入しません。

列を挿入するには、新しい Excel ファイルを生成し、そこに既存のデータと挿入したデータを入力する必要があります。

新しい行を INSERT して、20 列のうち 2 列のデータのみを提供しようとしている場合は、試行したときに何が起こるか、また失敗したことをどのように知るかについて、より詳細に説明する必要があります。 デバッガーは何を行っていることを示していますか? アプリの実行前と実行後、ファイルはどのように見えるでしょうか?

解決策 2

To set this permission, right click on the Excelsheet folder (or whichever other folder you have put the file in) and select Properties. Look for the Sharing tab. Click share button and give read and write permission to every one name then click share button. That's it. You are done. Now that will work. working for me.

コメント

タイトルとURLをコピーしました