Excel数据导入SQL Server

基本有2种方案,都是无需安装Office的方案

Ole DB读取 + BulkCopy

获取Excel各个SheetName

//连接串

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";

OleDbConnection conn = new OleDbConnection(strConn); 



conn.Open(); 



//返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等  

DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); 



//包含excel中表名的字符串数组

string[] strTableNames = new string[dtSheetName.Rows.Count];

for (int k = 0; k < dtSheetName.Rows.Count; k++)

{

    strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();

}

return strTableNames;

NPOI读取 + BulkCopy

获取Excel各个SheetName

using (FileStream fs = File.OpenRead(txtPath.Text)) //打开myxls.xls文件

{

    HSSFWorkbook wk = new HSSFWorkbook(fs);

    string[] strTableNames = new string[wk.NumberOfSheets];

    for (int i = 0; i < wk.NumberOfSheets; i++) //NumberOfSheets是myxls.xls中总共的表数

    {

        strTableNames[i] = wk.GetSheetAt(i).SheetName;

    }

    return strTableNames;

}

SQLBulkCopy数据写入

using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))

{

    //bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);

    bcp.BatchSize = 100;//每次传输的行数

    bcp.NotifyAfter = 100;//进度提示的行数

    bcp.DestinationTableName = sheetName;//目标表

    bcp.WriteToServer(ds.Tables[0]);

}

你可能感兴趣的:(SQL Server)