如何使用双撇号替换excel表中的所有撇号

时间:2014-08-13 04:28:47

标签: c# sql asp.net excel oledb

我必须将excel表导出到ms sql数据库表。为此,我使用了oledb连接。它运作良好。但是包含撇号的任何单元格值(例如:单元格1值为 - divya's)都会显示错误“字符串后面的未闭合引号”。 我发现要在数据库中插入单引号或撇号数据,我们需要在数据中使用两个连续的单引号或撇号。如何才能在excel表中实现?

 protected void btnSend_Click(object sender, ImageClickEventArgs e) //upload QB
{
    SqlConnection con = obj.getcon();      
    string filename = Path.GetFileName(fileuploadExcel.FileName);
    int fileSize = fileuploadExcel.PostedFile.ContentLength;
   if ((Path.GetExtension(filename) == ".xlsx" || Path.GetExtension(filename) == ".xls") && (fileSize <= (1.049e+6)))
    {

            string excel_file = "my_excel_file";
            var path1 = Server.MapPath("~/personal/" + excel_file + "");
            var directory = new DirectoryInfo(path1);
            if (directory.Exists == false)
            {
                directory.Create();
            }

            fileuploadExcel.SaveAs(path1 + "\\" + filename);
            string filepath = path1 + "\\" + filename;
            //Create connection string to Excel work book
            string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0;Persist Security Info=False";


            OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
            //Create OleDbCommand to fetch data from Excel
            OleDbCommand cmd = new OleDbCommand("Select [Name],[Address] from  [mysheet$]", excelConnection);
            excelConnection.Open();
            OleDbDataReader dReader;
            dReader = cmd.ExecuteReader();

            string name = "";
            string address = "";

            while (dReader.Read())
            {
               name = valid(dReader, 0);
               address = valid(dReader, 1);
               insertdataintosql(name,address);
            }
            excelConnection.Close();       
    }

    else
    {
        Label5.Visible = true;
        Label5.Text = " Only Files Having .xlsx or.xls format and less than 1MB size can be uploaded**";

    }

}
  protected string valid(OleDbDataReader myreader, int stval)
{
    //if any columns are found null then they are replaced by zero
    object val = myreader[stval];
    if (object.ReferenceEquals(val, DBNull.Value))
    {
        return Convert.ToString(0);
    }
    else
    {
        return val.ToString();
    }
}
public void insertdataintosql(string name,string address,)
{   SqlConnection conn = obj.getcon();
    conn.Open();
    string query = "insert into sample_test(name,address) values('" + name + "','"+address+ "')"; 
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.ExecuteNonQuery();
    conn.Close();
  }

1 个答案:

答案 0 :(得分:0)

valid函数中:

而不是

return val.ToString();

使用:

return val.ToString().Replace("'","''");