12
 13# endregion // Includes
 14
 15namespace MyLib.ExportData
 16{
 17    # region Summary
 18
 19    /**//// <summary>
 20    /// Exports datatable to CSV or Excel format.
 21    /// This uses DataSet's XML features and XSLT for exporting.
 22    /// 
 23    /// C#.Net Example to be used in WebForms
 24    /// ------------------------------------- 
 25    /// using MyLib.ExportData;
 26    /// 
 27    /// private void btnExport_Click(object sender, System.EventArgs e)
 28    /// {
 29    ///   try
 30    ///   {
 31    ///     // Declarations
 32    ///     DataSet dsUsers =  ((DataSet) Session["dsUsers"]).Copy( );
 33    ///     MyLib.ExportData.Export oExport = new MyLib.ExportData.Export("Web"); 
 34    ///     string FileName = "UserList.csv";
 35    ///     int[] ColList = {2, 3, 4, 5, 6};
 36    ///     oExport.ExportDetails(dsUsers.Tables[0], ColList, Export.ExportFormat.CSV, FileName);
 37    ///   }
 38    ///   catch(Exception Ex)
 39    ///   {
 40    ///     lblError.Text = Ex.Message;
 41    ///   }
 42    /// }    
 43    /// </summary>
 44
 45    # endregion // Summary
 46
 47    public class ExportData
 48    {        
 49        public enum ExportFormat : int {CSV = 1, Excel = 2}; // Export format enumeration            
 50        System.Web.HttpResponse response;
 51        private string appType;    
 52            
 53        public ExportData()
 54        {
 55            appType = "Web";
 56            response = System.Web.HttpContext.Current.Response;
 57        }
 58
 59            public ExportData(string ApplicationType)
 60        {
 61            appType = ApplicationType;
 62            if(appType != "Web" && appType != "Win") throw new Exception("Provide valid application format (Web/Win)");
 63            if (appType == "Web") response = System.Web.HttpContext.Current.Response;
 64        }
 65        
 66        ExportDetails OverLoad : Type#1#region ExportDetails OverLoad : Type#1
 67        
 68        // Function  : ExportDetails 
 69        // Arguments : DetailsTable, FormatType, FileName
 70        // Purpose     : To get all the column headers in the datatable and 
 71        //               exorts in CSV / Excel format with all columns
 72
 73        public void ExportDetails(DataTable DetailsTable, ExportFormat FormatType, string FileName)
 74        {
 75            try
 76            {                
 77                if(DetailsTable.Rows.Count == 0) 
 78                    throw new Exception("There are no details to export.");                
 79                
 80                // Create Dataset
 81                DataSet dsExport = new DataSet("Export");
 82                DataTable dtExport = DetailsTable.Copy();
 83                dtExport.TableName = "Values"; 
 84                dsExport.Tables.Add(dtExport);    
 85                
 86                // Getting Field Names
 87                string[] sHeaders = new string[dtExport.Columns.Count];
 88                string[] sFileds = new string[dtExport.Columns.Count];
 89                
 90                for (int i=0; i < dtExport.Columns.Count; i++)
 91                {
 92                    sHeaders[i] = dtExport.Columns[i].ColumnName;
 93                    sFileds[i] = dtExport.Columns[i].ColumnName;                    
 94                }
 95
 96                if(appType == "Web")
 97                    Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);
 98                else if(appType == "Win")
 99                    Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);
100            }            
101            catch(Exception Ex)
102            {
103                throw Ex;
104            }            
105        }
106
107        #endregion // ExportDetails OverLoad : Type#1
108
109        ExportDetails OverLoad : Type#2

解决方案 »

  1.   

    #region ExportDetails OverLoad : Type#2
    110
    111        // Function  : ExportDetails 
    112        // Arguments : DetailsTable, ColumnList, FormatType, FileName        
    113        // Purpose     : To get the specified column headers in the datatable and
    114        //               exorts in CSV / Excel format with specified columns
    115
    116        public void ExportDetails(DataTable DetailsTable, int[] ColumnList, ExportFormat FormatType, string FileName)
    117        {
    118            try
    119            {
    120                if(DetailsTable.Rows.Count == 0)
    121                    throw new Exception("There are no details to export");
    122                
    123                // Create Dataset
    124                DataSet dsExport = new DataSet("Export");
    125                DataTable dtExport = DetailsTable.Copy();
    126                dtExport.TableName = "Values"; 
    127                dsExport.Tables.Add(dtExport);
    128
    129                if(ColumnList.Length > dtExport.Columns.Count)
    130                    throw new Exception("ExportColumn List should not exceed Total Columns");
    131                
    132                // Getting Field Names
    133                string[] sHeaders = new string[ColumnList.Length];
    134                string[] sFileds = new string[ColumnList.Length];
    135                
    136                for (int i=0; i < ColumnList.Length; i++)
    137                {
    138                    if((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))
    139                        throw new Exception("ExportColumn Number should not exceed Total Columns Range");
    140                    
    141                    sHeaders[i] = dtExport.Columns[ColumnList[i]].ColumnName;
    142                    sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;                    
    143                }
    144
    145                if(appType == "Web")
    146                    Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);
    147                else if(appType == "Win")
    148                    Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);
    149            }            
    150            catch(Exception Ex)
    151            {
    152                throw Ex;
    153            }            
    154        }
    155        
    156        #endregion // ExportDetails OverLoad : Type#2
    157
    158        ExportDetails OverLoad : Type#3#region ExportDetails OverLoad : Type#3
    159
    160        // Function  : ExportDetails 
    161        // Arguments : DetailsTable, ColumnList, Headers, FormatType, FileName    
    162        // Purpose     : To get the specified column headers in the datatable and    
    163        //               exorts in CSV / Excel format with specified columns and 
    164        //               with specified headers
    165
    166        public void ExportDetails(DataTable DetailsTable, int[] ColumnList, string[] Headers, ExportFormat FormatType, 
    167            string FileName)
    168        {
    169            try
    170            {
    171                if(DetailsTable.Rows.Count == 0)
    172                    throw new Exception("There are no details to export");
    173                
    174                // Create Dataset
    175                DataSet dsExport = new DataSet("Export");
    176                DataTable dtExport = DetailsTable.Copy();
    177                dtExport.TableName = "Values"; 
    178                dsExport.Tables.Add(dtExport);
    179
    180                if(ColumnList.Length != Headers.Length)
    181                    throw new Exception("ExportColumn List and Headers List should be of same length");
    182                else if(ColumnList.Length > dtExport.Columns.Count || Headers.Length > dtExport.Columns.Count)
    183                    throw new Exception("ExportColumn List should not exceed Total Columns");
    184                
    185                // Getting Field Names
    186                string[] sFileds = new string[ColumnList.Length];
    187                
    188                for (int i=0; i < ColumnList.Length; i++)
    189                {
    190                    if((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))
    191                        throw new Exception("ExportColumn Number should not exceed Total Columns Range");
    192                    
    193                    sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;                    
    194                }
    195
    196                if(appType == "Web")
    197                    Export_with_XSLT_Web(dsExport, Headers, sFileds, FormatType, FileName);
    198                else if(appType == "Win")
    199                    Export_with_XSLT_Windows(dsExport, Headers, sFileds, FormatType, FileName);
    200            }            
    201            catch(Exception Ex)
    202            {
    203                throw Ex;
    204            }            
    205        }
    206        
    207        #endregion // ExportDetails OverLoad : Type#3
    208
    209        ExportDetails OverLoad : Type#3
      

  2.   

    #region ExportDetails OverLoad : Type#3
    210        
    211        // Function  : ExportDetails 
    212        // Arguments : DetailsTable, FormatType, FileName
    213        // Purpose     : To get all the column headers in the datatable and 
    214        //               exorts in CSV / Excel format with all columns
    215
    216        public void ExportDetails(DataTableCollection DetailsTables, ExportFormat FormatType, string FileName)
    217        {
    218            try
    219            {
    220                string NewFileName;
    221        
    222                foreach(DataTable DetailsTable in DetailsTables)
    223                {
    224                    if(DetailsTable.Rows.Count == 0) 
    225                        throw new Exception("There are no details to export.");                
    226                    
    227                    NewFileName = FileName.Substring(0,FileName.LastIndexOf("."));
    228                    NewFileName+= " - " + DetailsTable.TableName;
    229                    NewFileName+= FileName.Substring(FileName.LastIndexOf("."));
    230                                
    231                    // Create Dataset
    232                    DataSet dsExport = new DataSet("Export");
    233                    DataTable dtExport = DetailsTable.Copy();
    234                    dtExport.TableName = "Values"; 
    235                    dsExport.Tables.Add(dtExport);    
    236                
    237                    // Getting Field Names
    238                    string[] sHeaders = new string[dtExport.Columns.Count];
    239                    string[] sFileds = new string[dtExport.Columns.Count];
    240                
    241                    for (int i=0; i < dtExport.Columns.Count; i++)
    242                    {
    243                        sHeaders[i] = dtExport.Columns[i].ColumnName;
    244                        sFileds[i] = dtExport.Columns[i].ColumnName;                    
    245                    }
    246
    247                    if(appType == "Web")
    248                        Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, NewFileName);
    249                    else if(appType == "Win")
    250                        Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, NewFileName);
    251                }
    252            }            
    253            catch(Exception Ex)
    254            {
    255                throw Ex;
    256            }            
    257        }
    258
    259        #endregion //ExportDetails OverLoad : Type#4
    260
    261        Export_with_XSLT_Web#region Export_with_XSLT_Web
    262
    263        // Function  : Export_with_XSLT_Web 
    264        // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName
    265        // Purpose   : Exports dataset into CSV / Excel format
    266
    267        private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
    268        {
    269            try
    270            {                
    271                // Appending Headers
    272                response.Clear();
    273                response.Buffer= true;
    274                
    275                if(FormatType == ExportFormat.CSV)
    276                {
    277                    response.ContentType = "text/csv";
    278                    response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
    279                }        
    280                else
    281                {
    282                    response.ContentType = "application/vnd.ms-excel";
    283                    response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
    284                }
    285
    286                // XSLT to use for transforming this dataset.                        
    287                MemoryStream stream = new MemoryStream( );
    288                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
    289                
    290                CreateStylesheet(writer, sHeaders, sFileds, FormatType);
    291                writer.Flush( ); 
    292                stream.Seek( 0, SeekOrigin.Begin); 
    293
    294                XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
    295                XslTransform xslTran = new XslTransform();                
    296                xslTran.Load(new XmlTextReader(stream), null, null);
    297                                
    298                System.IO.StringWriter  sw = new System.IO.StringWriter();            
    299                xslTran.Transform(xmlDoc, null, sw, null);
    300                                    
    301                //Writeout the Content                
    302                response.Write(sw.ToString());                
    303                sw.Close();    
    304                writer.Close();
    305                stream.Close();            
    306                response.End();
    307            }
    308            catch(ThreadAbortException Ex)
    309            {
    310                string ErrMsg = Ex.Message;
    311            }
    312            catch(Exception Ex)
    313            {
    314                throw Ex;
    315            }
    316        }        
    317        
    318        #endregion // Export_with_XSLT 
    319
    320        Export_with_XSLT_Windows