我想将一个.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