zoukankan      html  css  js  c++  java
  • Excel 导入到Datatable 中,再使用常规方法写入数据库

    首先呢?要看你的电脑的office版本,我的是office 2013 .为了使用oledb程序,需要安装一个引擎。名字为AccessDatabaseEngine.exe。这里不过多介绍了哦。它的数据库连接字符串是"Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"

    所以,我们是使用ole来读取excel的。

    1 excel 的文件内容:

    2 测试的页面设计图

    3 webconfig里设置数据库相关字符串

    4 测试页面的代码:

    简单的布局,主要看功能:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExcelTodatabase.aspx.cs" Inherits="ExcelToDatabase.ExcelTodatabase" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        
            <asp:FileUpload ID="Excelfile" runat="server" />
        
            <asp:Button ID="btnFileUp" runat="server" Text="提交" OnClick="btnFileUp_Click" />
            <br />
            <br />
            <br />
            <asp:GridView ID="gvExcel" runat="server">
            </asp:GridView>
            <br />
            <br />
            <asp:Label ID="debug" runat="server" Text="Label"></asp:Label>
            <br />
        
        </div>
        </form>
    </body>
    </html>

    5 主要功能:

    5.1 导入文件

    5.2 将excel导入datatable

    5.3 将datatable 写入数据库

    完整的代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Data;
    using System.Data.SqlClient;
    using System.Data.OleDb;
    using System.IO;
    using System.Configuration;
    
    namespace ExcelToDatabase
    {
        public partial class ExcelTodatabase : System.Web.UI.Page
        {
            // 连接字符串
            private static string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            protected void Page_Load(object sender, EventArgs e)
            {
    
            }
    
            protected void btnFileUp_Click(object sender, EventArgs e)
            {
                if (Excelfile.HasFile)
                {
                    //检查文件扩展名
                    string filename = Path.GetFileName(Excelfile.PostedFile.FileName);
                    //debug.Text = filename;
                    string extension = Path.GetExtension(Excelfile.PostedFile.FileName);
                    //debug.Text = extension;
                    if (extension != ".xlsx")
                    {
                        Response.Write("<script>alert('抱歉!您上传的不是有效的Excel文件')</script>");
                    }
                    else
                    {
                        //首先保存到服务器上
                        string newFileName = "excel"+DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string savePath = "ExcelFiles/"+newFileName;
                        Excelfile.PostedFile.SaveAs(Server.MapPath(savePath)+extension);
                        //debug.Text = Server.MapPath(savePath) + extension;
                        //这里可以导入数据了
                        string fileUrl = Server.MapPath(savePath) + extension;
                        DataTable dt = GetExcel(fileUrl);
                        gvExcel.DataSource = dt;
                        gvExcel.DataBind();
                        //写入数据库   
                        bool addToDb = InsertDb(dt);
                        if (addToDb)
                        {
                            Response.Write("<script>alert('写入数据库成功')</script>");
                        }
                        else
                        {
                            Response.Write("<script>alert('抱歉!写入失败')</script>");
                        }
                    }
                }
                else
                {
                    Response.Write("<script>alert('抱歉!您还没上传文件')</script>");
                }
            }
            /// <summary>
            /// 根据文件名来导入excel到datatable
            /// </summary>
            /// <param name="fileUrl"></param>
            /// <returns></returns>
            public DataTable GetExcel(string fileUrl)
            {
                const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
                DataTable dt = null;
                OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
                try
                {
                    //打开连接
                    if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    //获取Excel的第一个Sheet名称
                    string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();
                    //查询sheet中的数据
                    string strSql = "SELECT * FROM [" + sheetName + "]";//sql语句,可以修改
                    OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    dt = ds.Tables[0];
                    return dt;
                }
                catch (Exception)
                {
    
                    throw;
                }
            }
            public bool InsertDb(DataTable dt)
            {
                int result=0;
                //1 首先是要 定义好字段
                string name = "";
                string money = "";
                //遍历存在的表格
                foreach (DataRow dr in dt.Rows)
                {
                    name = dr["name"].ToString().Trim();
                    money = dr["money"].ToString().Trim();
                    string sql = String.Format("insert into test(name,money)values('{0}','{1}')",name,money);//sql语句,测试用的
                    using (SqlConnection conn=new SqlConnection(connString))
                    {
                        conn.Open();
                        SqlCommand cmd = new SqlCommand(sql,conn);
                        result = cmd.ExecuteNonQuery();
                    }
                }
                if (result>0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
    }

    实际运行的页面

    数据库中内容:

    简单的过程就是这样了。。

    难度在于几个错误

    1 未在本机计算机注册.............解决:看开头介绍的

    2 其他的一些错误暂且未发现与程序相关的。可以自行解决。

    完整项目下载地址:http://files.cnblogs.com/files/fanling521/ExcelToDatabase.rar

    包含了excel文件

  • 相关阅读:
    trim标签:可以自定义字符串的截取规则
    登录框(用获取value值方法)
    C++在ARM Linux下的交叉编译
    happybase导入报错:thriftpy.parser.exc.ThriftParserError: ThriftPy does not support generating module with path in protocol 'c'
    Nginx报错总结
    ubuntu安装Nginx
    mqtt在debian strench 9 docker环境下的搭建
    evokly/kafka-connect-mqtt 不支持kafka集群部署
    树莓派mqtt安装
    kafka和mqtt的区别和联系
  • 原文地址:https://www.cnblogs.com/fanling521/p/5532437.html
Copyright © 2011-2022 走看看