首页 > 解决方案 > C# 从通过 OpenFileDialog 加载到 DataGridView 中的文件更新 Excel 中的列,其中的值从 ComboBox 中选择

问题描述

我有一个包含 2 Buttons( Browse& updateExcel)、a ComboBox( comboBox1) 和DataGridView( dataGridView1)的小表格

第一个按钮让您选择一个 Excel 文件,然后将文件加载到DataGridView

private void Browse_Click(object sender, EventArgs e)
    {

        OpenFileDialog op = new OpenFileDialog();
        op.InitialDirectory = @"C:\";
        op.Title = "Browse Excel Files";
        op.CheckFileExists = true;
        op.CheckPathExists = true;
        op.DefaultExt = "xls";
        op.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm;*.csv";
        op.FilterIndex = 2;
        op.RestoreDirectory = true;
        op.ReadOnlyChecked = true;
        op.ShowReadOnly = true;

        if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            if (File.Exists(op.FileName))
            {
                string[] Arr = null;
                Arr = op.FileName.Split('.');
                if (Arr.Length > 0)
                {
                    if (Arr[Arr.Length - 1] == "xls")
                        sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                        op.FileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                }
                else if (Arr[Arr.Length - 1] == "xlsx")
                {
                    sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + op.FileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';";
                }
            }
            FillData();
        }
    }

这也使用以下代码:

    public string sConnectionString;
    private void FillData()
    {
        if (sConnectionString.Length > 0)
        {
            OleDbConnection cn = new OleDbConnection(sConnectionString);
            {
                cn.Open();
                DataTable dt = new DataTable();
                OleDbDataAdapter Adpt = new OleDbDataAdapter("select * from [sheet1$]", cn);
                Adpt.Fill(dt);
                dataGridView1.DataSource = dt;
            }
            try { }
            catch (Exception ex)
            {
            }
        }
    }

显示文件后,我有一个ComboBox( comboBox1) ,它设置了可以选择的静态值。

我要做的是在另一个按钮 ( updateExcel) 上,它采用您在 中选择的值ComboBox,然后替换 C 列中的所有值。

当前用途:

using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System;
using System.ComponentModel;
using System.Data;

例如:

如果我的 Excel 文件是:

a   b   c   d   e   f
aaa bbb ccc ddd eee fff
ggg hhh iii jjj kkk lll
mmm nnn ooo ppp qqq rrr

XXXComboBox我希望输出中选择:

a   b   c   d   e   f
aaa bbb XXX ddd eee fff
ggg hhh XXX jjj kkk lll
mmm nnn XXX ppp qqq rrr

标签: c#winformsdatagridviewopenfiledialog

解决方案


我通过使用以下代码解决了这个问题:

    private void updateExcel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < dataGridView1.RowCount - 1; i++)
        {
            dataGridView1[2, i].Value = ConsigneeCombo.Text;
        }
    }

推荐阅读