EXECL文件导入数据库

Execl数据导入数据库:

注意事项:execl中的列名与列数要与数据库的列名和列数一致、值类型一致,列名不一致的话可在导入的时候,给字段起别名,确定保持一致

界面代码:

EXECL文件导入数据库

   <div>

     导入Execl路径:

     <asp:FileUpload ID="FileUpload1" runat="server" />

     <asp:Button ID="ExeclToSql" runat="server" Text="导入数据库" Width="120px"    onclick="ExeclToSql_Click" />

</div>

后台cs代码:

 

protected void ExeclToSql_Click(object sender, EventArgs e)

        {

            string excelFile = "";

            //string excelFile = FileUpload1.FileName;

            System.Web.HttpPostedFile postFile = FileUpload1.PostedFile;

            DataSet ds = new DataSet();

            OleDbConnection conn = new OleDbConnection();

            try

            {

                //判断路径是否为空

                if (postFile.FileName != String.Empty)

                {

                    //新建文件名

                    string fileName = Guid.NewGuid().ToString() + ".xls";

                    //文件上传服务器目录路径

                    string absPath = Request.PhysicalApplicationPath + ("upload\\"); if (!System.IO.Directory.Exists(absPath)) System.IO.Directory.CreateDirectory(absPath); //上传文件,要检查一下是否建立了相关目录 

                    //保存文件至服务器

                    postFile.SaveAs(absPath + fileName);

                    //文件全部路径

                    excelFile = absPath + fileName;

                    try

                    {

                        //value代表数据库的字段名,*代表execl的字段

                        string ss = "INSERT INTO 数据库表名(value)  SELECT * FROM OPENDATASOURCE(‘Microsoft.ACE.OLEDB.12.0‘,‘Data Source=" + excelFile + ";Extended Properties=Excel 8.0‘)...[sheet1$]";

                        //注意:改方法为封装好的SQL执行语句,请用自己封装的连接数据库执行增删改查的类方法

                        DbHelperSQL.ExecuteSql(ss);

 

                        Page.RegisterStartupScript("js""<script>alert(‘导入数据成功!‘)</script>");

                    }

                    catch

                    {

                        Page.RegisterStartupScript("js""<script>alert(‘导入数据失败!‘)</script>");

                    }

                }

                else

                {

                    throw new Exception("请上传文件!");

                }

            }

            catch

            {

                Page.RegisterStartupScript("js""<script>alert(‘错误!‘)</script>");

            }

        }

或者用以下类方法:

 

public class ExcelToSQL

    {

        //string  sqlcon = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        public SqlConnection sqlcon = new SqlConnection("连接字符串");        //创建SQL连接  

        public SqlCommand sqlcom;          //创建SQL命令对象  

 

        public ExcelToSQL()

        {

            if (sqlcon.State.ToString() == "Open")

                sqlcon.Close();

        }

        public int ImportSql(string excelPath, string tableName)  //导入的Excel的路径,数据库里的表名  

        {

            if (!TableExist(tableName)) //表名是否存在  

                return (int)ImportState.tableNameError;

 

            DataTable dt = ExcelToDataTable(excelPath);//把Excel里的数据转换为DataTable,并返回DataTable

            if (dt == null)

            {

                return (int)ImportState.excelFormatError;//转换失败

            }

            ArrayList tableField = GetTableField(tableName);   //表格的列名称  (得到数据库表的列名)

 

            string columnName = "MGUID,"//Excel里的列名,增加一个ID列,如果ID自动递增则不需要增加ID列,只需要columnName=“”就可以了。  

            for (int i = 0; i < dt.Columns.Count; i++)

            {

                columnName += dt.Columns[i].ColumnName + ",";

                string currentColumn = dt.Columns[i].ToString().ToUpper(); //当前列名  

                for (int j = 0; j < tableField.Count; j++)

                {

                    if (tableField[j].ToString().ToUpper() == dt.Columns[i].ToString().ToUpper())

                        break;   //跳出本层和上一层循环,continue是跳出本层循环,如果用continue,会继续执行j++  

                    //Excel里的字段必须在Sql中都有  

                    if ((tableField[j].ToString().ToUpper() != dt.Columns[i].ToString().ToUpper()) && j == tableField.Count - 1)

                        return (int)ImportState.fieldMatchError;

                }

            }

            int m = columnName.LastIndexOf(‘,‘);

            columnName = columnName.Remove(m);  //移除最后一个逗号  

 

            sqlcom = new SqlCommand();

            sqlcom.Connection = sqlcon;

            sqlcon.Open();

            sqlcom.CommandType = CommandType.Text;

 

            for (int h = 0; h < dt.Rows.Count; h++)

            {

                string value = "‘" + System.Guid.NewGuid().ToString() + "‘" + ","//如果ID自动递增ID列不需要增加了,那么value的初始值只需要value=“”就可以了。  

 

                for (int k = 0; k < dt.Columns.Count; k++) //根据列名得到值  

                {

                    value += "‘" + dt.Rows[h][k].ToString() + "‘" + ",";

                }

                value = value.Remove(0, 1);

                int n = value.LastIndexOf(‘,‘);

                value = value.Remove(n);    //移除最后一个逗号  

                n = value.LastIndexOf("‘");

                value = value.Remove(n);

 

                try

                {

                    string sql = "insert into " + tableName + "(" + columnName + ") values(‘" + value + "‘)";

                    sqlcom.CommandText = sql;

                    string sss = sqlcom.ExecuteNonQuery().ToString();

                }

                catch (Exception err)

                {

                    string erroe = err.Message;

                    return (int)ImportState.dataTypeError;

                }

            }

            sqlcon.Close();

            sqlcom.Dispose();

 

            return (int)ImportState.right;

        }

        public DataTable ExcelToDataTable(string excelPath)  //把Excel里的数据转换为DataTable,并返回DataTable  

        {

            string strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties=‘Excel 8.0;IMEX=1‘";

            System.Data.OleDb.OleDbConnection Conn = new System.Data.OleDb.OleDbConnection(strCon);

            string strCom = "SELECT * FROM [库存数量$]";

            DataTable dt;

            try

            {

                Conn.Open();

                System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, Conn);

                DataSet ds = new DataSet();

                myCommand.Fill(ds, "[库存数量$]");

                Conn.Close();

                dt = ds.Tables[0];

            }

            catch (Exception err)

            {

                return null;

            }

            return dt;

        }

        public bool TableExist(string tableName) //查看数据库里是否有此表名  

        {

            sqlcom = new SqlCommand();

            sqlcom.Connection = sqlcon;

            sqlcom.CommandType = CommandType.Text;

            try

            {

                sqlcon.Open();

                string sql = "select name from sysobjects where type=‘u‘";

                sqlcom.CommandText = sql;

                SqlDataReader sqldr = sqlcom.ExecuteReader();

                while (sqldr.Read())

                {

                    if (sqldr.GetString(0).ToUpper() == tableName.ToUpper())

                        return true;

                }

            }

            catch { return false; }

            finally

            {

                sqlcon.Close();

            }

            return false;

        }

        public ArrayList GetTableField(string tableName)  //得到数据库某一个表中的所有字段  

        {

            ArrayList al = new ArrayList();

            sqlcom = new SqlCommand();

            sqlcom.Connection = sqlcon;

            sqlcom.CommandType = CommandType.Text;

            try

            {

                sqlcon.Open();

                string sql = "SELECT b.name FROM sysobjects a INNER JOIN syscolumns b ON a.id = b.id WHERE (a.name = ‘" + tableName + "‘)";

                sqlcom.CommandText = sql;

                SqlDataReader sqldr = sqlcom.ExecuteReader();

                while (sqldr.Read())

                {

                    al.Add(sqldr.GetString(0));

                }

            }

            finally

            {

                sqlcon.Close();

            }

            return al; //返回的是表中的字段  

        }

        public enum ImportState

        {

            right = 1, //成功  

            tableNameError = 2,//表名不存在  

            fieldMatchError = 3,//excel里的字段和数据库表里的字段不匹配  

            dataTypeError = 4, //转换数据类型时发生错误  

            excelFormatError = 5,//Excel格式不能读取  

        }

        public void Alert(string str)

        {

            HttpContext.Current.Response.Write("<script language=‘javascript‘>alert(‘" + str + "‘);</script>");

        }

                                                                                

    }

EXECL文件导入数据库,布布扣,bubuko.com

EXECL文件导入数据库

上一篇:Cacti--cacti数据库详解


下一篇:C#调用SQLServer存储过程