嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元微信扫码支付:2 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
用C#3层结构对Excel文件与SqlServer数据库进行导入与导出
1.将数据库中数据导出Excel文件中,其原理是先将数据库中的你所选择的一张表,先加载到DataGridView上,然后将DataGridView中的数据填充到Excel文件(*.xls|.xlsx)中。
将Excel文件加载到数据库中的代码
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace OperationExcel.DAL
{
public class ExcelToSQL
{
DBUnti _db = new DBUnti();
public void ExcelToSql()
{
OpenFileDialog fd = new OpenFileDialog();
fd.Filter = "导入SQL数据库|*.xlsx;*.xls";//打开文件对话框筛选器
if (fd.ShowDialog() == DialogResult.OK)
{
TransferData(fd.FileName, "Sheet1", _db.connstr); //数据库表中名称
}
}
public void TransferData(string excelFile, string sheetName, string connectionString)
{
DataSet ds = new DataSet();
try
{
string strConn = "";
strConn = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source=" excelFile ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; //版本不一样,都写一下
strConn = "Provider = Microsoft.ACE.OLEDB.12.0;Data Source=" excelFile ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'"; //版本不一样,都写一下
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand;
strExcel = string.Format("select * from [{0}$]", sheetName);
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds, sheetName);
//如果目标表不存在则创建,excel文件的第一行为列标题,从第二行开始全部都是数据记录
string strSql = string.Format("if not exists(select * from sysobjects where name = '{0}') create table {0}(", sheetName); //以sheetName为表名
foreach (DataColumn c in ds.Tables[0].Columns)
{
strSql = string.Format("[{0}] varchar(50),", c.ColumnName);
}
strSql = strSql.Trim(',') ")";
using (SqlConnection sqlconn = new SqlConnection(connectionString))
{
sqlconn.Open();
SqlCommand command = sqlconn.CreateCommand();
command.CommandText = strSql;
command.ExecuteNonQuery();
sqlconn.Close();
}
//用bcp导入数据
//excel文件中列的顺序必须和数据表的列顺序一致,因为数据导入时,是从excel文件的第二行数据开始,不管数据表的结构是什么样的,反正就是第一列的数据会插入到数据表的第一列字段中,第二列的数据插入到数据表的第二列字段中,以此类推,它本身不会去判断要插入的数据是对应数据表中哪一个字段的
using (SqlBulkCopy bcp = new SqlBulkCopy(connectionString))
{
bcp.BatchSize = 100;//每次传输的行数
bcp.NotifyAfter = 100;//进度提示的行数
bcp.DestinationTableName = sheetName;//目标表
bcp.WriteToServer(ds.Tables[0]);
}
MessageBox.Show("导入数据库成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "导入失败!");
}
}
}
}