2

hello guys we got a project from school. its getting data from excel and putting it to datagridview. i got and excel file named "data.xls" and inside a sheet name "clay"; my code gets saying they can't find the sheet clay. any comments... here is my code using asp.net

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        String filePath = textPath.Text;
        String sheetName = textSheet.Text;
        string constr=  "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;'";
        OleDbConnection con = new OleDbConnection(constr);
        OleDbDataAdapter sda = new OleDbDataAdapter("Select * from ['" + sheetName + "$']",con);
        DataTable dt = new DataTable();
        sda.Fill(dt);
        dataGridView1.DataSource = dt; 
    }
}
}
stema
  • 90,351
  • 20
  • 107
  • 135
rein
  • 25
  • 4

1 Answers1

2

I don't think you need to use single quotes with sheetName.

Use this instead;

OleDbDataAdapter sda = new OleDbDataAdapter("Select * from [" + sheetName + "$]",con);
Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • thank you very much @soner i thought its needed based on some books im reading. thank you very much sir. – rein Mar 02 '14 at 11:13