【问题标题】:Updating cells using dataset read from xls file and save to CSV file使用从 xls 文件读取的数据集更新单元格并保存到 CSV 文件
【发布时间】:2018-11-14 20:21:05
【问题描述】:

谁能告诉我为什么这个更新程序不起作用?我想从 XLS 读取数据到数据集,它工作得很好,但 UPDATE 根本不起作用。没有错误,没有变化,就像它不存在一样。该文件创建但值只是原始 xls 的副本。

xls sheet 格式很简单,一栏:id 1 2 3

       string string_conn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\name.xls;Extended Properties='Excel 8.0;HDR=Yes;'";

        OleDbConnection conn = new OleDbConnection(string_conn);
        conn.Open();

        DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        string[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        foreach (DataRow row in dt.Rows)
        {
            excelSheets[i] = row["TABLE_NAME"].ToString();
            i++;
        }

        comboBox1.DataSource = excelSheets;
        string xlsSheet = comboBox1.SelectedItem.ToString();

        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
        DataSet dataset = new DataSet();
        adapter.Fill(dataset);

        adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = " + tbox1.Text + " WHERE id = " + tbox2.Text + "", conn);
        adapter.UpdateCommand.Parameters.Add("@id", OleDbType.Char, 255).SourceColumn = "id";
        adapter.UpdateCommand.Parameters.Add("@Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;

        adapter.Update(dataset);
        dataset.AcceptChanges();


        DataTable dtable = new DataTable();
        dtable = dataset.Tables[0];


        StringBuilder str = new StringBuilder();
        foreach (DataRow dr in dtable.Rows)
        {
            foreach (var field in dr.ItemArray)
            {
                str.Append(field.ToString());
                str.Append(", ");
            }
            str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
        }

        MessageBox.Show(str.ToString()); //for test's sake

        string pathFile = @"path\filename.csv";

        if (!File.Exists(pathFile))
        {
            File.Create(pathFile).Close();
        }

        File.AppendAllText(pathFile, str.ToString());

参数可能有问题,但我尝试过这种方式也没有成功(我添加了第二列,所以 id 保持不变只是为了找到正确的行),执行时出现 UPDATE 命令语法错误:

string string_conn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";

        OleDbConnection conn= new OleDbConnection(string_conn);
        conn.Open();

        DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        string[] excelSheets = new String[dt.Rows.Count];
        int i = 0;

        foreach (DataRow row in dt.Rows)
        {
            excelSheets[i] = row["TABLE_NAME"].ToString();
            i++;
        }

        comboBox1.DataSource = excelSheets;
        string xlsSheet = comboBox1.SelectedItem.ToString();

        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);
        DataSet dataset = new DataSet();
        adapter.Fill(dataset);

        adapter.UpdateCommand = new OleDbCommand("UPDATE " + xlsSheet + " SET nazwa = @nazwa WHERE id = @id", conn);

   adapter.UpdateCommand.Parameters.AddWithValue("@id", tbox1.Text).OleDbType = OleDbType.Integer;
        adapter.UpdateCommand.Parameters.AddWithValue("@nazwa", tbox2.Text).OleDbType = OleDbType.VarChar;
        adapter.UpdateCommand.ExecuteNonQuery();

        adapter.Update(dataset);
        dataset.AcceptChanges();


        DataTable dtable = new DataTable();
        dtable = dataset.Tables[0];



        StringBuilder str = new StringBuilder();
        foreach (DataRow dr in dtable.Rows)
        {
            foreach (var field in dr.ItemArray)
            {
                str.Append(field.ToString());
                str.Append(", ");
            }
            str.Replace(",", str.AppendLine().ToString(), str.Length - 1, 1);
        }

        MessageBox.Show(str.ToString());

        string sciezkaPlik = @"path\filename.csv";

        if (!File.Exists(sciezkaPlik))
        {
            File.Create(sciezkaPlik).Close();
        }

        File.AppendAllText(sciezkaPlik, str.ToString());

我解决了这个问题。为了将来参考,它的工作原理如下:

 string string_conn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=path\arkusz.xls;Extended Properties='Excel 8.0;HDR=Yes;'";

        OleDbConnection conn = new OleDbConnection(string_conn);
        conn.Open();

        DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        string[] excelSheets = new String[dt.Rows.Count];

        int i = 0;

        foreach (DataRow row in dt.Rows) 
        {
            excelSheets[i] = row["TABLE_NAME"].ToString();
            i++;
        }

        comboBox1.DataSource = excelSheets; 
        string xlsSheet = comboBox1.SelectedItem.ToString(); 

        OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + xlsSheet + "]", conn);

        DataSet dataset = new DataSet();
        adapter.Fill(dataset);


        OleDbCommand odbc = new OleDbCommand("UPDATE ["+xlsSheet+"] SET nazwa = " + txtNewValue.Text + " WHERE id = " + txtID.Text + "", conn);

        adapter.UpdateCommand = odbc;

        odbc.Parameters.AddWithValue("nazwa", txtNewValue.Text).OleDbType = OleDbType.VarChar;
        odbc.Parameters.AddWithValue("id", txtID.Text).OleDbType = OleDbType.Integer;

        odbc.ExecuteNonQuery();

        dataset.Clear();
        adapter.Fill(dataset);

        DataTable dtable = new DataTable();
        dtable = dataset.Tables[0];

        StringBuilder str = new StringBuilder();
        foreach (DataRow dr in dtable.Rows) 
        {
            foreach (var field in dr.ItemArray) /
            {
                str.Append(field.ToString());
                str.Append(", ");
            }
            str = str.Replace(',', '\n'); 
        }

        string filePath= @"path\filename.csv"; 

        if (!File.Exists(filePath))
        {
            File.Create(filePath).Close();
        }

        File.WriteAllText(filePath, str.ToString());

【问题讨论】:

    标签: c# excel dataset oledb


    【解决方案1】:

    Hare 是一种非常简单的插入 Excel 工作表的方法。

    using System;
    using System.Drawing;
    using System.Windows.Forms;
    using Excel = Microsoft.Office.Interop.Excel; 
    
    namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    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.Jet.OLEDB.4.0;Data Source='c:\\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
                    MyConnection.Open();
                    myCommand.Connection = MyConnection;
                    sql = "Insert into [Sheet1$] (id,name) values('5','e')";
                    myCommand.CommandText = sql;
                    myCommand.ExecuteNonQuery();
                    MyConnection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show (ex.ToString());
                }
            }
       }
    }
    

    【讨论】:

      【解决方案2】:

      编辑-我认为可能是这一行需要将参数作为问号放入,而不是传入实际值,所以更像这样:

      adapter.UpdateCommand = new OleDbCommand ("UPDATE " + xlsSheet + " SET id = ? WHERE id = ?", conn);
      

      那么你接下来的几行是正确的,它们足够聪明,可以在运行时用实际值替换 UpdateCommand 中的问号:

      adapter.UpdateCommand.Parameters.Add("@id", OleDbType.Char, 255).SourceColumn = "id";
      adapter.UpdateCommand.Parameters.Add("@Oldid", OleDbType.Char, 255, "id").SourceVersion = DataRowVersion.Original;
      

      【讨论】:

      • 我将其更改为: ("UPDATE Arkusz1$ SET nazwa = 123 WHERE id = 1", conn);我仍然得到更新语法错误。 Arkusz1$ 是 xls 中工作表的名称。
      • 能否请您粘贴语法错误。我想知道它是否是工作表名称中的 $ 符号,不要尝试,但如果必须保留它,我认为语法是在它周围加上方括号,所以 [Arkusz1$] 但我没有尝试过。
      • 我解决了那部分。它仅在名称在括号内时才有效:[Arkusz1$],现在它有效:) 我也有点解决了更新参数的问题。如果你想看看,我更新了我的帖子。现在它会更改 XLS 表并正确发送到 CSV。感谢您的建议!
      • 嗨,迈克,如果对您有帮助,您介意投票并将其标记为答案吗,我需要一些积分。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2019-02-08
      • 2023-03-14
      • 1970-01-01
      • 2015-11-05
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多