vb.net excel导入sql如何自动获取excel的sheet名?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了vb.net excel导入sql如何自动获取excel的sheet名?相关的知识,希望对你有一定的参考价值。
Dim strPath As String = File1.PostedFile.FileName
If strPath = "" Then
Response.Write(" <script> alert( '请先选择文件 ') </script> ")
Response.End()
End If
'定义连接字符串
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strPath & "; Extended Properties=Excel 8.0;"
Try
Dim oleDbConnection As OleDbConnection = New OleDbConnection(sConnectionString)
oleDbConnection.Open()
'获取excel表
Dim dataTable As DataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
'获取sheet名,其中(0)(1)...(N): 按名称排列的表单元素
Dim tableName As String = dataTable.Rows(0)(2).ToString().Trim()
tableName = "[" & tableName.Replace(" ' ", " ") & "]"
'利用SQL语句从Excel文件里获取数据
Dim query As String = "SELECT 部门,全年任务,本年累计完成,上年同期完成,[完成全年任务的%],[可比增长%] FROM " & tableName
Dim dataset As DataSet = New DataSet()
Dim oleAdapter As OleDbDataAdapter = New OleDbDataAdapter(query, sConnectionString)
oleAdapter.Fill(dataset, "Rwb")
'SQL数据库连接
Dim sqlcon As SqlClient.SqlConnection = New SqlClient.SqlConnection("server=(local);database=test;user id=sa;password=123")
sqlcon.Open()
'从excel文件获得数据后,插入记录到SQL Server的数据表
Dim dataTable1 As DataTable = New DataTable()
Dim sqlDA1 As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter("SELECT 部门,全年任务, 本年累计完成,上年同期完成,[完成全年任务的%],[可比增长%] FROM Rwb ", sqlcon)
Dim sqlCB1 As SqlClient.SqlCommandBuilder = New SqlClient.SqlCommandBuilder(sqlDA1)
sqlDA1.Fill(dataTable1)
Dim dataRow11 As DataRow
For Each dataRow11 In dataset.Tables("qssrzb").Rows
'sql里数据dataRow1
Dim dataRow1 As DataRow = dataTable1.NewRow()
dataRow1("部门") = dataRow11("部门")
dataRow1("全年任务") = dataRow11("全年任务")
dataRow1("本年累计完成") = dataRow11("本年累计完成")
dataRow1("上年同期完成") = dataRow11("上年同期完成")
dataRow1("完成全年任务的%") = dataRow11("完成全年任务的%")
dataRow1("可比增长%") = dataRow11("可比增长%")
dataTable1.Rows.Add(dataRow1)
Next
Console.WriteLine("新插入 " & dataTable1.Rows.Count.ToString() & " 条记录 ")
sqlDA1.Update(dataTable1)
oleDbConnection.Close()
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try
怎么改?
如果EXCELsheet名是sheet1就可以获取,如果是别的自定义的就不行
/// <summary>
/// 上传文件到指定服务器文件
/// </summary>
/// <param name="fileUpload">.Net_FileUpload控件</param>
/// <param name="mag">out 返回上传是否成功</param>
/// <param name="fileName">out 返回上传到服务器上的文件名</param>
/// <returns>返回布尔类型。 上传成功返回true 失败false</returns>
public static bool UpLoad(FileUpload fileUpload, out string mag, out string fileName)
mag = null;
fileName = null;
bool flag = false;
//是否允许上载
bool fileAllow = false;
//设定允许上载的扩展文件名类型
string[] allowExtensions = ".xls", ".xlsx" ;
//检查是否有(是否包含)文件案
if (fileUpload.HasFile)
//取得上传文件之扩展文件名,并转换成小写字母
string fileExtension = System.IO.Path.GetExtension(fileUpload.FileName).ToLower();
//检查扩展文件名是否符合限定类型
for (int i = 0; i < allowExtensions.Length; i++)
if (fileExtension == allowExtensions[i])
fileAllow = true;
//符合上传文件类型
if (fileAllow)
try
//重命名文件名
fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + fileUpload.FileName;
//存储文件到文件夹
fileUpload.SaveAs(GetServerPath(fileName));
fileUpload.Dispose();
mag = "文件导入成功";
flag = true;
catch (Exception ex)
mag += ex.Message;
flag = false;
else
mag = "不允许上载:" + fileUpload.PostedFile.FileName + ",只能上传xls和xlsx的文件,请检查!";
flag = false;
else
mag = "请选择要导入的Excel文件!";
flag = false;
return flag;
调用 bool ft = ExcelImport.UpLoad(FileUpload1, out mag, out filePath);
FileUpload1为。net的上传控件
二,查询出Excel里面的所有工作薄名,根据OUT出来的存放excel的路径
/// <summary>
/// 获取EXCEL文件中的所有表名(模板类型)(SheetName)
/// </summary>
/// <param name="filepath">文件绝对路径</param>
/// <returns>ArrayList集合</returns>
public static ArrayList ExcelSheetName(string filepath)
ArrayList al = new ArrayList();
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
try
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable
(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] null, null, null, "TABLE" );
conn.Close();
foreach (DataRow dr in sheetNames.Rows)
al.Add(dr[2]);
catch (Exception e)
Logger.Error("ExcelImport.cs 页面 ExcelSheetName", e);
finally
conn.Close();
return al;
调用 //获取导入模板所有的模板表名
ArrayList al = ExcelImport.ExcelSheetName(UpPath);
3.进行工作薄名称的对比
string sheet = null;
//进行判断是否取到想要的sheet1
bool isExists = false;
for (int i = 0; i < al.Count; i++)
//获取模板表名
sheet = al[i].ToString();
if (sheet.Equals("sheet1"))
//EXCELsheet名是sheet1
isExists = true;
参考技术A --如果接受数据导入的表已经存在
insert into 表 select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$)
--如果导入数据并生成表
select * into 表 from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;DATABASE=c:\test.xls',sheet1$)
使用 vb.net 从 excel 文件更新 SQL 表
【中文标题】使用 vb.net 从 excel 文件更新 SQL 表【英文标题】:Update SQL Table from excel file with vb.net 【发布时间】:2016-08-25 12:09:01 【问题描述】:我编写了一个小程序,它在输入中获取一个 .xlsx 文件(此文件会定期更新),并将数据提取到一个 sql 表中。 我想通过将 excel 文件的内容与 sql 表的内容进行比较来定期更新此 sql 表,并将所有新行(如果存在)插入其中。 我搜索了许多解决方案,但没有成功。 我该怎么办?
我的实际代码如下:
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & SourceFile & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim RequeteExcelMat As String = "SELECT * FROM [feuil 1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(RequeteExcelMat, ExcelConnection)
Dim objDR As OleDbDataReader
Dim ConnexionBDDMat As New SqlConnection("SERVER=(local);DATABASE=MatStat;Trusted_Connection=True")
Try
ConnexionBDDMat.Open()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(ConnexionBDDMat)
bulkCopy.DestinationTableName = "dbo.Material"
'If SourceFile Content different from "Material" Sql Table Content Then
' Update "Material" Table by inserting the new rows from SourceFile
'Else
' MsgBox("Table is already updated")
'End If
Try
objDR = objCmdSelect.ExecuteReader
bulkCopy.WriteToServer(objDR)
objDR.Close()
ConnexionBDDMat.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
【问题讨论】:
【参考方案1】:我用它来处理一个小表来更新/插入数据从 Excel 到 SQL Server
Sub merge()
Dim CurConn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim SomeName As Worksheet
Dim Lastrow, Sql, n, i
Set SomeName = Sheets("SomeName")
Lastrow = SomeName.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To Lastrow
If i < Lastrow Then
Sql = Sql + "(" + CStr(SomeName.Range("A" & i).Value) + ", '" + SomeName.Range("B" & i).Value + "', '" + SomeName.Range("C" & i).Value + "', '" + SomeName.Range("D" & i).Value + "', '" + SomeName.Range("E" & i).Value + "', '" + SomeName.Range("F" & i).Value + "'),"
Else
Sql = Sql + "(" + CStr(SomeName.Range("A" & i).Value) + ", '" + SomeName.Range("B" & i).Value + "', '" + SomeName.Range("C" & i).Value + "', '" + SomeName.Range("D" & i).Value + "', '" + SomeName.Range("E" & i).Value + "', '" + SomeName.Range("F" & i).Value + "')"
End If
Next i
Set CurConn = New ADODB.Connection
CurConn.Open "Provider=SQLNCLI11;Server=SERVER\INSTANCE;Database=DATABASENAME;Trusted_Connection=yes;"
CurConn.CommandTimeout = 180
CurConn.CursorLocation = adUseClient
Sql = "MERGE [dbo].[SomeName] as target " _
& "USING (" _
& " SELECT [Userid]" _
& " ,[Login]" _
& " ,[name]" _
& " ,[org]" _
& " ,[pos]" _
& " ,[mail]" _
& " FROM (VALUES" _
& Sql _
& " ) as t([Userid],[Login],[name],[org],[pos],[mail])" _
& ") as source " _
& "ON target.[Userid] =source.[Userid] AND target.[Login] =source.[Login] " _
& "WHEN MATCHED THEN " _
& " UPDATE SET target.[name] =source.[name], " _
& " target.[org] =source.[org], " _
& " target.[pos] =source.[pos], " _
& " target.[mail] = Source.[mail] " _
& "WHEN NOT MATCHED THEN " _
& " INSERT ([Userid],[Login],[name],[org],[pos],[mail]) " _
& " VALUES (source.[Userid],source.[Login],source.[name],source.[org],source.[pos],source.[mail]); "
MsgBox ("Success!")
CurConn.Execute (Sql)
CurConn.Close
Set rst = Nothing
Set CurConn = Nothing
End Sub
将 Excel 表格转换为 VALUES (1,2,3,4,5,6),(7,8,9,10,11,12)..etc
很奇怪,但它工作正常。您可以采用此解决方案和 f.e.插入一些临时表,然后像上图那样合并它。
【讨论】:
【参考方案2】:使用相同的架构创建另一个名为 MaterialStaging 的表。批量插入此表而不是常规表。
然后,运行使用 MERGE 命令的存储过程来查找生产表和临时表之间的差异,并更新或插入差异。
【讨论】:
【参考方案3】:不要为此使用 VB。在 SQL Server 中执行此操作,并按照 Russ 的建议使用 MERGE 命令。
https://www.simple-talk.com/sql/learn-sql-server/the-merge-statement-in-sql-server-2008/
【讨论】:
以上是关于vb.net excel导入sql如何自动获取excel的sheet名?的主要内容,如果未能解决你的问题,请参考以下文章
我正在将 348k 行数据从 Excel 导入到 VB.net SQL。我得到这个错误:超时已过期