【发布时间】:2019-04-21 10:47:00
【问题描述】:
我创建了一个具有 DataGrid 的表单,它是从 excel 文件加载的。我想在组合框中显示 excel 文件表名称。我找到了在我的组合框中显示 excel 工作表名称的解决方案。但是我希望当我更改我的组合框项目时,datagridview 填充取决于我更改我的组合框的 excel 表。 [IMG]http://i67.tinypic.com/153l82v.jpg[/IMG] 我怎样才能做到这一点? 我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace excel2access
{
public partial class Form2 : Form
{
string FilePath;
string CB;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OpenFD = new OpenFileDialog();
OpenFD.FileName = "";
OpenFD.Title = "Choose Excel file to Upload Data ";
OpenFD.DefaultExt = "xls";
OpenFD.Filter = "Ms-Excel Files (*.xls)|*.xls|All Files|*.*";
if (OpenFD.ShowDialog() == DialogResult.OK)
{
FilePath = OpenFD.InitialDirectory + OpenFD.FileName;//Code to get FullPath, Filename and extension
textBox1.Text = FilePath;
string excelConnStr = string.Empty;
OleDbCommand excelCommand = new OleDbCommand();
if (FilePath.EndsWith(".xlsx"))
{
//2007 Format
excelConnStr =string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Extended Properties='Excel 8.0;HDR=No'", FilePath);
}
else
{
//2003 Format
excelConnStr= string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties='Excel 8.0;HDR=No'", FilePath);
}
//Get the Sheets in Excel Workbook
OleDbConnection excelConn = new OleDbConnection(excelConnStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = excelConn;
excelConn.Open();
comboBox1.DataSource = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
comboBox1.DisplayMember = "TABLE_NAME";
comboBox1.ValueMember = "TABLE_NAME";
CB = comboBox1.DisplayMember;
DataTable dtsheet = new DataTable();
dtsheet = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + comboBox1.Text + "]", excelConnStr);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
【问题讨论】:
-
很好,您当前的代码是否有效?你让网格填充了吗?您是否为组合框定义了选择更改事件?
-
我的代码正在运行,我得到的 Excel 工作表名称为“Sheet1$”。当我选择 Sheet2 时,我希望我的数据网格数据填充在 sheet2 上。我无法解决这个问题。
-
你能看看我的回答吗?如果您有任何疑问,请告诉我
-
它显示一个错误。附加信息“$”不是有效名称。确保它不包含无效字符或标点符号,并且不要太长。我认为我的工作表名称显示为“sheet1$”,但需要将 sheet1$ 设置为“sheet1$”。但是如何在我的 combobox1 中获取不带单引号的工作表名称?