zoukankan      html  css  js  c++  java
  • Excel导入数据到数据库

    两年前大费周章的写了个导入程序,现在要用到想直接拿来用。却找不到了。

    于是重新写了一遍,这里记录一下用Excel导入到数据库的过程。为下次节省时间...

    思路:

    1、上传Excel文件到服务器

    2、将Excel内容读取出来 填充到DataTable中

    3、将DataTable内容保存到数据库内。

    (当然还可以先校验后帮到页面上,让用户再次确认要导入的数据。这里我省掉了,只列出详细的错误清单)

    so easy。。。

    实现:

    首先 要准备一个Excel模板。Excel第一行一定要写入你要导入的字段名称,名称可以用汉字,但只要你能和数据库字段对应起来用程序处理就可以了。

    有必要的话 在页面上写点说明, 比如哪个字段一定要填写什么样的数据。当然程序异常处理还是要的。

    1、前台页面代码

      页面上就简单点 放一个上传控件、一个导入的按钮。

    <div>
                    <p><b>数据导入:</b></p>
                    <div>
                        选择文件:<asp:FileUpload ID="fu_excel"  runat="server" />
                        <asp:Button ID="btn_save" runat="server" Text="导入" onclick="btn_save_Click" /><br />
                        <asp:Label ID="lb_msg" runat="server" Text="" ForeColor="Red"></asp:Label>
                    </div>
                </div>

    2、后台代码
        导入按钮事件

    /// <summary>
            /// 上传 保存到数据库
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void btn_save_Click(object sender, EventArgs e)
            {
                ExcelUpload();
            }

        上传导入的一些方法

    /// <summary>
            /// 文件上传方法
            /// </summary>
            protected void ExcelUpload()
            {
                //存放文件路径
                String filepath = "";
    
                //存放文件扩展名
                string fileExtName = "";
                //文件名
                string mFileName = "";
                //服务器上的相对路径
                string mPath = "";
    
                if (fu_excel.PostedFile.FileName != "")
                {
                    //取得文件路径
                    filepath = fu_excel.PostedFile.FileName;
                    //取得文件扩展名
                    fileExtName = filepath.Substring(filepath.LastIndexOf(".") + 1);
                    //取得服务器上的相对路径
                    mPath = this.Request.PhysicalApplicationPath + "UpLoadFiles\\Excel\\";
                    //取得文件名
                    mFileName = filepath.Substring(filepath.LastIndexOf("\\") + 1);
                    //保存文件到指定目录
                    if (!Directory.Exists(mPath))
                    {
                        try
                        {
                            Directory.CreateDirectory(mPath);
                        }
                        catch
                        {
                            MessageBox.Show(this.Page, "服务器创建存放目录失败");
                        }
                    }
                    //如果文件已经存在则删除原来的文件
                    if (File.Exists(mPath + mFileName))
                    {
                        try
                        {
                            File.Delete(mPath + mFileName);
                        }
                        catch
                        {
                            MessageBox.Show(this.Page, "服务器上存在相同文件,删除失败。");
                        }
                    }
    
                    #region 判断文件扩展名
    
                    //判断上传文件格式
                    Boolean fileOK = false;
    
                    if (fu_excel.HasFile)
                    {
    
                        String fileExtension = System.IO.Path.GetExtension(fu_excel.FileName).ToLower();
    
                        String[] allowedExtensions = { ".xls" };
    
                        for (int i = 0; i < allowedExtensions.Length; i++)
                        {
    
                            if (fileExtension == allowedExtensions[i])
                            {
    
                                fileOK = true;
    
                            }
    
                        }
    
                    }
                    #endregion
    
                    #region 判断文件是否上传成功
    
                    //判断文件是否上传成功
                    bool fileUpOK = false;
                    if (fileOK)
                    {
                        try
                        {
                            //文件上传到服务器
                            fu_excel.PostedFile.SaveAs(mPath + mFileName);
    
                            fileUpOK = true;
                        }
                        catch
                        {
                            MessageBox.Show(this.Page,"文件上传失败!请确认文件内容格式符合要求!");
                        }
                    }
                    else
                    {
    
                        MessageBox.Show(this.Page,"上传文件的格式错误,应为.xls格式!");
    
                    }
                    #endregion
    
                    #region 将Excel填充到数据集
    
                    //将Excel填充到数据集
                    if (fileUpOK)
                    {
                        System.Data.DataTable dt_User = new System.Data.DataTable();
                        try
                        {
                            //获取Excel表中的内容
                            dt_User = GetList(mPath + mFileName);
                            if (dt_User==null)
                            {
                                MessageBox.Show(this.Page, "获取Excel内容失败!");
                                return;
                            }
                        }
                        catch
                        {
                            MessageBox.Show(this.Page,"获取Excel内容失败!");
                        }
                        int rowNum = 0;
                        try
                        {
                            rowNum = dt_User.Rows.Count;
                        }
                        catch
                        {
                            MessageBox.Show(this.Page,"Excel表获取失败!");
                        }
                        if (rowNum == 0)
                        {
                            MessageBox.Show(this.Page,"Excel为空表,无数据!");
                        }
                        else
                        {
                            //数据保存
                            SaveToDataBase(dt_User);
                        }
                    }
    
                    #endregion
                }
            }
    
            #region 读取Excel表数据
            
            /// <summary>
            /// 根据Excel文件路径读取Excel表中第一个表的内容
            /// </summary>
            /// <param name="FilePath">Excel文件的物理路径</param>
            /// <returns>DataSet</returns>
            public System.Data.DataTable GetList(string FilePath)
            {
                string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=Excel 8.0;";
                string strSql = string.Empty;
                //string workSheetName = Get_FistWorkBookName(FilePath);
       //第一个工作表的名称。考虑到稳定性,就直接写死了。 string workSheetName = "Sheet1"; if (workSheetName != "") { strSql = "select * from [" + workSheetName + "$]"; try { OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbDataAdapter myCommand = null; myCommand = new OleDbDataAdapter(strSql, connectionString); System.Data.DataTable dt = new System.Data.DataTable(); myCommand.Fill(dt); conn.Close(); conn.Dispose(); return dt; } catch (Exception) { return null; } } else { return null; } } /// <summary> /// 根据EXCEL文件路径获取EXCEL第一个工作薄的表名 /// 缺点:需要打开excel占用进程,暂不使用此方法 /// 优点:更灵活,可以随意更改表名 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public string Get_FistWorkBookName(string fileName) { Application app = new ApplicationClass(); Workbook workBook = app.Workbooks.Add(Type.Missing); ; Worksheet workSheet = (Worksheet)workBook.Sheets.get_Item(1); string rev = string.Empty; if (!File.Exists(fileName)) throw new Exception("指定路径的Excel文件不存在!"); Workbook tmpworkBook; Worksheet tmpworkSheet; try { object missing = System.Reflection.Missing.Value; //打开一个WorkBook tmpworkBook = app.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, missing); // tmpworkSheet = (Worksheet) workBook.Sheets.get_Item ( 1 ); app.Visible = false; tmpworkSheet = (Worksheet)tmpworkBook.Worksheets[1]; rev = tmpworkSheet.Name; } catch { rev = ""; } finally { tmpworkSheet = null; tmpworkBook = null; this.Dispose(); } return rev; } #endregion
     
    #region 将数据保存到数据库
            /// <summary>
            /// 将数据保存到数据库
            /// </summary>
            /// <param name="dt_user"></param>
            protected void SaveToDataBase(System.Data.DataTable dt_user)
            {
             string strMsg = "";
                lb_msg.Text = "";
                //创建事务s
                SqlTransaction trans_user = null;
                //打开数据连接
                SqlConnection con = new SqlConnection(PubConstant.ConnectionString);
                con.Open();
                //事务开始
                trans_user = con.BeginTransaction();
                try
                {
                 // 导入的话能用事务还是用事务处理吧
                 //事务提交
                    trans_user.Commit();
                    //flagOk = true;
                    MessageBox.Show(this.Page, "数据导入成功!");
                }
                catch (Exception ex)
                {
                    trans_user.Rollback();
    
                    MessageBox.Show(this.Page, "数据导入失败!" + ex.ToString().Substring(0, ex.ToString().IndexOf("") + 1) + " <br />请检查文件内容后重新导入!");
                }
                finally
                {
                    con.Close();
                    trans_user = null;
                    lb_msg.Text = strMsg;
                }
    }
            #endregion

       

  • 相关阅读:
    noi 1944 吃糖果
    noi 6049 买书
    noi 2985 数字组合
    noi 2728 摘花生
    noi 2718 移动路线
    noi 4977 怪盗基德的滑翔翼
    noi 8780 拦截导弹
    noi 1996 登山
    NOI 动态规划题集
    图的色数
  • 原文地址:https://www.cnblogs.com/loner/p/2946295.html
Copyright © 2011-2022 走看看