我想將一個.csv文件導入到我的數據庫中。我能夠將excel工作表導入到我的數據庫中,但是由於與.xls中的.csv文件格式不同,因此我需要爲.csv專門創建一個導入函數。打開ExcelConnection時出錯C#VS2005
下面是我的代碼:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Get the name of the Excel spreadsheet to upload.
string strFileName = Server.HtmlEncode(FileUpload1.FileName);
// Get the extension of the Excel spreadsheet.
string strExtension = Path.GetExtension(strFileName);
// Validate the file extension.
if (strExtension != ".xls" && strExtension != ".xlsx" && strExtension != ".csv" && strExtension != ".csv")
{
Response.Write("<script>alert('Failed to import DEM Conflicting Role Datasheet. Cause: Invalid Excel file.');</script>");
return;
}
// Generate the file name to save.
string strUploadFileName = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
// Save the Excel spreadsheet on server.
FileUpload1.SaveAs(strUploadFileName);
// Create Connection to Excel Workbook
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Text;";
using (OleDbConnection ExcelConnection = new OleDbConnection(connStr)){
OleDbCommand ExcelCommand = new OleDbCommand("SELECT [columns] FROM +userrolelist", ExcelConnection);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
ExcelConnection.Open();
using (DbDataReader dr = ExcelCommand.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=<IP>;Initial Catalog=<DB>;User ID=<userid>;Password=<password>";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "DEMUserRoles";
bulkCopy.WriteToServer(dr);
Response.Write("<script>alert('DEM User Data imported');</script>");
}
}
}
}
else Response.Write("<script>alert('Failed to import DEM User Roles Data. Cause: No file found.');</script>");
}
該文件已成功保存,但錯誤說,該文件的路徑是無效的,即使該文件已成功保存作爲.csv,因此我無法繼續將數據導入到我的數據庫的過程。
下面是我的錯誤的截圖:
在我遇到的錯誤將CSV文件保存的文件路徑無效的結論,雖然csv文件保存成功。需要一些有經驗的幫助。謝謝
感謝坎貝爾,它似乎爲我工作。但是,在將管道分隔文本文件轉換爲.csv文件時,我遇到了一些問題,某些列變量分爲兩部分,並跳到下一列,搞亂了行,所以我必須排除故障原因。你介意看看我用於將管道分隔文件轉換爲.csv文件的代碼嗎?謝謝 – gymcode
http://stackoverflow.com/questions/8061307/rows-messed-up-when-converting-pipe-delimited-text-files-to-csv-excel-file-c-sh 這是錯誤我目前面對,我不知道爲什麼轉換有錯誤。 – gymcode