没有在gridview中显示excel数据

时间:2013-11-27 17:41:09

标签: asp.net c#-4.0

当我按下按钮id是btnshow它没有在gridview中显示上传的excel文件数据时,可能会出现什么问题?

protected void btnupload_Click(object sender, EventArgs e)
{

    if (System.IO.Path.GetExtension(FileUpload1.FileName) == ".xls" || System.IO.Path.GetExtension(FileUpload1.FileName) == ".xlsx") 
    {
        FileUpload1.SaveAs(Server.MapPath("~/upload/payment.xlsx"));
        Label1.Text = "File Uploded";
    }

    else
    {
        Label1.Text = "Upload only Excel File";
    }

}

protected void btnshow_Click(object sender, EventArgs e)
{
    string currpath = Server.MapPath("~/upload/payment.xlsx");
    string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + currpath + ";Extended Properties=Excel 12.0";

    OleDbConnection oledbConn = new OleDbConnection(connString);
    try
    {
        oledbConn.Open();
        OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn);

        OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
        objAdapter1.SelectCommand = cmd;
        DataSet objDataset1 = new DataSet();
        objAdapter1.Fill(objDataset1, "ExcelData");
        GridView1.DataSource = objDataset1;
        GridView1.DataBind();

    }
    catch (Exception ex)
    {
       Label1.Text = "" + ex;
    }
    finally
    {
        oledbConn.Close();
    }

`

1 个答案:

答案 0 :(得分:0)

您需要将数据源设置为表,而不是数据集。 编辑:默认情况下,datasource将设置为Tables [0]。所以你的代码应该工作正常。但是在标记中,你应该为GridView提供AutoGenerateColumns="true"

<asp:GridView ID="GridView1" AutoGenerateColumns="true" runat="server"></asp:GridView>

您可以下载我用于测试代码的项目here