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

时间:2011-11-08 08:22:21

标签: c# sql-server visual-studio excel

我正在尝试将.csv文件导入我的数据库。我可以将excel工作表导入到我的数据库中,但是由于.csv的文件格式与.xls不同,我需要专门为.csv创建一个导入函数。

以下是我的代码:

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,因此我无法继续导入数据的过程进入我的数据库。

以下是我的错误的屏幕截图: enter image description here

enter image description here

总之,我遇到错误,即保存csv文件的文件路径无效,尽管csv文件已成功保存。需要经验丰富的帮助。谢谢

4 个答案:

答案 0 :(得分:2)

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

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

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

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

答案 1 :(得分:0)

我认为你有这个问题,因为你使用“/”而不是“\” 尝试修改路径C:\ .....

答案 2 :(得分:0)

您需要在文件路径上使用反斜杠(\)。

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

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

编辑2:即使您使用的是connectionstring格式,您.csv也存在问题,您需要设置Excel 8.0或{{1} }作为扩展属性

以下是样本:

Excel 12.0 Xml

对于其他类型,请检查OLEDB section of my article的代码。

答案 3 :(得分:0)

为避免连接打开,您可以使用

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

如需更多帮助,您还可以See This Link