如何防止出口“&”来自GridView?

时间:2012-02-29 07:48:09

标签: c# asp.net visual-studio

每当我尝试使用导出点击从数据库导出数据记录时,我都会收到有趣的数据记录,例如&。但是,有时候它的效果非常好。任何人都可以告诉我为什么会这样,我该如何解决这个问题?

示例代码:

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 class:

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

2 个答案:

答案 0 :(得分:5)

在附加到StringBuilder.Append

中之前,将所有字符串传递给下面的函数
HttpUtility.HtmlDecode ()

例如:

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

答案 1 :(得分:2)

您应该使用HttpUtility.HtmlDecode解码控件的Text属性,因为它们的编码为:

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

如果在HTTP中传递空格和标点符号等字符   流,他们可能会在接收端被误解。 HTML   编码将HTML中不允许的字符转换为   字符实体等价物; HTML解码反转了编码。对于   例如,当嵌入在文本块中时,字符&lt;和&gt;是   编码为&lt;&gt;进行HTTP传输。

您的&amp;已解码回&个符号。

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