我想将一张excel文件导入到访问数据库
Private Sub Commande9_Click()
Dim filepath As String
filepath = "C:\Users\TXZG6067\Desktop\com.xlsx"
DoCmd.TransferSpreadsheet acImport, , "ImportFromExcel", filepath, True
End Sub
我需要你的帮助,谢谢。
答案 0 :(得分:1)
要将Excel文件或其中一个工作表导入数据库,您必须执行以下步骤:
1)将该表/文件转换为逗号分隔符。使用Save as
选项进行转换。
2)使用StreamReader
课程阅读此文件。验证列长度和每列包含的数据。
3)使用StringBuilder
类创建查询(推荐),但您也可以使用string
。如:
StringBuilder Sb = new StringBuilder("Insert Into table_name Values(");
foreach(row in dt.rows)
{
sb = null;
int j = 1;
for(int i=0; i<columns_Count-1 ; i++) //Column count minus one to handle last column data
{
Sb.Append("'"+row[0][i]+"',");
j++;
}
if(j == columns_Count) //last column appends data without comma
{
Sb.Append("'"+row[0][columns_Count]+"'");
}
Sb.Append(")");
//execute insert query here
}
答案 1 :(得分:1)
您可以在Excel VBA(ADO)中尝试此操作,假设您的数据位于A列到C列等等。
Dim dbpath as String, _
x as long, _
rs As ADODB.Recordset, _
cn As ADODB.Connection
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
dbPath = /your db path
cn.Open "Provider=Microsoft.ace.OLEDB.12.0;Data Source=" & dbPath
rs.Open "Consolidated", cn, adOpenKeyset, adLockOptimistic, adCmdTable
For x = 2 To LastRow
rs.AddNew
rs.Fields("Fieldnm1") = Range("A" & x).value
rs.Fields("Fieldnm2") = Range("B" & x).value
rs.Fields("Fieldnm3") = Range("C" & x).value
rs.Update
Next x
rs.Close
Set cn = Nothing
Set rs = Nothing
答案 2 :(得分:0)
指定工作表名称:
DoCmd.TransferSpreadsheet acImport, , "ImportFromExcel", filepath, True, "WorksheetName$"
或:
DoCmd.TransferSpreadsheet acImport, , "ImportFromExcel", filepath, True, "WorksheetName!"
答案 3 :(得分:0)
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9 , _
"TableOrQuery","YourExcelPath", _
True, "TheNameofTheSheetYouWant"
答案 4 :(得分:0)
语法:
expression .TransferSpreadsheet(TransferType, SpreadsheetType, TableName, FileName, HasFieldNames, Range, UseOA)
示例:
DoCmd.TransferSpreadsheet acImport, 3, _
"Employees","C:\Lotus\Newemps.wk3", True, "A1:G12"
您必须为其提供SpreadsheetType,有关SpreadsheetType
的详细信息,请参阅以下链接:
https://msdn.microsoft.com/en-us/library/office/ff196017.aspx