我想将一个 excel 文件复制到我的数据库中。我遇到的问题是我似乎无法将路径复制到代码隐藏中。这是我的asp代码:
<asp:FileUpload id="FileUploadControl" runat="server" />
<asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" />
<br /><br />
<asp:Label runat="server" id="StatusLabel" text="Upload status: " />
如果我在路径中硬编码,那么我的代码将起作用:
string path = @"C:\Users\moynik\Desktop\datatest.xls";
但如果我使用以下行,我只会得到一条无法正常工作的不同路径。
string path = Path.GetFullPath(FileUploadControl.FileName);
但我需要使我的路径动态化,以便用户可以从自己的计算机上的不同目的地上传。谁能帮我吗。这是工作并将excel文件复制到我的数据库的功能
如果这是不可能的,如果他们想到一个解决方案,有人可以帮助我解决问题。谢谢
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string path = @"C:\Users\moynik\Desktop\datatest.xls";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
using (OleDbConnection connection = new OleDbConnection(connStr))
{
OleDbCommand command = new OleDbCommand ("Select Name,Address,Age FROM [Sheet1$]", connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
string sqlConnectionString = "SERVER=<servername>;UID=schafc;Trusted_Connection=Yes;DATABASE=<dbname>;";
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "<tableName>";
bulkCopy.WriteToServer(dr);
}
}
}
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}