0% found this document useful (0 votes)
77 views

Convert Dataset To Excel Format

This document describes a function that converts a dataset into an Excel file format. The function takes in a dataset, loops through the tables and columns to build an HTML table, encodes it to UTF-8, and returns a stream that can be attached to an email as an Excel attachment. The attachment stream is then used to attach the converted dataset in Excel format to an email.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

Convert Dataset To Excel Format

This document describes a function that converts a dataset into an Excel file format. The function takes in a dataset, loops through the tables and columns to build an HTML table, encodes it to UTF-8, and returns a stream that can be attached to an email as an Excel attachment. The attachment stream is then used to attach the converted dataset in Excel format to an email.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

The following function can be used to convert a dataset into excel content.

System.Net.Mail.Attachment attachment = new


System.Net.Mail.Attachment(ConvertDatsetToExcel(myDataset), "myExcel.xls");

You can attach the stream to the mail which is in excel format.

public Stream ConvertDatsetToExcel(DataSet dataset)


{
Stream attachment = null;
string excelContent = "";

excelContent += "<table border='0' cellspacing='2'


cellpadding='2'>";

if (dataset.Tables[0].Rows.Count > 0)
{
excelContent += "<tr>";
for (int index = 0; index <
dataset.Tables[0].Columns.Count; index++)
{
excelContent += "<td><b>";
excelContent +=
dataset.Tables[0].Columns[index].ColumnName;
excelContent += "</b></td>";
}
excelContent += "</tr>";

for (int rowNo = 0; rowNo < dataset.Tables[0].Rows.Count;


rowNo++)
{
excelContent += "<tr>";
for (int colNo = 0; colNo <
dataset.Tables[0].Columns.Count; colNo++)
{
excelContent += "<td>";
excelContent += dataset.Tables[0].Rows[rowNo]
[colNo].ToString();
excelContent += "</td>";
}
excelContent += "</tr>";
}
}
else
{
excelContent += "<tr>";
for (int index = 0; index <
dataset.Tables[0].Columns.Count; index++)
{
excelContent += "<td><b>";
excelContent +=
dataset.Tables[0].Columns[index].ColumnName;
excelContent += "</b></td>";
}
excelContent += "</tr>";
}
2

excelContent += "</table>";

attachment = new
MemoryStream(System.Text.Encoding.UTF8.GetBytes(excelContent));

return attachment;
}

You might also like