我创建了一个演示,用于将 Excel 文件上传到 webserver,然后将数据从它复制到 SQL server db。它运行良好。
ASPX 设计:
<table>
<tr>
<td>
<span style="color: Red">*</span>Attach Excel file
</td>
<td>
<asp:FileUpload ID="fileuploadExcel" runat="server" />
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSend" runat="server" Text="Export" onclick="btnSend_Click" />
</td>
</tr>
</table>
后面的代码:
private String strConnection = "Data Source=Test-PC;Initial Catalog=ExcelMapping;User ID=Test;Password=Test";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSend_Click(object sender, EventArgs e)
{
//file upload path
string path = fileuploadExcel.PostedFile.FileName;
fileuploadExcel.SaveAs(Server.MapPath(path));
//Create connection string to Excel work book
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(path) + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [lat],[long] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
DataSet ds = new DataSet();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "Test";
sqlBulk.ColumnMappings.Add(0, 1);
sqlBulk.ColumnMappings.Add(1, 2);
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
}
但是当我在现有应用程序中使用相同的代码时。打开与 Excel 的连接时出现错误
'Microsoft.ACE.OLEDB.12.0' 提供程序未在本地计算机上注册
请建议我如何解决这个问题。