你好,游客 登录
背景:
阅读新闻

winfrom导入excel文件 -

[日期:2013-04-05] 来源:  作者: [字体: ]
  private DataSet xsldata()            //定义一个dataset并把excel数据读入dataset
        {
            dataGridView1.Rows.Clear();
            OpenFileDialog openFile = new OpenFileDialog();//打开文件对话框。
            openFile.Filter = ("Excel 文件(*.xls)|*.xls");//后缀名。
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string filename = openFile.FileName;  //文件路径             
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties='Excel 8.0;IMEX=1'";
                OleDbConnection Conn = new OleDbConnection(strCon);
                string strCom = "SELECT * FROM [sheet1$]";
                Conn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, Conn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[sheet1$]");
                Conn.Close();
                Conn.Dispose();
                return ds;    //返回dataset
            }
            else
                return null;
        }
        //导入excel     
        private void toolStripButton1_Click(object sender, EventArgs e)
        {         
            try
            {                
                DataSet ds = xsldata();
                if (ds == null)    //如果录入dataset的数据为空(没有点击导入或者直接退出),则{}不执行
                { }
                else
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        dataGridView1.Rows.Add((i + 1).ToString(),
                            ds.Tables[0].Rows[i][0].ToString(),
                            ds.Tables[0].Rows[i][1].ToString(),
                            ds.Tables[0].Rows[i][2].ToString(),
                            ds.Tables[0].Rows[i][3].ToString(),
                            ds.Tables[0].Rows[i][4].ToString(),
                            ds.Tables[0].Rows[i][5].ToString(),
                            ds.Tables[0].Rows[i][6].ToString(),
                            ds.Tables[0].Rows[i][7].ToString(),
                            ds.Tables[0].Rows[i][8].ToString(),
                            ds.Tables[0].Rows[i][9].ToString(),
                            ds.Tables[0].Rows[i][10].ToString()
                           );
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex.ToString() + "导入文件时出错,文件可能正被打开", "提示");
                return;
            }





收藏 推荐 打印 | 录入:admin | 阅读:
相关新闻