search
HomeSoftware TutorialOffice SoftwareSource code implementation of Excel importing into SQLServer

A source code that can import excel into sqlserver

Give you a code to upload data directly to SqlServer in Excel:

Can be modified appropriately,

FormName is the table in the database,

DBString is the database connection field,

Sub UploadData()

If FormName = "" Then Exit Sub

Dim a As New ADODB.Connection

Dim b As New ADODB.Recordset

a.Open DBString

RowCount = Application.CountA(Rows("1:1"))

For i = 2 To application.counta(range("a:a"))

sql = """

Set b = Nothing

For j = 1 To RowCount - 1

sql = sql & "'" & Cells(i, j) & "', "

Next

sql = "insert into " & FormName & "values(" & sql & "'" & Cells(i, RowCount) & "')"

b.Open Source:=sql, ActiveConnection:=a

Next

MsgBox "OK!"

End Sub

There are various methods, just find a suitable one,

To complete your task, you need to understand the connection properties of the database. The following are the connection fields, which can be modified according to your actual situation. You have to set the basic parameters yourself,

Provider=SQLOLEDB.1;Persist Security Info=False;User id=md-inspection;PWD=mdOL20!31)25;Initial Catalog=Online_Inspection;Data Source=Cduvmdb01,1433

In addition, relevant references need to be added to the VBE page:

Source code implementation of Excel importing into SQLServer

A C Excel source code for importing database

Environment: c#.2005 Access Sql

1. Insert the DataTable into the database

public static void DataTableToDB()

{

string _strExcelFileName = @"D:\example.xls";

DataTable dtExcel = ExcelToDataTable(_strExcelFileName,"Sheet1");

for (int i = 0; i

{

InsertDataToAccess(dtExcel.Rows[i][0].ToString(), float.Parse(dtExcel.Rows[i][1].ToString()));

}

}

2. Read Excel data into DataTable

public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)

{

string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" strExcelFileName ";" "Extended Properties=Excel 5.0;";

string strExcel = string.Format("select * from [{0}$]", strSheetName);

DataSet ds = new DataSet();

using (OleDbConnection conn = new OleDbConnection(strConn))

{

conn.Open();

OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);

adapter.Fill(ds, strSheetName);

conn.Close();

}

return ds.Tables[strSheetName];

}

3. Insert data into Access database table

public static void InsertDataToAccess(string _strPara,float _fPara)

{

OleDbConnection oleDbConn = new OleDbConnection();

oleDbConn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\ExcelData.mdb;User Id=admin;Password=;";

oleDbConn.Open();

string strInsertString = "INSERT INTO tb_excelData (strCollumn1,fCollumn2) VALUES (@strCollumn1,@fCollumn2)";

OleDbCommand oComm = new OleDbCommand(strInsertString, oleDbConn);

oComm.Parameters.Add("@strCollumn1", OleDbType.Char , 50);

oComm.Parameters["@strCollumn1"].Value = _strPara;

oComm.Parameters.Add("@fCollumn2", OleDbType.Double);

oComm.Parameters["@fCollumn2"].Value = _fPara;

ocomm.ExecuteNonQuery();

oleDbConn.Close();

}

How to batch import multiple excel data files into another excel file table source code

code show as below:

Sub file merge()

Dim wb As Workbook, sh As Worksheet, pT As String, wb2 As Workbook, t

t = Timer

'Check whether any unrelated workbooks are opened

If Workbooks.Count > 1 Then

MsgBox "Close other open workbooks"

Exit Sub

End If

'Specify the folder where the file is located

With Application.FileDialog(msoFileDialogFolderPicker)

.Show

If .SelectedItems.Count = 0 Then Exit Sub 'If you press Cancel or X closes the dialog box, exit directly

pT = .SelectedItems(1)

End With

Application.ScreenUpdating = False 'Turn off screen refresh

Application.DisplayAlerts = False 'Close dialog box

'Create a new worksheet named New.xls

Set wb = Workbooks.Add

shJS = wb.Worksheets.Count

fn = Dir(pT & "\*.xls")

While fn """

If fn = wb.Name Then GoTo gg

i = i 1

If i > shJS Then

Set sh = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))

End If

Set wb2 = Workbooks.Open(fn, ReadOnly = True)

wb2.Worksheets(1).Cells.Copy wb.Worksheets(i).Cells

wb.Worksheets(i).Name = Left(fn, Len(fn) - 4)

wb2.Close

gg:

fn = Dir

Wend

wb.SaveAs pT & "\new.xls"

wb.Close

Application.ScreenUpdating = True 'Turn on screen refresh

Application.DisplayAlerts = True 'Open dialog box

MsgBox "Shared Time" & Timer - t & "Seconds. Generate a new file new.xls"

End Sub

Complete code for importing data from excel to delphi

Table A in the database has fields A1, A2, A3, a4, a5

Spreadsheet d\:shuju.xls

Contains items b1, b2, b3, b4, b5

insert into dbo.A

(a1,a2,a3,a4,a5)

SELECT b1,b2,b3,b4,b5

FROM OPENDATASOURCE ('Microsoft.Jet.OLEDB.4.0',

'Data Source=d:\shuju.xls;Extended Properties=EXCEL 8.0' )...[Sheet1$] Rowset_1

In this way, you can import it. Of course, you can also use the control TXLSFile. If you need it, you can ask me for it

mchestnut@163.com

The above is the detailed content of Source code implementation of Excel importing into SQLServer. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Excel办公网. If there is any infringement, please contact admin@php.cn delete
How to change Excel table styles and remove table formattingHow to change Excel table styles and remove table formattingApr 19, 2025 am 11:45 AM

This tutorial shows you how to quickly apply, modify, and remove Excel table styles while preserving all table functionalities. Want to make your Excel tables look exactly how you want? Read on! After creating an Excel table, the first step is usual

Subtotals in Excel: how to insert, use and removeSubtotals in Excel: how to insert, use and removeApr 19, 2025 am 10:26 AM

This tutorial shows you how to use Excel's Subtotal feature to efficiently summarize data within groups of cells. Learn how to sum, count, or average, display or hide details, copy only subtotals, and remove subtotals altogether. Large datasets can

Calculate CAGR in Excel: Compound Annual Growth Rate formulasCalculate CAGR in Excel: Compound Annual Growth Rate formulasApr 19, 2025 am 10:25 AM

This tutorial explains the Compound Annual Growth Rate (CAGR) and provides multiple ways to calculate it in Excel. CAGR measures the average annual growth of an investment over a specific period, offering a clearer picture than simple year-to-year g

Excel SUBTOTAL function with formula examplesExcel SUBTOTAL function with formula examplesApr 19, 2025 am 09:59 AM

The tutorial explains the specificities of the SUBTOTAL function in Excel and shows how to use Subtotal formulas to summarize data in visible cells. In the previous article, we discussed an automatic way to insert subtotals in Excel by us

The new Excel IFS function instead of multiple IFThe new Excel IFS function instead of multiple IFApr 19, 2025 am 09:54 AM

This tutorial introduces the Excel IFS function, a streamlined alternative to nested IF statements. It simplifies creating formulas with multiple conditions and improves readability. Available in Excel 365, 2021, and 2019, IFS significantly reduces

I Always Name Ranges in Excel, and You Should TooI Always Name Ranges in Excel, and You Should TooApr 19, 2025 am 12:56 AM

Improve Excel efficiency: Make good use of named regions By default, Microsoft Excel cells are named after column-row coordinates, such as A1 or B2. However, you can assign more specific names to a cell or cell range, improving navigation, making formulas clearer, and ultimately saving time. Why always name regions in Excel? You may be familiar with bookmarks in Microsoft Word, which are invisible signposts for the specified locations in your document, and you can jump to where you want at any time. Microsoft Excel has a bit of a unimaginative alternative to this time-saving tool called "names" and is accessible via the name box in the upper left corner of the workbook. Related content #

Insert checkbox in Excel: create interactive checklist or to-do listInsert checkbox in Excel: create interactive checklist or to-do listApr 18, 2025 am 10:21 AM

This tutorial shows you how to create interactive Excel checklists, to-do lists, reports, and charts using checkboxes. Checkboxes, also known as tick boxes or selection boxes, are small squares you click to select or deselect options. Adding them to

Excel Advanced Filter – how to create and useExcel Advanced Filter – how to create and useApr 18, 2025 am 10:05 AM

This tutorial unveils the power of Excel's Advanced Filter, guiding you through its use in retrieving records based on complex criteria. Unlike the standard AutoFilter, which handles simpler filtering tasks, the Advanced Filter offers precise contro

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool