博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# Excel数据导入到数据库
阅读量:4963 次
发布时间:2019-06-12

本文共 3509 字,大约阅读时间需要 11 分钟。

http://www.jb51.net/article/44743.htm

 

假如Excel中的数据如下:

数据库建表如下:

其中Id为自增字段:

代码:

复制代码 代码如下:
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.OleDb;
using System.Configuration;
using System.Data.SqlClient;

namespace InExcelOutExcel

{
    public partial class ExcelToDB : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            FileSvr fileSvr = new FileSvr();
            System.Data.DataTable dt = fileSvr.GetExcelDatatable("C:\\Users\\NewSpring\\Desktop\\Demo\\InExcelOutExcel\\InExcelOutExcel\\excel\\ExcelToDB.xlsx", "mapTable");
            fileSvr.InsetData(dt);
        }
    }
    class FileSvr
    {
        /// <summary>
        /// Excel数据导入Datable
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <param name="table"></param>
        /// <returns></returns>
        public System.Data.DataTable GetExcelDatatable(string fileUrl, string table)
        {

OpenFileDialog dialog = new OpenFileDialog(); dialog.Multiselect = true;

//该值确定是否可以选择多个文件 dialog.Title = "请选择文件夹";

dialog.Filter = "所有文件(*.*)|*.*"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string file = dialog.FileName; }

            //office2007之前 仅支持.xls
            //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";
            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;
            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";

            System.Data.DataTable dt = null;

            //建立连接
            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));
            try
            {
                //打开连接
                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
                {
                    conn.Open();
                }

                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                //获取Excel的第一个Sheet名称

                string sheetName = schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();

                //查询sheet中的数据

                string strSql = "select * from [" + sheetName + "]";
                OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
                DataSet ds = new DataSet();
                da.Fill(ds, table);
                dt = ds.Tables[0];

                return dt;

            }
            catch (Exception exc)
            {
                throw exc;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }

        }

        /// <summary>

        /// 从System.Data.DataTable导入数据到数据库
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public int InsetData(System.Data.DataTable dt)
        {
            int i = 0;
            string lng = "";
            string lat = "";
            string offsetLNG = "";
            string offsetLAT = "";

            foreach (DataRow dr in dt.Rows)

            {
                lng = dr["LNG"].ToString().Trim();
                lat = dr["LAT"].ToString().Trim();
                offsetLNG = dr["OFFSET_LNG"].ToString().Trim();
                offsetLAT = dr["OFFSET_LAT"].ToString().Trim();

                //sw = string.IsNullOrEmpty(sw) ? "null" : sw;

                //kr = string.IsNullOrEmpty(kr) ? "null" : kr;

                string strSql = string.Format("Insert into DBToExcel (LNG,LAT,OFFSET_LNG,OFFSET_LAT) Values ('{0}','{1}',{2},{3})", lng, lat, offsetLNG, offsetLAT);

                string strConnection = ConfigurationManager.ConnectionStrings["ConnectionStr"].ToString();

                SqlConnection sqlConnection = new SqlConnection(strConnection);
                try
                {
                    // SqlConnection sqlConnection = new SqlConnection(strConnection);
                    sqlConnection.Open();
                    SqlCommand sqlCmd = new SqlCommand();
                    sqlCmd.CommandText = strSql;
                    sqlCmd.Connection = sqlConnection;
                    SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
                    i++;
                    sqlDataReader.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    sqlConnection.Close();

                }

                //if (opdb.ExcSQL(strSql))
                //    i++;
            }
            return i;
        }
    }
}

运行结果:

转载于:https://www.cnblogs.com/LuoEast/p/7742566.html

你可能感兴趣的文章
混沌分形之迭代函数系统(IFS)
查看>>
边框圆角Css
查看>>
使用Busybox制作根文件系统
查看>>
jpg图片在IE6、IE7和IE8下不显示解决办法
查看>>
delphi之模糊找图
查看>>
Javascript模块化编程的写法
查看>>
oracle 使用job定时自动重置sequence
查看>>
在项目中加入其他样式
查看>>
OMAPL138学习----DSPLINK DEMO解析之SCALE
查看>>
restframework CBV试图的4种方式
查看>>
大图居中,以1920px为例
查看>>
[C陷阱和缺陷] 第7章 可移植性缺陷
查看>>
linux中configure文件默认执行结果所在位置
查看>>
Windows向Linux上传文件夹
查看>>
20180104-高级特性-Slice
查看>>
6个SQL Server 2005性能优化工具介绍
查看>>
nginx启动、关闭命令、重启nginx报错open() "/var/run/nginx/nginx.pid" failed
查看>>
BZOJ 3097 Hash Killer I
查看>>
UINavigationController的视图层理关系
查看>>
html阴影效果怎么做,css 内阴影怎么做
查看>>