2012-02-29 2 views
0

수출 클릭을 사용하여 데이터베이스에서 데이터 레코드 내보내기를 시도 할 때마다 &과 같은 재미있는 데이터 레코드가 표시됩니다. 그러나 때로는 완벽하게 잘 작동합니다. 아무도 왜 그렇게 말해 줄 수 있고 어떻게 문제를 해결할 수 있습니까?GridView에서 "&"을 내보내는 것을 방지하려면?

샘플 코드 :

protected void CsvImg_Click(object sender, ImageClickEventArgs e) 
{ 
    try 
    { 
     DataTable dataTable = (DataTable)Session["dataTable"]; 
     Response.ClearContent(); 
     Response.Buffer = true; 
     Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "sqlresult.csv")); 
     Response.ContentType = "application/text"; 
     exportView.AllowPaging = false; 
     exportView.DataSource = dataTable; 
     exportView.DataBind(); 
     System.Text.StringBuilder strbldr = new System.Text.StringBuilder(); 
     for (int i = 0; i < exportView.HeaderRow.Cells.Count; i++) 
     { 
      //separting header columns text with comma operator 
      strbldr.Append(exportView.HeaderRow.Cells[i].Text + ','); 
     } 
     //appending new line for gridview header row 
     strbldr.Append("\n"); 
     for (int j = 0; j < exportView.Rows.Count; j++) 
     { 
      for (int i = 0; i < exportView.HeaderRow.Cells.Count; i++) 
      { 
       //separating gridview columns with comma 
       strbldr.Append(exportView.Rows[j].Cells[i].Text + ','); 
      } 
      //appending new line for gridview rows 
      strbldr.Append("\n"); 
     } 
     Response.Write(strbldr.ToString()); 
     Response.End(); 
    } 
    catch (Exception) 
    { 
    } 
} 

가져 오기 코드 :

using (CsvFileReader reader = new CsvFileReader(CourseDataFileUpload.PostedFile.InputStream)) 
{ 
#region create dt 
DataTable List = new DataTable(); 
List.Columns.Add("CourseID"); 
List.Columns.Add("CourseName"); 
List.Columns.Add("CourseCoordinator"); 
#endregion 

CsvRow row = new CsvRow(); 
bool dataformat = false; 
string checkname = "CourseID,CourseName,CourseCoordinator"; 

while (reader.ReadRowSpecial(row)) 
    { 
for (int i = 0; i < row.Count; i++) 
{ 
string total = HttpUtility.HtmlEncode(row[i].ToString()); 
if (total == checkname) 
{ 
dataformat = true; 
} 

if (dataformat == true) 
{ 
string[] splitname = total.Split(','); 
#region split string 
string first = splitname[0].ToString(); 
string second = splitname[1].ToString(); 
string third = splitname[2].ToString(); 
#endregion 
List.Rows.Add(first, second, third); 
listOfCourseInformation = List; 
} 
} 
if (dataformat == false) 
{ 
break; 
} 
} 
if (List.Rows.Count > 0) 
{ 
List.Rows.RemoveAt(0); 
} 
} 

CSV 클래스 :

public bool ReadRowSpecial(CsvRow row) 
     { 
      row.LineText = ReadLine(); 
      if (String.IsNullOrEmpty(row.LineText)) 
       return false; 

      int pos = 0; 
      int rows = 0; 

      while (pos < row.LineText.Length) 
      { 
       string value; 

       // Special handling for quoted field 
       if (row.LineText[pos] == '"') 
       { 
        // Skip initial quote 
        //pos++; 

        // Parse quoted value 
        int start = pos; 
        while (pos < row.LineText.Length) 
        { 
         // Test for quote character 
         if (row.LineText[pos] == '"') 
         { 
          // Found one 
          pos++; 

          // If two quotes together, keep one 
          // Otherwise, indicates end of value 
          if (pos >= row.LineText.Length || row.LineText[pos] != '"') 
          { 
           pos--; 
           break; 
          } 
         } 
         pos++; 
        } 
        value = row.LineText.Substring(start, pos - start); 
        value = value.Replace("\"\"", "\""); 
       } 
       else 
       { 
        //Parse unquoted value 
        int start = pos; 
        while (pos < row.LineText.Length && row.LineText[pos] != '"') 
         pos++; 
        value = row.LineText.Substring(start, pos - start); 
       } 

       // Add field to list 
       if (rows < row.Count) 
        row[rows] = value; 
       else 
        row.Add(value); 
       rows++; 

       // Eat up to and including next comma 
       while (pos < row.LineText.Length && row.LineText[pos] != '"') 
        pos++; 
       if (pos < row.LineText.Length) 
        pos++; 
      } 
      //// Delete any unused items 
      //while (row.Count > rows) 
      // row.RemoveAt(rows); 

      // Return true if any columns read 
      return (row.Count > 0); 
     } 

답변

5

패스 아래 함수에 모든 문자열 StringBuilder.Append

내부에 추가하기 전에
HttpUtility.HtmlDecode() 

예 :

strbldr.Append(HttpUtility.HtmlDecode(exportView.Rows[j].Cells[i].Text + ',')); 
+0

이봐 난 당신이 다른 질문 요청할 수 있습니다? 데이터 가져 오기는 어떻습니까? 나는 같은 문제를 가지고있다. 코드를 업데이트 해 드리겠습니다. –

+0

역순을 사용하십시오. HttpUtility.HtmlEncode – PraveenVenu

+0

어디에 넣어야합니까? 어쨌든 그것을 인코딩하려고 할 때 "&"를 "And"로 바꾸는 것과 비슷하지만 여전히 가져 오지 못합니다. –

2

당신은 자신의 인코딩 때문에 컨트롤 'Text 속성을 디코딩하는 HttpUtility.HtmlDecode을 사용해야합니다

strbldr.Append(HttpUtility.HtmlDecode(exportView.Rows[j].Cells[i].Text)).Append(","); 

같은 공백 및 문장 부호와 같은 문자는 HTTP 전달하는 경우 스트림의 경우 수신 측에서 잘못 해석 될 수 있습니다. HTML 인코딩은 HTML에서 허용되지 않는 문자를 문자 엔티티와 동일하게 변환합니다. HTML 디코딩은 인코딩을 되돌립니다. 예를 들어, 텍스트 블록에 포함 된 경우 < 및> 문자는 &lt;&gt;으로 인코딩 된 이고 HTTP 전송 용입니다.

&amp;& 기호로 다시 디코딩됩니다.

http://htmlhelp.com/reference/html40/entities/special.html

관련 문제