使用从xls文件读取的数据集更新单元格并保存到CSV文件

时间:2018-06-05 11:04:26

标签: c# excel dataset oledb

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

Xls表格格式非常简单,一列: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());

2 个答案:

答案 0 :(得分:0)

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

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

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

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

答案 1 :(得分:0)

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