0
votes

Hi I am developing a rich client UI on the web with jQuery and Microsoft ASP.net 2.0, C# as server side, I basically have 2 issues, listed here under

  1. I am using HTMLTextWriter and StringWriter class libraries for that. What I have searched on the internet and learned from various tutorials and or tips thats the most affordable way to generate the excel sheets on the fly we just need to output the fabricated html in the response and set the required headers to tell the browser what kind of data is being transferred, and at that part everything is functioning fine like it should but While converting the html to the excel spread sheet it appends download page's html markup to the excel markup as well.
  2. When I call Response.Close() after outputting the data, I get connection abort error.

Here's the code snippet

public StringWriter getHTMLStream(){

            output = new StringWriter();
            htmlWriter = new HtmlTextWriter(output);
            string html= @" 
      table {mso-displayed-decimal-separator:'\.'; mso-displayed-thousand-separator:'\,';}.xlGeneral {padding-top:1px; padding-right:1px; padding-left:1px; mso-ignore:padding; color:windowtext; font-size:10.0pt; font-weight:400; font-style:normal; text-decoration:none; font-family:Arial; mso-generic-font-family:auto; mso-font-charset:0; mso-number-format:General; text-align:general; vertical-align:bottom; mso-background-source:auto; mso-pattern:auto; white-space:nowrap;}     ";
            html+=""+this.headerName+"-"+this.vehicleName+"";
            totalCols = (this.reportOrientation == "Horiz")?data.Columns.Count:2;
            if (this.reportOrientation == "Horiz")
            {
                html+="";
                // Add Header Columns
                foreach (DataColumn colName in this.data.Columns)
                {
                    html+=""+colName.ColumnName.Trim()+"";
                }
                html+="";

                // Now Add Data
                foreach (DataRow dr in this.data.Rows)
                {
                    html+="";
                    foreach (string colData in dr.ItemArray)
                    {
                        html+=""+colData+"";
                    }
                    html+="";
                }
            }
            else
            {
                // Get the Columns
                colsArr = new string[this.data.Columns.Count];
                int colCounter = 0;
                foreach (DataColumn colName in this.data.Columns)
                {
                    colsArr[colCounter] = colName.ColumnName;
                    colCounter++;
                }
                //tableHeads = arrayToString(colsArr);
                // Get the row data in string array
                rowArr = new string[this.data.Columns.Count];

                foreach (DataRow dr in this.data.Rows)
                {
                    colCounter = 0;
                    foreach (string col in dr.ItemArray)
                    {
                        rowArr[colCounter] = col;
                        colCounter++;
                    }
                }
                //tableHeads = arrayToString(colsArr);
                // Add PDF Table Cells
                for (int i = 0; i "+colsArr[i].Trim()+""+rowArr[i].Trim()+"";
                }

            }
            html+= "";
            htmlWriter.Write(html);
            return output;
        }

        private string arrayToString(string[] array){
            string result = string.Join(",", array);
            result = result.Substring(0, result.Length - 1);
            return result;
        }
    }

And that's how I am accessing it

Response.Clear();
            createHTML speedXLS = new createHTML("Vehicle Speed Report", "Horiz", vehicleName, speedDT);
            Response.ContentType = "application/vnd.xls";
            Response.AddHeader("content-disposition", "attachment;filename=VSpeedReport-" + vehicleName + ".xls");
            Response.Write(speedXLS.getHTMLStream().ToString());
            //Response.Close();

And here is whats being appended to my excel markup the download page's markup beside the wanted xls markup. How can I tell the server not to append the page's markup in the response body? **

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>

    </title></head>
    <body>
        <form name="form1" method="post" action="downloadData.aspx?reportType=speed&amp;value=1&amp;valUnit=Miles&amp;reqType=XLS&amp;selVehicle=GTA02&amp;Email=gps%40gtalimo.com&amp;startDate=2012-4-27+23%3a21%3a00&amp;endDate=2012-4-28+01%3a21%3a00&amp;vehicleName=GTA+07" id="form1">
    <div>
    <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE2MTY2ODcyMjlkZKkkaxju0wAdoc1rGUJiLkzjS9eU" />
    </div>

        <div>

        </div>
        </form>
    </body>
    </html>

** Comments or suggestion please! Thanks!

2

2 Answers

1
votes

1. Instead of

       **strong text** Response.Clear();
createHTML speedXLS = new createHTML("Vehicle Speed Report", "Horiz", vehicleName, speedDT);
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=VSpeedReport-" + vehicleName + ".xls");
Response.Write(speedXLS.getHTMLStream().ToString());

Use

 **Response.Buffer = true;**

   createHTML speedXLS = new createHTML("Vehicle Speed Report", "Horiz", vehicleName, speedDT);
        Response.ContentType = "application/vnd.xls";
        Response.AddHeader("content-disposition", "attachment;filename=VSpeedReport-" + vehicleName + ".xls");
        Response.Write(speedXLS.getHTMLStream().ToString());
  1. When you are using streaming class , use "using" statement.
1
votes

Generating html table and tricking the browser to show it in excel is not the best way to export data to excel. It's a hack not solution, and IMO it's just matter of time when will this stop working, maybe in next excel version or becouse some virus / antimalware /whatever detected that you are sending content with wrong headers, and excel 2007/2010 already warns user about that.

**UPDATE : ** In my opinion best way is to use 3rd party excel libraries that can generate true excel file and then browser will open excel, and content match headers. And there are really good open source libraries and I really don't see any reson why they shoudnt be used.

NPOI (xls) or / and EPPlus (xlsx)

So if you still want to do that without and 3rd party library use CSV format, look here for example of exporting DataTable to CSV :

Convert DataTable to CSV stream

Alternative would be export to XML with an excel schema. Here is the code :

public static MemoryStream DataSetToExcelXml(DataSet ADataset)
{
  MemoryStream result = new MemoryStream();
  XmlDataDocument doc = new XmlDataDocument(ADataset);
  XslCompiledTransform trans = new XslCompiledTransform();
  XmlDocument xmlDoc = new XmlDocument();
  Stream shema = Assembly.GetExecutingAssembly().GetManifestResourceStream("ResPathToExcelSheet.xsl");
  xmlDoc.Load(shema);
  trans.Load(xmlDoc);
  trans.Transform(doc, null, result);
  return result;
}

Schema

<xsl:stylesheet version="1.0"
    xmlns="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 xmlns:user="urn:my-scripts"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" >  
<xsl:template match="/">
  <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:x="urn:schemas-microsoft-com:office:excel"
    xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
    xmlns:html="http://www.w3.org/TR/REC-html40">
    <xsl:apply-templates/>
  </Workbook>
</xsl:template>
<xsl:template match="/*">
  <Worksheet>
  <xsl:attribute name="ss:Name">
  <xsl:value-of select="local-name(/*/*)"/>
  </xsl:attribute>
    <Table x:FullColumns="1" x:FullRows="1">
      <Row>
        <xsl:for-each select="*[position() = 1]/*">
          <Cell><Data ss:Type="String">
          <xsl:value-of select="local-name()"/>
          </Data></Cell>
        </xsl:for-each>
      </Row>
      <xsl:apply-templates/>
    </Table>
  </Worksheet>
</xsl:template>
<xsl:template match="/*/*">
  <Row>
    <xsl:apply-templates/>
  </Row>
</xsl:template>
<xsl:template match="/*/*/*">
  <Cell><Data ss:Type="String">
    <xsl:value-of select="."/>
  </Data></Cell>
</xsl:template>
</xsl:stylesheet>