using RunXc.Web;
using RunXc.DB;


RunXc


Where the DB meets the Web

Exporting a DataTable to Excel (DataTable to CSV)

clock June 24, 2009 06:58 by author

It seems like each time I need to do this in a project (that is create an Excel file from a GridView or SQL Query) I have to look for my little snippet on how to do this in a reusable manner.  Well here you go a nice Extension Method that will return CSV from any System.Data.DataTable.

public static String ToCSV(this DataTable dt)
{
    StringBuilder sb = new StringBuilder();

    for (int x = 0; x < dt.Columns.Count; x++)
    {
        if (x != 0)
            sb.Append(",");
        sb.Append(dt.Columns[x].ColumnName);
    }
    sb.AppendLine();
    foreach (DataRow row in dt.Rows)
    {
        for (int x = 0; x < dt.Columns.Count; x++)
        {
            if (x != 0)
                sb.Append(",");
            sb.Append(row[dt.Columns[x]].ToString());
        }

        sb.AppendLine();
    }
    return sb.ToString();
}
Submit this story to DotNetKicksShout it   Bookmark and Share  


Forcing a GridView to use clean html for use with jQuery plug-ins

clock June 15, 2009 06:50 by author

One of the problems of using a GridView with a lot of the table plug-ins for jQuery or any other JavaScript table library is that the library expects your html to be well formatted with your table headers appearing within a thead.  Example below.

<table>
	<thead>
		<tr><th>Header</th></tr>
	</thead>
	<tbody>
		<tr><td>Data</td></tr>
	</tbody>
</table>

 

The problem is that a GridView does not format the table correctly.  Below is a simple Extension Method used to clean up after your GridView to make it output clean html for use with JavaScript table frameworks.

GridView Extension method for clean html output

 

public static void FixThead(this GridView grid)
{
    if (grid.Rows.Count > 0)
    {
        //This replaces <td> with <th> and adds the scope attribute
        grid.UseAccessibleHeader = true;
        grid.HeaderRow.TableSection = TableRowSection.TableHeader;
    }
}

 

There you have it is as easy as that.

Submit this story to DotNetKicksShout it   Bookmark and Share  


Blog.RunXc

View Bret Ferrier's profile on LinkedIn

Read an Article and Need Help?

Consulting/Contracting -Get a bid

OpenSouce Projects I like -jQuery, SubSonic, Mono, CC.Net

Languages- C#,javascript, VB, SQL, T-SQL, PSQL

DataBases- SqlServer,Oracle,MySql, SQLite, Sql Anywhere

Linux Flavors- OpenSuse, Ubuntu

VM Preference - VirtualBox

Least Favorite Reporting Technology-Crystal Reports

Sign in