c# - 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
我XXX
从ComboBox
我希望输出中选择:
a b c d e f
aaa bbb XXX ddd eee fff
ggg hhh XXX jjj kkk lll
mmm nnn XXX ppp qqq rrr
解决方案
我通过使用以下代码解决了这个问题:
private void updateExcel_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1[2, i].Value = ConsigneeCombo.Text;
}
}
推荐阅读
- python - 如何将 --autoscaling_algorithm=NONE 标志传递给 python 代码中的数据流?
- javascript - 使用方括号表示法访问具有“n”级深度对象的嵌套对象
- visual-studio - 发布时从 3rd 方 Blazor 库中选择 wwwroot/_content/ 文件
- python - 通过 python SDK 将用户分配给 Azure Active Directory 企业应用程序
- rxjs - Observable 多次发出请求并一起收集响应
- html - CSS 网格 - 如何居中
- mysql - 在 WHERE 子句中使用子查询,但每个子查询结果限制为一个匹配项
- python-3.x - 带有 pil 图像的 tkinter 的奇怪行为
- javascript - 无法在反应类中声明常量
- python - Python单线程比CPU绑定中的两个线程慢