您的位置:首页 > 编程语言 > C#

C#表格导入实例(Winform也可以)直接复制可用

2016-01-04 15:22 585 查看
/// <summary>

        /// 导入

        /// </summary>

        public void InportExel()

        {

            try

            {

                OpenFileDialog openFileDialog = new OpenFileDialog();

                openFileDialog.Filter = "Microsoft Excel files(*.xls)|*.xls;*.xlsx";

                openFileDialog.RestoreDirectory = true;

                openFileDialog.FilterIndex = 1;

                if (openFileDialog.ShowDialog() == DialogResult.OK)//选择表

                {

                    //ShowProgress("正在导入数据..."); 进度条注释了,担心有的人不支持。

                    if (Import(openFileDialog.FileName))//调用方法

                    {

                        CommonUI.ShowMessageBox("导入成功");

                    }

                }

            }

            finally

            {

                //HideProgress();进度条注释了,担心有的人不支持。

                pagerControl1.ReLoadData();//刷新页面

            }

        }

/// <summary>

        /// 导入excel数据

        /// </summary>

        public static bool Import(string filePath)

        {

            bool istrue = false;

            //Excel就好比一个数据源一般使用

            //这里可以根据判断excel文件是03的还是07的,然后写相应的连接字符串

            string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;data source=" + filePath +

                             ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";

            if (filePath == null)

            {

                return false;

            }

            OleDbConnection con = new OleDbConnection(strConn);

            con.Open();

            try

            {

                string[] names = GetExcelSheetNames(con);  //查询表名方法

                if (names.Length > 0)

                {

                    foreach (string name in names)

                    {

                        OleDbCommand cmd = con.CreateCommand();

                        cmd.CommandText = string.Format(" select * from [{0}]", name); //[sheetName]要如此格式

                        OleDbDataReader odr = cmd.ExecuteReader();

                        while (odr.Read())

                        {

                            OrderDetailsInfo order = new OrderDetailsInfo();    //创建导入的实体类对象,并且给对应值赋值

                            order.iD = Guid.NewGuid().ToString();//自动生成

                            order.ecCompanyId = "Daoru";

                            order.special = int.Parse(odr["商品类型"].ToString().Trim());

                            order.weight = int.Parse(odr["商品重量"].ToString().Trim());

                            order.remark = odr["备注"].ToString().Trim();

                            order.codFee = Double.Parse(odr["代收货款"].ToString().Trim());

                            order.totalFee = Double.Parse(odr["总费用"].ToString().Trim());

                            order.expressFee = Double.Parse(odr["到付费用"].ToString().Trim());

                            //下面是调用方法 插入数据库,一般的项目直接类似这样:dao.insert(order),后台略

                            ServiceInvoker.Invoke<IOderDetailService>(service =>              

                            {

                                service.Insert(order);

                            }, "Order");

                        }

                        odr.Close();

                    }

                    istrue = true;

                }

               

            }

            catch (Exception ex)

            {

              //提示失败

                istrue= false;

            }

            finally

            {

                con.Close();

            }

            return istrue;

        }

/// <summary>

        /// 查询表名

        /// </summary>

        public static string[] GetExcelSheetNames(OleDbConnection con)

        {

            try

            {

                DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { null, null, null, "Table" });//检索Excel的架构信息

                var sheet = new string[dt.Rows.Count];

                for (int i = 0, j = dt.Rows.Count; i < j; i++)

                {

                    //获取的SheetName是带了$的

                    sheet[i] = dt.Rows[i]["TABLE_NAME"].ToString();

                }

                return sheet;

            }

            catch

            {

                return null;

            }

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: