C#VS2005导入.CSV文件到SQL数据库

我想导入一个.csv文件到我的数据库。 我可以导入一个Excel工作表到我的数据库,但是由于.csv和.xls文件格式不同,我需要为.csv创build一个导入函数。

以下是我的代码:

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>"); } 

该文件已被成功保存,但错误显示该文件的path无效,即使该文件已成功保存为.csv,因此我无法继续将数据导入到数据库的过程。

以下是我的错误截图: 在这里输入图像说明

在这里输入图像说明

总之,我有一个错误,即保存csv文件的文件path无效,虽然csv文件已成功保存。 需要一些有经验的帮助。 谢谢

如果您正在阅读CSV文件,则连接string应指定包含CSV文件的目录

 string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path.GetDirectoryName(strUploadFileName); 

然后在SELECT语句中使用文件名:

 "SELECT * FROM [" + Path.GetFileName(strUploadFileName) + "]" 

我想你有这个问题,因为你使用“/”而不是“\”尝试修改pathC:\ …..

您需要在文件path上使用反斜线( \ )。

 string strUploadFileName = @"C:\Documents and Settings\rhlim\My Documents\Visual Studio 2005\WebSites\SoD\UploadFiles\" + DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension; 

编辑1:我相信FileUpload1.SaveAs转换为/ \内部以确定正确的位置。

编辑2:它的connectionstringstring的问题,即使您使用.csv格式,您需要将Excel 8.0Excel 12.0 Xml扩展属性

这是样本:

 string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strUploadFileName + ";Extended Properties=Excel 12.0 Xml;"; 

对于其他types,请检查我的文章的OLEDB部分的代码。

为了避免连接打开,你可以使用像

 // Read the CSV file name & file path // I am usisg here Kendo UI Uploader string path = ""; string filenamee = ""; if (files != null) { foreach (var file in files) { var fileName = Path.GetFileName(file.FileName); path = Path.GetFullPath(file.FileName); filenamee = fileName; } // Read the CSV file data StreamReader sr = new StreamReader(path); string line = sr.ReadLine(); string[] value = line.Split(','); DataTable dt = new DataTable(); DataRow row; foreach (string dc in value) { dt.Columns.Add(new DataColumn(dc)); } while (!sr.EndOfStream) { value = sr.ReadLine().Split(','); if (value.Length == dt.Columns.Count) { row = dt.NewRow(); row.ItemArray = value; dt.Rows.Add(row); } } 

如需更多帮助,您还可以查看此链接