Charora's website  
Home arrow Technical Articles
Saturday, 04 September 2010
 
 
Technical Articles
Export a DataSet to Microsoft Excel PDF Print E-mail
Written by Administrator   
Friday, 08 September 2006

This function takes in a DataSet and file name and writes the DataSet to an Excel worksheet.

This function creates an XML file and save as an XLS file. So it can be used as either file format. No more leading zero truncation on numbers that look like strings.

Example, if you made a tab delimited file and put a field such as "00045" (a field that looks like a number but should be regarded as a string), Microsoft Excel would truncate the leading zeros. This problem is solved with this method.

Here is the source code

  public void Export_To_Excel(System.Data.DataSet Source, string FileName)
  {
   System.IO.StreamWriter ExcelDoc;
   ExcelDoc = new System.IO.StreamWriter(FileName);
   const string startExcelXML = "<xml version>\r\n<Workbook " +
       "xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n" +
       " xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n " +
       "xmlns:x=\"urn:schemas-    microsoft-com:office:" +
       "excel\"\r\n xmlns:ss=\"urn:schemas-microsoft-com:" +
       "office:spreadsheet\">\r\n <Styles>\r\n " +
       "<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n " +
       "<Alignment ss:Vertical=\"Bottom\"/>\r\n <Borders/>" +
       "\r\n <Font/>\r\n <Interior/>\r\n <NumberFormat/>" +
       "\r\n <Protection/>\r\n </Style>\r\n " +
       "<Style ss:ID=\"BoldColumn\">\r\n <Font " +
       "x:Family=\"Swiss\" ss:Bold=\"1\"/>\r\n </Style>\r\n " +
       "<Style     ss:ID=\"StringLiteral\">\r\n <NumberFormat" +
       " ss:Format=\"@\"/>\r\n </Style>\r\n <Style " +
       "ss:ID=\"Decimal\">\r\n <NumberFormat " +
       "ss:Format=\"0.0000\"/>\r\n </Style>\r\n " +
       "<Style ss:ID=\"Integer\">\r\n <NumberFormat " +
       "ss:Format=\"0\"/>\r\n </Style>\r\n <Style " +
       "ss:ID=\"DateLiteral\">\r\n <NumberFormat " +
       "ss:Format=\"mm/dd/yyyy;@\"/>\r\n </Style>\r\n " +
       "</Styles>\r\n ";
   const string endExcelXML = "</Workbook>";

   int RowCount = 0;
   int SheetCount = 1;
   ExcelDoc.Write(startExcelXML);
   ExcelDoc.Write("<Worksheet ss:Name=\"Sheet" + SheetCount + "\">");
   ExcelDoc.Write("<Table>");
   ExcelDoc.Write("<Row>");
   for(int x = 0; x < Source.Tables[0].Columns.Count; x++)
   {
    ExcelDoc.Write("<Cell ss:StyleID=\"BoldColumn\"><Data ss:Type=\"String\">");
    ExcelDoc.Write(Source.Tables[0].Columns[x].ColumnName);
    ExcelDoc.Write("</Data></Cell>");
   }
   ExcelDoc.Write("</Row>");
   foreach(DataRow x in Source.Tables[0].Rows)
   {
    RowCount++;
    //if the number of rows is > 64000 create a new page to continue output
    if(RowCount==64000)
    {
     RowCount = 0;
     SheetCount++;
     ExcelDoc.Write("</Table>");
     ExcelDoc.Write(" </Worksheet>");
     ExcelDoc.Write("<Worksheet ss:Name=\"Sheet" + SheetCount + "\">");
     ExcelDoc.Write("<Table>");
    }
    ExcelDoc.Write("<Row>"); //ID=" + RowCount + "
    for(int y = 0; y < Source.Tables[0].Columns.Count; y++)
    {
     System.Type rowType;
     rowType = x[y].GetType();
     switch(rowType.ToString())
     {
      case "System.String":
       string XMLstring = x[y].ToString();
       XMLstring = XMLstring.Trim();
       XMLstring = XMLstring.Replace("&","&");
       XMLstring = XMLstring.Replace(">",">");
       XMLstring = XMLstring.Replace("<","<");
       ExcelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
        "<Data ss:Type=\"String\">");
       ExcelDoc.Write(XMLstring);
       ExcelDoc.Write("</Data></Cell>");
       break;
      case "System.DateTime":
       //Excel has a specific Date Format of YYYY-MM-DD followed by 
       //the letter 'T' then hh:mm:sss.lll Example 2005-01-31T24:01:21.000
       //The Following Code puts the date stored in XMLDate
       //to the format above
       DateTime XMLDate = (DateTime)x[y];
       string XMLDatetoString = ""; //Excel Converted Date
       XMLDatetoString = XMLDate.Year.ToString() +
        "-" +
        (XMLDate.Month < 10 ? "0" +
        XMLDate.Month.ToString() : XMLDate.Month.ToString()) +
        "-" +
        (XMLDate.Day < 10 ? "0" +
        XMLDate.Day.ToString() : XMLDate.Day.ToString()) +
        "T" +
        (XMLDate.Hour < 10 ? "0" +
        XMLDate.Hour.ToString() : XMLDate.Hour.ToString()) +
        ":" +
        (XMLDate.Minute < 10 ? "0" +
        XMLDate.Minute.ToString() : XMLDate.Minute.ToString()) +
        ":" +
        (XMLDate.Second < 10 ? "0" +
        XMLDate.Second.ToString() : XMLDate.Second.ToString()) +
        ".000";
       ExcelDoc.Write("<Cell ss:StyleID=\"DateLiteral\">" +
        "<Data ss:Type=\"DateTime\">");
       ExcelDoc.Write(XMLDatetoString);
       ExcelDoc.Write("</Data></Cell>");
       break;
      case "System.Boolean":
       ExcelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
        "<Data ss:Type=\"String\">");
       ExcelDoc.Write(x[y].ToString());
       ExcelDoc.Write("</Data></Cell>");
       break;
      case "System.Int16":
      case "System.Int32":
      case "System.Int64":
      case "System.Byte":
       ExcelDoc.Write("<Cell ss:StyleID=\"Integer\">" +
        "<Data ss:Type=\"Number\">");
       ExcelDoc.Write(x[y].ToString());
       ExcelDoc.Write("</Data></Cell>");
       break;
      case "System.Decimal":
      case "System.Double":
       ExcelDoc.Write("<Cell ss:StyleID=\"Decimal\">" +
        "<Data ss:Type=\"Number\">");
       ExcelDoc.Write(x[y].ToString());
       ExcelDoc.Write("</Data></Cell>");
       break;
      case "System.DBNull":
       ExcelDoc.Write("<Cell ss:StyleID=\"StringLiteral\">" +
        "<Data ss:Type=\"String\">");
       ExcelDoc.Write("");
       ExcelDoc.Write("</Data></Cell>");
       break;
      default:
       throw(new Exception(rowType.ToString() + " not handled."));
     }
    }
    ExcelDoc.Write("</Row>");
   }
   ExcelDoc.Write("</Table>");
   ExcelDoc.Write(" </Worksheet>");
   ExcelDoc.Write(endExcelXML);
   ExcelDoc.Close();
  }


Write Comment
Last Updated ( Tuesday, 06 November 2007 )
 
Export SqlDataReader to Excel using C# PDF Print E-mail
Written by Hari Kishan Charora   
Wednesday, 30 August 2006
Use this function to export SqlDataReader to excel.

public void ExportToExcel(SqlDataReader rsExport, System.Web.HttpResponse rsWrite)
{
System.Web.UI.HtmlControls.HtmlTable mainTable = new System.Web.UI.HtmlControls.HtmlTable();
mainTable.Border = 1;
System.Web.UI.HtmlControls.HtmlTableRow HeadeRow = new System.Web.UI.HtmlControls.HtmlTableRow();
for (int i=0;i {
System.Web.UI.HtmlControls.HtmlTableCell hCell=new System.Web.UI.HtmlControls.HtmlTableCell();
hCell.BgColor = System.Drawing.Color.Lime.Name;
hCell.Style.Add("FONT-WEIGHT", "bold");
hCell.InnerHtml=rsExport.GetName(i);
HeadeRow.Cells.Add(hCell);
}
mainTable.Rows.Add(HeadeRow);
while (rsExport.Read())
{
System.Web.UI.HtmlControls.HtmlTableRow hRow=new System.Web.UI.HtmlControls.HtmlTableRow();
for (int i=0;i {
System.Web.UI.HtmlControls.HtmlTableCell hCell=new System.Web.UI.HtmlControls.HtmlTableCell();
if (rsExport.IsDBNull(i))
{
hCell.InnerHtml="";
}
else
{
switch (rsExport.GetFieldType(i).Name)
{
case "String":
{
hCell.InnerHtml=rsExport.GetString(i);
break;
}
case "Double":
{
hCell.InnerHtml=rsExport.GetDouble(i).ToString();
break;
}
case "Int32":
{
hCell.InnerHtml=rsExport.GetInt32(i).ToString();
break;
}
case "DateTime":
{
hCell.InnerHtml=rsExport.GetDateTime(i).ToString();
break;
}
}
}
hRow.Cells.Add(hCell);
}
mainTable.Rows.Add(hRow);
}
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
mainTable.RenderControl(htmlWrite);
rsWrite.Buffer= false;
rsWrite.AddHeader("Content-Disposition", "attachment; filename=\"USB_Monitor.xls\";");
rsWrite.ContentEncoding = System.Text.Encoding.UTF8;
rsWrite.Charset = "";
rsWrite.ContentType = "application/vnd.ms-excel";
rsWrite.Write(stringWrite);
rsWrite.Flush();
rsWrite.End();
}
}
}


Write Comment
Last Updated ( Tuesday, 06 November 2007 )
 
Google





Lost Password?
No account yet? Register
Archive
Newsflash
Vision is the art of seeing things invisible.
-- Jonathan Swift

To achieve great things, we must live as though we were never going to die.
-- Vauvenarges

The moment you stop learning, you stop leading.
-- Rick Warren

Most people would rather die than think, many do.
-- Eleanor Roosevelt

To a man with empty stomach, food is God.
-- M. K. Gandhi

We are only rich through what we give.
-- Anne-Sophie Swetchine

If you haven't any charity in your heart, you have the worst kind of heart trouble.
-- Bob Home

In a war of ideas, it is people who get killed.
-- Anonymous

The cobra will bite you whether you call it cobra or Mr. Cobra.
-- an Indian Proverb

If we had no winter, the spring would not be so pleasant.
-- Anne Bradstreet

It takes a lot of things to prove that you are smart, but only one to prove you are not.
-- Don Harold

Whenever you have truth, it must be given with love, or the message and the messenger both will be rejected.
-- Mahatma Gandhi

Forgiveness is a scent that the rose leaves on the heel that crushes it.
-- Mark Twain

When people think you amount to something, distrust yourself.
-- Epicectus, Stoic Philosophy

Fear not death; for the sooner we die, the longer shall we be immortal.
-- Benjamin Franklin

The world is round and the place which may seem like the end may also be only the beginning.
-- Anonymous

The minute a man is convinced he is interesting, he isn't.
-- Stephen Leacock

 
Related Items
Sections
 
Top! Top!