Runtime Debugger - kannan M ambadi's blog

March 2008 - Posts

Exporting Dataset as CSV

Hi Everyone,

Below given an easy way to export data from a dataset as CSV(comma seperated values) . At first, it converts the datatable to html table format and then writes data as output stream. We need to set the Content-Type of Response object as Excel format and add the filename to be streamed on the client browser in a dialog box

Check this snippet

private void ExportToCsvFromDataSet(DataSet dsExport) {

bool IsOutputStreamed = false;

try {

StringBuilder dataToExport = new StringBuilder();

foreach (DataTable dtExport in dsExport.Tables) {

string headerToExport= string.Empty;

foreach (DataColumn dCol in dtExport.Columns)

headerToExport = (char)34 + dCol.ColumnName + (char)34 + (char)44;

headerToExport.Remove(headerToExport.Length - 1, 1);

headerToExport = headerToExport + Environment.NewLine + Environment.NewLine;

dataToExport.Append(headerToExport);

string bodyToExport = string.Empty;

foreach (DataRow dRow in dtExport.Rows) {

foreach (object obj in dRow.ItemArray)

bodyToExport = bodyToExport + obj.ToString() + (char)44;

bodyToExport.Remove(bodyToExport.Length - 1, 1);

bodyToExport = bodyToExport + Environment.NewLine;

}

dataToExport.Append(bodyToExport);

dataToExport.Append(Environment.NewLine);

dataToExport.Append(Environment.NewLine);

if (string.IsNullOrEmpty(dataToExport.ToString())) {

Response.Clear();

Response.ContentType = "Text/vnd.ms-excel";

Response.AddHeader("Content-Disposition", "attachment;filename=report.csv");

Response.Write(dataToExport.ToString());

IsOutputStreamed = true;

}

}

}

catch { }

finally {

if (IsOutputStreamed)

Response.End();

}

}

Download the source code

Simple way to check your code performance

Hi guys,Of course, we all know foreach loop takes more time than for loop and there are lot of similar scenarios in .Net. Even if it takes lot of time, we'll be forced to use foreach loop at some cases. So it'll be better, if we come to know the time taken for executing a piece of code at the runtime. Here is a simple way to find out the time taken for each process.It just writes the start time and finish time taken for the process in the debug window. Debug.Indent() method simply changes the indentation of the Output by one level and Debug.WriteLine() method writes a string in the debug window.

Here is the snippet

//Increases the current IndentLevel

System.Diagnostics.Debug.Indent();

//Writes the starttime

System.Diagnostics.Debug.WriteLine("DEBUG START TIME -> : " + DateTime.Now.ToString("HH:mm s:fff"));

//Execute the code

ConfigureControls();

//Writes the finish time

System.Diagnostics.Debug.WriteLine("DEBUG FINISH TIME -> : " + DateTime.Now.ToString("HH:mm s:fff"));

//Reduces the current IndentLevel

System.Diagnostics.Debug.Unindent();

Hurray!!!!!!

 Atlast im in the world of micrsoft blogs..special thanks to joe stagner for providing blog space.  

kannan M ambadi

More Posts