将Excel表中的数据导入到数据库

时间:2021-07-12 23:56:08

网上查到的有参考价值的就一家,自己调试发现可行。感谢原创文章:将Excel中数据导入数据库(一)

    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 ConsoleApplication1
{
class FileSvr
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
FileSvr fileSvr = new FileSvr();
System.Data.DataTable dt = fileSvr.GetExcelDatatable("F:\\ExcelToDB1.xls", "mapTable");
int count = fileSvr.InsetData(dt);
Console.WriteLine(count);
} /// <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 words = "";
string wordKind = "";
string fellingkind = "";
string power = "";
string polar = "";
string assistfellingkind = "";
string assistpower = "";
string assistpolar = "";
foreach (DataRow dr in dt.Rows)
{
words = dr["Words"].ToString().Trim();
wordKind = dr["wordKind"].ToString().Trim();
fellingkind = dr["fellingkind"].ToString().Trim();
power = dr["power"].ToString().Trim();
polar = dr["polar"].ToString().Trim();
assistfellingkind = dr["assistfellingkind"].ToString().Trim();
assistpower = dr["assistpower"].ToString().Trim();
assistpolar = dr["assistpolar"].ToString().Trim();
//sw = string.IsNullOrEmpty(sw) ? "null" : sw;
//kr = string.IsNullOrEmpty(kr) ? "null" : kr;
string strSql = string.Format("Insert into tb_MyFellingWords (Words,wordKind,fellingkind,power,polar,assistfellingkind,assistpower,assistpolar) Values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", words, wordKind, fellingkind, power, polar, assistfellingkind, assistpower, assistpolar); //连接帐套数据库, 要跟据帐套参数定义创建连接字符串
string sConn = "Server={0};Database={1};User ID={2};Password={3};Connection TimeOut=180;";
sConn = String.Format(sConn,
"20120906-1046",
"CSFramework3.Test",
"sa",
"sa");
SqlConnection sqlConnection = new SqlConnection(sConn);
try
{
// SqlConnection sqlConnection = new SqlConnection(strConnection);
sqlConnection.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = strSql;
sqlCmd.Connection = sqlConnection;
SqlDataReader sqlDataReader = sqlCmd.ExecuteReader();
i++;
Console.WriteLine(i);
sqlDataReader.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
sqlConnection.Close();
}
//if (opdb.ExcSQL(strSql))
// i++;
}
return i;
}
}
}