c# - 在 C# 中读取和更改 gridview 的值

标签 c# magento csv gridview

我正在为 magento 开发一个 csv 更改工具。 此工具必须更改 csv 文件的某些值。 我已经将 csv 导入到 gridview 中。 我的问题是如何读取单个单元格的值并从 gridview 更改它。

我用的是windows窗体c#

我想要这样的东西:
输入:
EAN,产品代码,名称
363738492,MT-01234,手机壳
153289234,MT-89854,三星手机壳
876253483,PO-43466,网线

输出:
EAN、sku、名称
363738492,MT-01234,手机壳
153289234,MT-89854,三星手机壳
876253483,PO-43466,网线

这是我的工作导入代码:

private void Import_Click(object sender, EventArgs e)
{
    OpenFileDialog fdlg = new OpenFileDialog();

    fdlg.Title = "Select file";
    fdlg.InitialDirectory = @"c:\";
    fdlg.FileName = txtFileName.Text;
    fdlg.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
    fdlg.FilterIndex = 1;
    fdlg.RestoreDirectory = true;
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        txtFileName.Text = fdlg.FileName;
        Import();
        Application.DoEvents();
    }
}
    public static DataTable GetDataTable(string strFileName)
        {   

            ADODB.Connection oConn = new ADODB.Connection();
            oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
            string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
            ADODB.Recordset rs = new ADODB.Recordset();
            System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
            DataTable dt = new DataTable();
            rs.Open(strQuery, "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
            ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
            adapter.Fill(dt, rs);

            return dt;

}
private void Import()
{
if (txtFileName.Text.Trim() != string.Empty)
 {
try
{
    DataTable dt = GetDataTable(txtFileName.Text);
    dgvGv.DataSource = dt.DefaultView;
    dgvGv2.DataSource = dt.DefaultView;
    dgvGv3.DataSource = dt.DefaultView;
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message.ToString());
}

这是我的工作导出代码:

  private void button1_Click(object sender, EventArgs e)
        {
             // Don't save if no data is returned
            if (dgvGv.Rows.Count == 0)
            {
                return;
            }
            StringBuilder sb = new StringBuilder();
            // Column headers
            string columnsHeader = "";
            for (int i = 0; i < dgvGv.Columns.Count; i++)
            {
                columnsHeader += dgvGv.Columns[i].Name + ",";
            }
            sb.Append(columnsHeader + Environment.NewLine);
            // Go through each cell in the datagridview
            foreach (DataGridViewRow dgvRow in dgvGv.Rows)
            {
                // Make sure it's not an empty row.
                if (!dgvRow.IsNewRow)
                {
                    for (int c = 0; c < dgvRow.Cells.Count; c++)
                    {
                        // Append the cells data followed by a comma to delimit.

                        sb.Append(dgvRow.Cells[c].Value + ",");
                    }
                    // Add a new line in the text file.
                    sb.Append(Environment.NewLine);
                }
            }
            // Load up the save file dialog with the default option as saving as a .csv file.
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV files (*.csv)|*.csv";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // If they've selected a save location...
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
                {
                    // Write the stringbuilder text to the the file.
                    sw.WriteLine(sb.ToString());
                }
            }
            // Confirm to the user it has been completed.
            MessageBox.Show("CSV file saved.");
        }

如有任何问题,请随时发表评论。

最佳答案

/从下拉菜单中选择 CSV 文件,然后单击从/在按钮单击事件中导入

private void btnimportexcel_Click(object sender, EventArgs e)
    {
        string source = string.Empty;
        source = cmbImportsource.Text;
        if (!string.IsNullOrEmpty(source ))
        {
            string smsfilename=string .Empty ;
            OpenFileDialog of = new OpenFileDialog();
            DialogResult dlresult;

            of.InitialDirectory = Environment.SpecialFolder.Desktop.ToString ();
            switch (source)
            {
                case "EXCEL":
                     of.Filter = "Excel File(*.xlsx,*.xls)|*.xlsx;*.xls|All Files(*.*)|*.*";
                     of.Title = "Select Excel File...";
                      dlresult = of.ShowDialog();
                       if (dlresult == DialogResult.OK )
                        {
                             smsfilename = of.FileName;
                           if (System.IO.File.Exists(smsfilename))
                           {
                               getRecordFromXcel(smsfilename);
                           }
                        }

                    break;

                case "CSV":
                    //"Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
                    of.Filter = "CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
                    of.Title = "Select Excel File...";
                      dlresult = of.ShowDialog();
                       if (dlresult == DialogResult.OK )
                        {
                             smsfilename = of.FileName;
                           if (System.IO.File.Exists(smsfilename))
                           {
                               getRecordFromCSV(smsfilename);
                           }
                        }
                    break;

                case "TEXT FILE":
                    break;


            }

        }

//选择文件时

    private void getRecordFromCSV(string file)
    {
        String textLine = string.Empty;
        String[] splitLine;
        bool columncreater = false;
        try
        {
            StreamReader objReaders = new StreamReader(file);
            dataGridView1.DataSource = null;
            dataGridView1.Columns.Clear();
            dataGridView1.Rows.Clear();
            int datagridrowindex =-1;
            do
            {
                textLine = objReaders.ReadLine();
                datagridrowindex=  datagridrowindex + 1;
                if (textLine != "")
                {
                    splitLine = textLine.Split(',');

                    //if (splitLine[0] != "" || splitLine[1] != "")
                    //{
                    //    dataGridView1.Rows.Add(splitLine[0]);

                    //}

                        if (columncreater ==false )
                        {
                            for (int i = 0; i < splitLine.Length; i++)
                            {
                                dataGridView1.Columns.Add("C" + i + "", "C" + i + "");
                            }
                            columncreater = true;
                        }


                    dataGridView1.Rows.Add(splitLine);
                    int cc = dataGridView1.Columns.Count;
                    int rr = dataGridView1.Rows.Count;


                }
            } while (objReaders.Peek() != -1);
        }
        catch (Exception ex)
        {

        }
    }

关于c# - 在 C# 中读取和更改 gridview 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25849364/

相关文章:

c# - 无法将透明代理强制转换为来自 AppDomain 的类型

python - CSV 模块的作者不让我写出二进制文件

ruby - 尝试将字符串拆分为单个单词或 "quoted words",并希望将引号保留在结果数组中

c# - 在 xamarin 表单中获取位置

c# - HtmlHelper 在使用中使用 html/文本

c# - windows phone 8.1 swype 键盘事件捕获

magento - 有 Magento 兼容的国家/地区代码列表吗?

用于从 Magento 中的 sitemap.xml 中排除特定类别页面的 PHP 代码

php - Magento 2:通过脚本发送订单确认电子邮件

java - Spark java中的异常