当前位置: 代码迷 >> .NET Framework >> 2010版本Excel 数据导入到.NET中,提醒 “外部表不是预期的格式。” !
  详细解决方案

2010版本Excel 数据导入到.NET中,提醒 “外部表不是预期的格式。” !

热度:61   发布时间:2016-05-01 23:36:05.0
2010版本Excel 数据导入到.NET中,提示 “外部表不是预期的格式。” !!!!!!!急啊!!!
        SqlDataAdapter da = null;
        DataSet ds = null;
        
        private void button1_Click(object sender, EventArgs e)  //导入数据
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Excel文件";
            ofd.FileName = "";
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);//为了获取特定的系统文件夹,可以使用System.Environment类的静态方法GetFolderPath()。该方法接受一个Environment.SpecialFolder枚举,其中可以定义要返回路径的哪个系统目录
            ofd.Filter = "Excel文件(*.xlsx)|*.xlsx";
            ofd.ValidateNames = true;     //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
            ofd.CheckFileExists = true;  //验证路径有效性
            ofd.CheckPathExists = true; //验证文件有效性


            string strName = string.Empty;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                strName = ofd.FileName;
            }

            if (strName == "")
            {
                MessageBox.Show("没有选择Excel文件!无法进行数据导入");
                return;
            }
             // 调用导入数据方法
            EcxelToDataGridView(strName, this.dataGridView1);

         

        }
        public void EcxelToDataGridView(string filePath, DataGridView dgv)
        {
            //根据路径打开一个Excel文件并将数据填充到DataSet中
            string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'", filePath);
           // string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " + filePath + ";Extended Properties ='Excel 12.0;HDR=NO;IMEX=1'";//导入时包含Excel中的第一行数据,并且将数字和字符混合的单元格视为文本进行导入
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataSet ds = null;
            strExcel = "select  * from   [sheet1$]";
            myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "table1");

            //根据DataGridView的列构造一个新的DataTable
            DataTable tb = new DataTable();
            foreach (DataGridViewColumn dgvc in dgv.Columns)
            {
                if (dgvc.Visible && dgvc.CellType != typeof(DataGridViewCheckBoxCell))
                {
                    DataColumn dc = new DataColumn();
  相关解决方案