在工作中经常要将Excel中数据导入数据库,这里介绍一种方法。

  假如Excel中的数据如下:

  数据库建表如下:

  其中Id为自增字段:

  Excel中数据导入数据库帮助类如下:

 using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Data.SqlClient; /*
* 功能:文件操作类(读取、写入)
*/
namespace ExcelToDataBaseHelper.Service
{
class FileSvr
{
public 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[]["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[]; 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 = ;
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 Google_Offset2 (LNG,LAT,OFFSET_LNG,OFFSET_LAT) Values ('{0}','{1}',{2},{3})", lng, lat, offsetLNG, offsetLAT); String strConnection = ConfigurationSettings.AppSettings["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;
}
}
}

查看代码

  调用代码如下:

FileSvr fileSvr = new FileSvr();
System.Data.DataTable dt = fileSvr.GetExcelDatatable("../../excel/1.xlsx", "mapTable");
fileSvr.InsetData(dt);

  运行结果如下:

 

  相关文章:

  (1)将Excel中数据导入数据库(一)

  (2)将Excel中数据导入数据库(二)

  (3)将Excel中数据导入数据库(三)

  

将Excel中数据导入数据库(一)的更多相关文章

  1. 将Excel中数据导入数据库(三)

    上篇文章将Excel中数据导入数据库时,将从Excel读入的数据均转换成了数据库相应字段的类型,其实这是没有必要的,因为对于数据库各种类型的插入,均可以字符串格式插入.比如表WQ_SWMSAR_A字段 ...

  2. 将Excel中数据导入数据库(二)

    在上篇文章中介绍到将Excel中数据导入到数据库中,但上篇文章例子只出现了nvachar类型,且数据量很小.今天碰到将Excel中数据导入数据库中的Excel有6419行,其中每行均有48个字段,有i ...

  3. SpringBoot通过Ajax批量将excel中数据导入数据库

    Spring Boot通过Ajax上传Excel并将数据批量读取到数据库中 适合场景:需要通过excel表格批量向数据库中导入信息 操作流程 [1]前端上传一个excel表格 [2] 后端接收这个ex ...

  4. Excel表数据导入数据库表中

    ***Excel表数据导入到数据库表中 通过数据库表的模板做成‘Excel’表的数据导入到数据库相应的表中(注意:主表 和 从表的关系,要先导‘主表’在导入从表) 过程:通过数据库的导入工具—先导入为 ...

  5. mysqlconnector将EXCEL表数据导入数据库

    测试excel和脚本放在同一个目录 测试excel和脚本放在同一个目录 #!/usr/bin/env python #coding=utf-8 import xlrd import mysql.con ...

  6. SpringMVC 实现POI读取Excle文件中数据导入数据库(上传)、导出数据库中数据到Excle文件中(下载)

    读取Excale表返回一个集合: package com.shiliu.game.utils; import java.io.File; import java.io.FileInputStream; ...

  7. excel表格数据导入数据库Oracle

    方法一: 1.创建数据表 CREATE TABLE T_USER (   ID             VARCHAR2(32) primary key,   NAME           VARCH ...

  8. larave5.6 将Excel文件数据导入数据库代码实例

    <?php namespace App\Admin\Controllers; use App\AdminUser; use Illuminate\Http\Request; use Excel; ...

  9. java后端服务器读取excel将数据导入数据库

    使用的是easypoi,官网文档:http://easypoi.mydoc.io/ /** * 导入Excel文件 */ @PostMapping("/importTeacher" ...

随机推荐

  1. bzoj2592: [Usaco2012 Feb]Symmetry

    Description After taking a modern art class, Farmer John has become interested in finding geometric ...

  2. bzoj2152 聪聪可可

    Description 聪聪和可可是兄弟俩,他们俩经常为了一些琐事打起来,例如家中只剩下最后一根冰棍而两人都想吃.两个人都想玩儿电脑(可是他们家只有一台电脑)……遇到这种问题,一般情况下石头剪刀布就好 ...

  3. linux脚本后台运行

    一般情况下,linux运行脚本是随着终端的关闭而关闭的,那么怎么让脚本能够在后台运行并且不随终端关闭而关闭呢? 这时用到的是nohup命令 格式: nohup 脚本路径 & 例: nohup ...

  4. Python 派生类子类继承类

    1.创建list类的子类Namedlist,初始化新类,创建新对象实例johnny,检查对象类型,并使用list的一些功能来存储数据 >>> class Namedlist(list ...

  5. nokia5230 出厂设置

    你手机sim卡里的电话没事,还有储存卡里都没事,这个只是针对手机内存,如果不放心,拿你不用的手机卡,拔了内存卡格式化你好,我来具体说说吧首先如果你要单一恢复出厂设置,代码是输入*#7780#密码没改是 ...

  6. HDU3507 print artical

    题目大意:有N个数字a[N],每输出连续的一串,它的费用是 “这行数字的平方加上一个常数M”.问如何输出使得总费用最小.(n<=500000) 分析:动态规划方程为:dp[i]=dp[j]+M+ ...

  7. 安装ORACLE后,改变计算机名称,导致OracleDBConsoleOrcl服务无法启动

    错误信息: 启动oracledbconsoleorcl 服务提示 -- “--Windows不能再本地计算机启动oracledbconsoleorcl  有关更多信息,查阅系统事件日志,如果这是非Mi ...

  8. 输出一个对象的所有属性的值,可以不用反射机制,用JSON处理更方便

    String r = ""; ObjectMapper mapper = new ObjectMapper(); r = mapper.writeValueAsString(cre ...

  9. 前端实现 SVG 转 PNG

    http://fex.baidu.com/blog/2015/11/convert-svg-to-png-at-frontend/ 前言 svg 是一种矢量图形,在 web 上应用很广泛,但是很多时候 ...

  10. php表单数据验证类

    非常好用方便的表单数据验证类 <?php //验证类 class Fun{ function isEmpty($val) { if (!is_string($val)) return false ...