Insert excel data into DB

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)
        {
            //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;
        }
    }
}

时间: 2024-10-26 14:59:25

Insert excel data into DB的相关文章

以Excel 作为Data Source,将data导入db

将Excel作为数据源,将数据导入db,是SSIS的一个简单的应用,下图是示例Excel,数据列是code和name 第一部分,Excel中的数据类型是数值类型 1,使用SSDT创建一个package,创建Excel data source component,SSDT会在Connection Managers中创建一个Excel的connection 由于示例Excel的首行是列名,所以需要勾选"First row has column names",Excel connection

数据库内存泄漏——A SQLiteConnection object for database &#39;/data/data/.../databases/....db&#39; was leaked!

详细异常: A SQLiteConnection object for database '/data/data/.../database/....db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed 明显是数据库操作异常,数据库对象被锁,明确告诉你对象长久不用需要关闭.

A SQLiteConnection object for database &#39;/data/data/.../databases/....db&#39; was leaked!

详细异常: A SQLiteConnection object for database '/data/data/.../databases/....db' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed 明显是数据库操作异常,数据库对象被锁,明确告诉你对象长久不用需要关闭.

lessons learned from the Qlikview loads the data from DB into qvd files

Qlikview加载数据库里的数据,一般都是通过ODBC和数据库进行连接,然后把数据库里的相应的表里的数据加载到本地的disk folder里,后期就可以直接从用本地的disk folder里的QVD的文件获取数据来做DASHBOARD了.本人一开始加载数据的时候老是会死机,原因是我在加载好一个数据库里的表里数据到本地的QVD文件后,没有及时的从内存里把相应的表给删除掉,导致了多个表都在内存里,而且他们还会通过相同的自动名称进行关联,有时候QLIKVIEW 会自动的产生很多个synthetic的

读取Excel二进制写入DB,并从DB中读取生成Excel文件

namespace SendMailSMSService { class Program { static void Main(string[] args) { var connString = SqlDataHelper.GetConnectionString<FileContent>(); //读取Excle文件并写入表中 var bytes = File.ReadAllBytes("a.xlsx"); var entity = new FileContent { Fi

Convert Excel data to MDB file

所需组件: microsoft ado ext. 2.8 for ddl and security 或者更新的组件. 添加: using ADOX;using System.Runtime.InteropServices;using System.IO; 然后利用OleDbCommand组件,设置其2个链接,一个链接负责查找并打开excel数据源,另一个链接负责将数据源插入到MDB文件中. 操作页面: 后台源码: private void button1_Click(object sender,

简单的批量读取外部insert文并插入DB

package com.tongxiang.item.base.dao; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import ja

使用Statement 的addBatch方法批量导入数据库

1 try { 2 boolean auto = conn.getAutoCommit(); 3 conn.setAutoCommit(false); 4 5 Statement stat = conn.createStatement(); 6 Iterator<String> it = sourcetime.iterator(); 7 // System.out.println("get sourcetime iterator successfully"); 8 whil

Python实现农历生日提醒功能

前言: 某天突发奇想,想要实现一个农历生日提醒.这个时候有了如下的大概思路: 获取农历   -->    匹配    -->     提醒 发现实现这个需求最主要的在获取农历这一块,后边两个不是什么巨大挑战.遂查阅一番资料,发现数据库可以实现阳历转阴历功能.在数据库这一块,我是在是小菜,看不懂存储过程.蛋疼!直接放弃改用其他思路.思考了许久,想到可以通过爬虫爬取现成的日历信息,存库再进行匹配.所以,现在思路如下: 爬取农历存库   -->    匹配姓名表    -->     提