将Excel文件数据库导入SQL Server的三种方案

1 篇文章 0 订阅
1 篇文章 0 订阅
//方案一: 通过OleDB方式获取Excel文件的数据,然后通过DataSet中转到SQL Server

openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";

if(openFileDialog.ShowDialog()==DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(openFileDialog.FileName);
string filePath = fileInfo.FullName;
string connExcel = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";

try
{
OleDbConnection oleDbConnection = new OleDbConnection(connExcel);
oleDbConnection.Open();

//获取excel表
DataTable dataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

//获取sheet名,其中[0][1]...[N]: 按名称排列的表单元素
string tableName = dataTable.Rows[0][2].ToString().Trim();
tableName = "[" + tableName.Replace("'","") + "]";

//利用SQL语句从Excel文件里获取数据
//string query = "SELECT classDate,classPlace,classTeacher,classTitle,classID FROM " + tableName;
string query = "SELECT 日期,开课城市,讲师,课程名称,持续时间 FROM " + tableName;
dataSet = new DataSet();

//OleDbCommand oleCommand = new OleDbCommand(query, oleDbConnection);
//OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(query,connExcel);

oleAdapter.Fill(dataSet,"gch_Class_Info");

//dataGrid1.DataSource = dataSet;
//dataGrid1.DataMember = tableName;
dataGrid1.SetDataBinding(dataSet,"gch_Class_Info");

//从excel文件获得数据后,插入记录到SQL Server的数据表
DataTable dataTable1 = new DataTable();

SqlDataAdapter sqlDA1 = new SqlDataAdapter(@"SELECT classID, classDate,
classPlace, classTeacher, classTitle, durativeDate FROM gch_Class_Info",sqlConnection1);

SqlCommandBuilder sqlCB1 = new SqlCommandBuilder(sqlDA1);

sqlDA1.Fill(dataTable1);

foreach(DataRow dataRow in dataSet.Tables["gch_Class_Info"].Rows)
{
DataRow dataRow1 = dataTable1.NewRow();

dataRow1["classDate"] = dataRow["日期"];
dataRow1["classPlace"] = dataRow["开课城市"];
dataRow1["classTeacher"] = dataRow["讲师"];
dataRow1["classTitle"] = dataRow["课程名称"];
dataRow1["durativeDate"] = dataRow["持续时间"];

dataTable1.Rows.Add(dataRow1);
}

Console.WriteLine("新插入 " + dataTable1.Rows.Count.ToString() + " 条记录");
sqlDA1.Update(dataTable1);

oleDbConnection.Close();

}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}



//方案二: 直接通过SQL语句执行SQL Server的功能函数将Excel文件转换到SQL Server数据库

OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Excel files(*.xls)|*.xls";

SqlConnection sqlConnection1 = null;

if(openFileDialog.ShowDialog()==DialogResult.OK)
{
string filePath = openFileDialog.FileName;

sqlConnection1 = new SqlConnection();
sqlConnection1.ConnectionString = "server=(local);integrated security=SSPI;initial catalog=Library";

//import excel into SQL Server 2000
/*string importSQL = "SELECT * into live41 FROM OpenDataSource" +
"('Microsoft.Jet.OLEDB.4.0','Data Source=" + "\"" + "E:\\022n.xls" + "\"" +
"; User ID=;Password=; Extended properties=Excel 5.0')...[Sheet1$]";*/

//export SQL Server 2000 into excel
string exportSQL = @"EXEC master..xp_cmdshell
'bcp Library.dbo.live41 out " + filePath + "-c -q -S" + "\"" + "\"" +
" -U" + "\"" + "\"" + " -P" + "\"" + "\"" + "\'";

try
{
sqlConnection1.Open();

//SqlCommand sqlCommand1 = new SqlCommand();
//sqlCommand1.Connection = sqlConnection1;
//sqlCommand1.CommandText = importSQL;
//sqlCommand1.ExecuteNonQuery();
//MessageBox.Show("import finish!");

SqlCommand sqlCommand2 = new SqlCommand();
sqlCommand2.Connection = sqlConnection1;
sqlCommand2.CommandText = exportSQL;
sqlCommand2.ExecuteNonQuery();
MessageBox.Show("export finish!");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

if(sqlConnection1!=null)
{
sqlConnection1.Close();
sqlConnection1 = null;
}




//方案三: 通过到入Excel的VBA dll,通过VBA接口获取Excel数据到DataSet

OpenFileDialog openFile = new OpenFileDialog();
openFile.Filter = "Excel files(*.xls)|*.xls";

ExcelIO excelio = new ExcelIO();

if(openFile.ShowDialog()==DialogResult.OK)
{
if(excelio!=null)
excelio.Close();

excelio = new ExcelIO(openFile.FileName);
object[,] range = excelio.GetRange();
excelio.Close();


DataSet ds = new DataSet("xlsRange");

int x = range.GetLength(0);
int y = range.GetLength(1);

DataTable dt = new DataTable("xlsTable");
DataRow dr;
DataColumn dc;

ds.Tables.Add(dt);

for(int c=1; c<=y; c++)
{
dc = new DataColumn();
dt.Columns.Add(dc);
}

object[] temp = new object[y];

for(int i=1; i<=x; i++)
{
dr = dt.NewRow();

for(int j=1; j<=y; j++)
{
temp[j-1] = range[i,j];
}

dr.ItemArray = temp;
ds.Tables[0].Rows.Add(dr);
}

dataGrid1.SetDataBinding(ds,"xlsTable");

if(excelio!=null)
excelio.Close();
}



//其中,方案三中使用到的类方法如下:

using System;
using System.Reflection;
using System.IO;
using System.Windows.Forms;
using Excel;

namespace Excel2SQL
{
public class ExcelIO
{
private Excel.ApplicationClass oExcel;
private Excel.Workbook oBook;
private Excel.Worksheet oSheet;
private Excel.Range oRange;

private object missing = Type.Missing;

public ExcelIO()
{
}

public ExcelIO(string inFile)
{
object fileName = inFile;

oExcel = new Excel.ApplicationClass();
oBook = null;
oSheet = null;
oRange = null;

oExcel.Visible = false;
oExcel.ScreenUpdating = false;
oExcel.DisplayAlerts = false;

oBook = oExcel.Workbooks.Open(inFile, missing, missing,
missing, missing, missing, missing, missing, missing,
missing, missing, missing, missing, missing, missing);
}

public object[,] GetRange()
{
oSheet = (Worksheet)oBook.Worksheets[1];
oRange = oSheet.get_Range("A1", missing);
oRange = oRange.get_End(Excel.XlDirection.xlToRight);
oRange = oRange.get_End(Excel.XlDirection.xlDown);
string downAddress = oRange.get_Address(false, false, XlReferenceStyle.xlA1, missing, missing);
oRange = oSheet.get_Range("A1", downAddress);
object[,] values = (object[,])oRange.Value2;

return values;
}

public void Close()
{
oRange = null;
oSheet = null;
if(oBook != null)
oBook.Close(false, missing, missing);
oBook = null;
if(oExcel != null)
oExcel.Quit();
oExcel = null;
}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
可以使用Python中的pandas库和pyodbc库来实现将Excel数据批量导入SQL Server数据库。 首先需要安装pandas库和pyodbc库,可以使用以下命令进行安装: ``` pip install pandas pip install pyodbc ``` 然后可以按照以下步骤进行操作: 1. 使用pandas库读取Excel数据,可以使用以下代码: ``` import pandas as pd df = pd.read_excel('data.xlsx') ``` 其中,`data.xlsx`是要导入Excel文件名,可以根据实际情况修改。 2. 连接SQL Server数据库,可以使用以下代码: ``` import pyodbc conn = pyodbc.connect('Driver={SQL Server};' 'Server=server_name;' 'Database=database_name;' 'Trusted_Connection=yes;') ``` 其中,`server_name`和`database_name`分别是SQL Server服务器名称和数据库名称,可以根据实际情况修改。 3. 将数据导入SQL Server数据库,可以使用以下代码: ``` cursor = conn.cursor() for index, row in df.iterrows(): cursor.execute("INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)", row['column1'], row['column2'], row['column3']) conn.commit() ``` 其中,`table_name`是要导入数据的表格名称,`column1`、`column2`和`column3`分别是表格中要导入的列名,可以根据实际情况修改。 4. 关闭数据库连接: ``` conn.close() ``` 完整代码示例: ``` import pandas as pd import pyodbc df = pd.read_excel('data.xlsx') conn = pyodbc.connect('Driver={SQL Server};' 'Server=server_name;' 'Database=database_name;' 'Trusted_Connection=yes;') cursor = conn.cursor() for index, row in df.iterrows(): cursor.execute("INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)", row['column1'], row['column2'], row['column3']) conn.commit() conn.close() ``` 注意:在实际操作中,需要根据实际情况修改代码中的参数,例如Excel文件名、SQL Server服务器名称、数据库名称、表格名称和列名等。同时,在执行INSERT语句时,需要根据实际情况修改VALUES后面的参数个数和顺序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值