Click here to Skip to main content
Click here to Skip to main content

Exporting in MS Excel by MS Excel way

, 8 Jul 2006
Rate this:
Please Sign up or sign in to vote.
Exporting in MS Excel by MS Excel way
Title:       Export in excel by excel way
Author:      Dimitar Nikolaev Madjarov 
Email:       madjarov_d_n@yahoo.com
Environment: Windows 2000, XP, 2003, MS Visual Studio 2003,
             ASP.NET, IIS v5.0, 5.1, 6.0
Keywords:    Export in Excel as reporting action
Level:       "Intermediate"
Description: An article which describe how to make export in excel in ASP.NET
Section      ASP.NET
SubSection   Reporting

Final report/export in excel

Final report/export in excel

Introduction

Everyone developer know for basic problem when he or she has to made an export from an ASP.NET application and when the export is done  in case that we have an data field from data type string with value as for an example 08-12 when we open in MS Excel  the exported file/data are automatically convert from "MS Excel" in next data "08.December" which is very boredom and not very good  option according end user who use our application.  
This may to become a very big problem for us as developers. If you try to find solution of this case in Internet as you going to looking for information via web based sources as "http://www.google.com/" or "http://www.codeproject.com/" you will find many examples how to make an export in Excel from existing data set, data table or directly from an ASP.Grid but most of the given examples do not solve the problem which I describe above.  
Therefore I will try to provide an export in MS Excel solution which solve all the transformation problems between data types  in MS Excel and ASP.NET.  
The main idea of this article is to use the MS Excel to generate a report as we use the visual part of the MS Excel  and after that to save ready report as an Web page.  
Next step is just to copy generated structure and adapt it for our needs. 

Using the code

As I try to explain what is the main idea I will put here the code of three main methods.  The first one is an method which export in MS Excel the whole data table which it is receive.  
Second one is an method which export only the chosen column's numbers(position) and replace the  column's caption with define new names or captions.   And the last one is just an help method which support of second one to remove all unnecessary columns from an data table. 
You may see the code below.

//
// this method return is an column from dataset is for deleting or not
//
private bool isForDeleting(ArrayList columsForDeleting, string targetColum)
{
   bool actionResult = true;

   if (columsForDeleting.Count > 0   )
   {  
     for (int i = 0;  i <  columsForDeleting.Count; i++)
     {
	if (columsForDeleting[i].ToString() == targetColum)
	{
	     break;
	     actionResult = false;
	}
     }
    }
    else
    {
      actionResult = false;
    }
   return actionResult;
  }

// 
// this method return an string with only chosen one columns with correct column's captions 
// 
private string ConvertToExcelFewFiledsFromTable(DataTable dt, string sheetName, string[] exportFieldsName, int[] tableColums) 
{ 
   // 
   // Define an error export message 
   // 
   const string lenghtError = "The number of colum's names has to be equal of number of column's id!";      
   // 
   // In case that column's names and exported fields are equal as numbers going
   // to export, otherwise generate an export error. 
   // 
   if (exportFieldsName.Length != tableColums.Length) 
   { 
     // 
     // Return an export error.
     //
      return lenghtError; 
   } 
   else 
   { 
     DataTable dtUpdated = new DataTable();
     dtUpdated           = dt.Copy(); 
     // 
     // Going to update and remove necessary Column's captions with new one 
     // 
     for (int i=0; i < dtUpdated.Columns.Count; i++) 
     { 
       for (int j=0; j < exportFieldsName.Length; j++) 
       { 
          if (tableColums[j] == i) 
          { 
            // 
            // Going to update Column's captions with new one
            // 
            dtUpdated.Columns[i].Caption = exportFieldsName[j].ToString().ToUpper();
          } 
         } 
      } 
      
      // 
      // Going to remove not necessary columns 
      //
      string columsNoForDeleting = ""; 
      for (int i=0; i < tableColums.Length; i++)
      {
        columsNoForDeleting = columsNoForDeleting + ";" + dtUpdated.Columns[tableColums[i]].ColumnName.ToString();
      } 
     
      ArrayList columsForRemove = new ArrayList(); 
      for (int j=0; j < dtUpdated.Columns.Count; j++) 
      { 
         if (columsNoForDeleting.IndexOf(dtUpdated.Columns[j].ColumnName.ToString(),0) == -1) 
         { 
            columsForRemove.Add(dtUpdated.Columns[j].ColumnName.ToString()); 
         } 
      }
    
      if (columsForRemove.Count > 0) 
      { 
        dtUpdated.PrimaryKey = null; 
        for (int i=0; i < columsForRemove.Count; i++) 
        { 
          dtUpdated.Columns.Remove(columsForRemove[i].ToString());
        } 
      } 
     
      // 
      // Call again the export function into excel for whole data table 
      // 
      return ConvertToExcelAllFieldsFromTable(dtUpdated, sheetName); 
      } 
    }         
    

You may see the final export data result as an report on pictures above!

Conclusion

As conclusion I like to say that the way to use MS Excel as an visual designer for our report needs and after that  to "Save as" this Excel template report as a Web page and copy the structure and adapt for an ASP.NET export report  is a very powerful way to design correct reports.  
I hope that this very simple example will be useful for you guys.  

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Dimitar Madjarov
Software Developer (Senior) http://www.uplandsoftware.com/
Canada Canada
Canada, Quebec, Laval,
Currnet position: Senior ASP.NET Developer
Company: Uplandsoftware Inc
Certificates: MCITP, MCP, MCTS

Comments and Discussions

 
GeneralQuestion about structure of Excel Pinmemberimagic11-Aug-09 18:07 
GeneralRe: Question about structure of Excel PinmemberDimitar Madjarov12-Aug-09 4:42 
GeneralNeed HELP in vb.NET PinmemberPhellipe Schelotag24-Jul-08 10:33 
Generalvb.net PinmemberFormy25-Jul-07 18:44 
GeneralSaveAs defaults to html not .xls PinmemberElizabeth Gee6-Jun-07 9:39 
GeneralRe: SaveAs defaults to html not .xls PinmemberDimitar Madjarov6-Jun-07 22:30 
GeneralRe: SaveAs defaults to html not .xls PinmemberJamesHoward97222-Jan-12 23:00 
QuestionText Number Conversion Pinmemberlab@gaia.is.it20-Jul-06 3:01 
AnswerRe: Text Number Conversion PinmemberDimitar Madjarov20-Jul-06 4:08 
Generalunable to read excel sheet using C# Pinmembersudha_josyula9-Jul-06 7:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 8 Jul 2006
Article Copyright 2006 by Dimitar Madjarov
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid