程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c#讀取Excel數據到Gridview

c#讀取Excel數據到Gridview

編輯:C#入門知識

#region 讀取Excel數據到Gridview

    public void ReadExcel(string sExcelFile, GridView dgBom)
    {

    DataTable ExcelTable;
        DataSet ds = new DataSet();

        //Excel的連接
        OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sExcelFile + ";" + "Extended Properties=Excel 8.0;");
        objConn.Open();
        DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);

        string tableName = schemaTable.Rows[0][2].ToString().Trim();//獲取 Excel 的表名,默認值是sheet1
        string strSql = "select * from [" + tableName + "]";

        OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
        OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);

        //填充數據
        myData.Fill(ds, tableName);

        objConn.Close();

        ExcelTable = ds.Tables[tableName];
        int iColums = ExcelTable.Columns.Count;//列數
        int iRows = ExcelTable.Rows.Count;//行數

        //定義二維數組存儲 Excel 表中讀取的數據
        string[,] storedata = new string[iRows, iColums];

        ArrayList list = new ArrayList();

        for (int i = 0; i < ExcelTable.Rows.Count; i++)
        {
            SupermarketVO vo = new SupermarketVO();

            for (int j = 1; j < ExcelTable.Columns.Count; j++)
            {
                //將Excel表中的數據存儲到數組
                storedata[i, j] = ExcelTable.Rows[i][j].ToString();

                if (j == 1)
                {
                    vo.Sup_nm = ExcelTable.Rows[i][j].ToString();
                }
                else if (j == 2)
                {
                    vo.Sup_linker = ExcelTable.Rows[i][j].ToString();
                }
                else if (j == 3)
                {
                    vo.Phone = ExcelTable.Rows[i][j].ToString();
                }
            }

            //如果名稱、聯系人、電話都為空,則忽略該記錄
            if (vo.Sup_nm.Trim() == "" && vo.Sup_linker.Trim() == "" && vo.Phone.Trim() == "")
            {
                continue;
            }
            else
            {
                list.Add(vo);
            }
        }

        //判斷記錄數,以便於處理空記錄時的顯示
        if (list.Count < 1)
        {
            SupermarketVO vo = new SupermarketVO();
            list.Add(vo);

            //設置空記錄時的顯示(包含表頭顯示)和綁定記錄
            GridviewControl.GridViewDataBind(dgBom, list);
        }
        else
        {
            dgBom.DataSource = list;
            dgBom.DataBind();
        }

        LblErrorInfo.Text = "導入操作已經完成。";
    }

    #endregion
 

    

  1. 上一頁:
  2. 下一頁: