1

i am getting funny data records like & whenever i tried export data records from database using the export click. However, sometimes it works perfectly fine. Can anyone tell me why is it so and how can i solve the problem?

Sample code:

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

Import code:

    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 Answers 2

6

Pass all the strings to the below function before appending inside the StringBuilder.Append

HttpUtility.HtmlDecode ()

ex:

strbldr.Append(HttpUtility.HtmlDecode(exportView.Rows[j].Cells[i].Text + ','));
6
  • hey can i ask you another question? how about importing data? i have the same problem. let me just update the code for you.
    – user1037134
    Feb 29, 2012 at 8:15
  • any idea where should i put them? anyway its like turning "&" to "And" when i try to encode it but still fails to import.
    – user1037134
    Feb 29, 2012 at 8:25
  • Can you post the lines of code? Encoding will convert & to amp; Feb 29, 2012 at 8:27
  • I am pretty sure it the Encoding and Decoding is giving me problems, is it ok if i just "Decode" from export and do nothing at import?
    – user1037134
    Feb 29, 2012 at 8:39
  • hmmm i think i just need to check on my codes abit more, thanks alot!
    – user1037134
    Feb 29, 2012 at 8:43
2

You should use HttpUtility.HtmlDecode to decode the controls' Text property since their encoded:

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

If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents; HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are encoded as &lt; and &gt; for HTTP transmission.

Your &amp; is decoded back to an & sign.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.