asp.net 读取Excel数据并将数据插入到数据库中

     #region 获取数据集
        public DataSet GetDataSet(string filePath)
        {
            //2010以前版本连接字符串
            //string Connstr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");  

            //IMEX=1 一共有三种模式 0表示导出 1 导入 2表示混合模式 在读取Excel数据有金额类型的后面带小数点最好去掉IMEX属性  
            //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES
            string Connstr2010 = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties='Excel 12.0'");
            OleDbConnection Conn = new OleDbConnection(Connstr2010);
            //创建ArrayList对象 存放所有sheetname    
            ArrayList sheetNamelist = new ArrayList();

            DataSet dsExcel = new DataSet();
            try
            {
                if (Conn.State == ConnectionState.Closed)
                {
                    Conn.Open();
                }
                DataTable dtExcelSchema = Conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });


                string sheetName = string.Empty;

                for (int j = 0; j < dtExcelSchema.Rows.Count; j++)
                {

                    sheetName = dtExcelSchema.Rows[j]["TABLE_NAME"].ToString();
                    //sheet名称 
                    if (sheetName.ToLower().IndexOf("database") != -1)
                        continue;
                    else
                        sheetNamelist.Add(sheetName);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString(), ex);
            }
            finally
            {
                Conn.Close();
            }
            try
            {
                string strSQL = string.Empty;
                for (int i = 0; i < sheetNamelist.Count; i++)
                {

                    strSQL = "select * from [" + sheetNamelist[i].ToString() + "]";
                    OleDbDataAdapter da = new OleDbDataAdapter(strSQL, Conn);
                    DataTable dtExcel = new DataTable(sheetNamelist[i].ToString());
                    da.Fill(dtExcel);

                    dsExcel.Tables.Add(dtExcel);
                }

                return dsExcel;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message.ToString(), ex);
            }
            finally
            {

            }
        }
        #endregion

        #region 从Excel 表中取出数据 将取出来的数据插入到数据库中
        public void InsertData(DataSet ds)
        {
            string costCenter = string.Empty;
            string strSQL = string.Empty;
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int j = 0; j < ds.Tables.Count; j++)
                {

                    if ((ds.Tables[j].TableName.ToString().StartsWith("'") && ds.Tables[j].TableName.ToString().EndsWith("'")) && ds.Tables[j].TableName.ToString().IndexOf("$") != -1)
                    {
                        costCenter = ds.Tables[j].TableName.ToString().TrimStart("'".ToCharArray()).TrimEnd("'".ToCharArray()).TrimEnd("$".ToCharArray());
                    }

                    //从16行开始读取
                    for (int i = 12; i < ds.Tables[j].Rows.Count; i++)
                    {

                        DataRow dr = ds.Tables[j].Rows[i];
                        //AcctCode
                        string AcctCode = dr[ds.Tables[j].Columns[0].ColumnName].ToString();
                        int num = 0;
                        if (!string.IsNullOrEmpty(AcctCode.Trim()) && int.TryParse(AcctCode, out num) == false)
                        {
                            continue;
                        }
                        else if (!string.IsNullOrEmpty(AcctCode.Trim()) && !IsExistsAcctCode(AcctCode))
                        {
                            Response.Write("<script>alert('当前在" + costCenter + "中的第" + i.ToString() + "行" + AcctCode + "不存在科目表中!不能导入')</script>");

                            continue;
                        }
                        else if (!string.IsNullOrEmpty(costCenter) && !IsExistscostCenter(costCenter.Trim()))
                        {
                            Response.Write("<script>alert('当前成本中心" + costCenter + "不存在')</script>");
                            break;
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(AcctCode.Trim()) || AcctCode.Trim().Length == 0)
                            {
                                continue;
                            }
                            else
                            {
                                try
                                {
                                    for (int m = 1; m < 13; m++)
                                    {
                                        string coluName = string.Empty;
                                        string period = string.Empty;
                                        if (m < 10)
                                        {
                                            period = "20130" + m.ToString();


                                        }
                                        else
                                        {
                                            period = "2013" + m.ToString();
                                        }

                                        //读取月份字段
                                        switch (m)
                                        {
                                            case 1:
                                                coluName = ds.Tables[j].Columns[3].ColumnName.ToString();
                                                break;
                                            case 2:
                                                coluName = ds.Tables[j].Columns[4].ColumnName.ToString();
                                                break;

                                            case 3:
                                                coluName = ds.Tables[j].Columns[5].ColumnName.ToString();
                                                break;
                                            case 4:
                                                coluName = ds.Tables[j].Columns[6].ColumnName.ToString();
                                                break;
                                            case 5:
                                                coluName = ds.Tables[j].Columns[7].ColumnName.ToString();
                                                break;
                                            case 6:
                                                coluName = ds.Tables[j].Columns[8].ColumnName.ToString();
                                                break;
                                            case 7:
                                                coluName = ds.Tables[j].Columns[9].ColumnName.ToString();
                                                break;

                                            case 8:
                                                coluName = ds.Tables[j].Columns[10].ColumnName.ToString();
                                                break;

                                            case 9:
                                                coluName = ds.Tables[j].Columns[11].ColumnName.ToString();
                                                break;

                                            case 10:
                                                coluName = ds.Tables[j].Columns[12].ColumnName.ToString();
                                                break;
                                            case 11:
                                                coluName = ds.Tables[j].Columns[13].ColumnName.ToString();
                                                break;

                                            case 12:
                                                coluName = ds.Tables[j].Columns[14].ColumnName.ToString();
                                                break;

                                        }

                                        string amount = dr[coluName].ToString().Trim();


                                        if (amount.ToString().IndexOf(",") != -1)
                                        {
                                            amount = amount.ToString().Replace(",", "").Trim();
                                        }

                                        if (!string.IsNullOrWhiteSpace(amount.ToString()) && amount.ToString() != "0")
                                        {
                                            strSQL = string.Format("insert into tbl_Budget(CostCenter,NaturalCode,Period,BudgetAmount)values('{0}','{1}','{2}','{3}')", costCenter.Trim(), AcctCode, period, amount.ToString());

                                            int result = ExecuteCommand(strSQL);
                                        }
                                        else
                                        {

                                        }
                                    }

                                }

                                catch (Exception ex)
                                {
                                    throw ex;
                                }
                                finally
                                {

                                }
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region 判断从Excel读取的AcctCode数据是否存在tbl_Account 表中
        public bool IsExistsAcctCode(string accountCode)
        {
            string strSQL = string.Format("select COUNT(1) as tcount from tbl_Account where NaturalCode='{0}'", accountCode);
            int count = 0;
            DataSet ds = ReturnDataSet(strSQL);
            if (ds.Tables[0].Rows.Count > 0)
            {
                count = Convert.ToInt32(ds.Tables[0].Rows[0]["tcount"].ToString());
            }

            if (count > 0)
                return true;
            else

                return false;


        }


        #endregion

        #region 判断从Excel读取的AcctCode数据是否存在tbl_Account 表中
        public bool IsExistscostCenter(string costCenter)
        {
            string strSQL = string.Format("select COUNT(1) as tcount from tbl_ExternalTable_CostCenter where CostCenter='{0}'", costCenter);
            int count = 0;
            DataSet ds = ReturnDataSet(strSQL);
            if (ds.Tables[0].Rows.Count > 0)
            {
                count = Convert.ToInt32(ds.Tables[0].Rows[0]["tcount"].ToString());
            }

            if (count > 0)
                return true;
            else

                return false;


        }


        #endregion

        #region SQL Helper

        public static int ExecuteCommand(string safeSql)
        {
            int result = 0;
            string connectionString = "Data Source=phshadb3;Initial Catalog=EIS;Integrated Security=True;max pool size=512;";
            SqlConnection Connection = new SqlConnection(connectionString);
            try
            {
                Connection.Open();
                SqlCommand cmd = new SqlCommand(safeSql, Connection);
                result = cmd.ExecuteNonQuery();
                cmd.Dispose();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                Connection.Close();


                Connection.Dispose();
            }

            return result;
        }




        public static int ExecuteScalar(string safeSql)
        {
            string connectionString = "Data Source=phshadb3;Initial Catalog=EIS;Integrated Security=True";
            SqlConnection Connection = new SqlConnection(connectionString);
            Connection.Open();
            SqlCommand cmd = new SqlCommand(safeSql, Connection);
            int result = (int)cmd.ExecuteScalar();
            return result;
        }



        public static SqlDataReader ExecuteReader(string safeSql)
        {
            string connectionString = "Data Source=phshadb3;Initial Catalog=EIS;Integrated Security=True";
            SqlConnection Connection = new SqlConnection(connectionString);
            Connection.Open();
            SqlCommand cmd = new SqlCommand(safeSql, Connection);
            SqlDataReader reader = cmd.ExecuteReader();
            return reader;
        }


        public static DataSet ReturnDataSet(string safeSql)
        {
            string connectionString = "Data Source=phshadb3;Initial Catalog=EIS;Integrated Security=True;max pool size=512;";
            SqlConnection Connection = new SqlConnection(connectionString);
            DataSet ds;
            try
            {

                Connection.Open();
                ds = new DataSet();

                SqlDataAdapter da = new SqlDataAdapter(safeSql, connectionString);
                da.Fill(ds);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            finally
            {
                Connection.Close();

            }
            return ds;
        }
        #endregion

        #region 导入Excel数据
        protected void Button1_Click(object sender, EventArgs e)
        {

            string fileName = FileUpload1.FileName;
            //判断是否存在上传文件  
            if (FileUpload1.PostedFile.FileName.Length == 0)
            {
                Page.ClientScript.RegisterStartupScript(typeof(index), "ok", "alert('请选择你要上传的Excel文件')");
            }
            //判断上传的文件类型是否正确  
            else if (!Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower().Equals(".xls") && !Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower().Equals(".xlsx"))
            {
                Page.ClientScript.RegisterStartupScript(typeof(index), "ok", "alert(很抱歉,你上传的文件格式不正确)");
            }
            else
            {
                // 获取上传的文件路径  
                string filePath = Server.MapPath("ExcelFiles//") + DateTime.Now.ToString("yyyyMMddhhmmss") + fileName;
                //保存上传文件
                this.FileUpload1.PostedFile.SaveAs(filePath);
                //获取数据集
                DataSet ds = GetDataSet(filePath);
                //获取数据源向数据库插入相应的值
                InsertData(ds);

            }

        }
        #endregion


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值