我正在使用Visual Studio2010。使用OleDB,如何将Excel工作表的选定列和行导入到我的datagridView1
中?假设我的行和列从B13开始并获得至少B13的20行。
有人有示例代码或链接可以帮助我做到这一点吗?非常感谢!
答案 0 :(得分:1)
您可以通过以下命令执行此操作:
"SELECT * FROM [<SheetName>$<optional range>]";
//Ex : OleDbCommand OleConnection = new OleDbCommand("SELECT * FROM [Sheet1$B13:B33]", Con);
来源:Select cell adress from Excel using OLEDB in C#
完整代码在这里:
try
{
OpenFileDialog dlg_im = new OpenFileDialog();
dlg_im.Filter = "Excel File|*.xls;*.xlsx;*.xlsm";
//dlg_im.Filter = "Excel File|*.xlsx";
if (dlg_im.ShowDialog() == DialogResult.OK)
{
dataGridView1.Rows.Clear();
textBox1.Text = dlg_im.FileName;
string name = "Sheet1";
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection Con = new OleDbConnection(constr);
OleDbCommand OleConnection = new OleDbCommand("SELECT * FROM [Sheet1$B13:B33]", Con);
Con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(OleConnection);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
dataGridView1.ReadOnly = true;
dataGridView1.Columns[0].Width = 320;
dataGridView1.ClearSelection();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
MessageBox.Show("Done");
答案 1 :(得分:1)
如果要将Excel文件的列导入到可用datagridview中的空列。
例如:您具有如下datagridview,并且您想要读取excel文件并导入到“类”列中
假设您要将Excel文件的A1到A11范围的数据添加到datagridview的“类”(第二列)中
private void button3_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog dlg_im = new OpenFileDialog();
dlg_im.Filter = "Excel File|*.xls;*.xlsx;*.xlsm";
//dlg_im.Filter = "Excel File|*.xlsx";
if (dlg_im.ShowDialog() == DialogResult.OK)
{
textBox1.Text = dlg_im.FileName;
string name = "Sheet1";
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection Con = new OleDbConnection(constr);
OleDbCommand OleConnection = new OleDbCommand("SELECT *FROM [Sheet1$A1:A11]", Con);
Con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(OleConnection);
DataTable data = new DataTable();
sda.Fill(data);
int i = 0;//The position of row in datagridview you want to start adding
foreach (DataRow dr in data.Rows)
{
Console.WriteLine(dr.ItemArray[0]);
dataGridView1.Rows[i].Cells[2].Value = dr.ItemArray[0];//Cells[2] --> Columns[2] --> Column Class
i++;
}
dataGridView1.ClearSelection();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
这是输出:
答案 2 :(得分:0)
“如果excel中的列类有一个空行该怎么办?我想导入A1-A10,但是我的excel中的类列只有a1-a5,这是不可能的,我也可以获得空列而不会超出范围是因为我遇到了错误。我尝试仅在excel的Class列中放入1个数据,只是为了放入A1并仍然在查询字符串构造时获得A1-A10。“
->如您在下图中所看到的,我尝试仅在excel文件的类列中放入1个数据“ A1”。当我将此excel文件导入datagridview时,我不会遇到任何超出范围的异常。
答案 3 :(得分:0)