Export.cs

Description du code

Export.cs est un fichier du projet BrolDev.
Ce fichier est situé dans /var/www/bin/sniplets/bibliobrol/broldev/src/.

Projet BrolDev : Librairie de composants réutilisables pour les applications BrolDev en CSharp.

Code source ou contenu du fichier

  1. using System;
  2. using System.Data;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Xml;
  7. using System.Xml.Xsl;
  8. using be.gaudry.model.enums;
  9.  
  10. namespace be.gaudry.model
  11. {
  12. # region Summary
  13.  
  14. /// <summary>
  15. /// Exports datatable to CSV or Excel format.
  16. /// This uses DataSet's XML features and XSLT for exporting.
  17. ///
  18. /// C#.Net Example to be used in WebForms
  19. /// -------------------------------------
  20. /// using MyLib.ExportData;
  21. ///
  22. /// private void btnExport_Click(object sender, System.EventArgs e)
  23. /// {
  24. /// try
  25. /// {
  26. /// // Declarations
  27. /// DataSet dsUsers = ((DataSet) Session["dsUsers"]).Copy( );
  28. /// MyLib.ExportData.Export oExport = new MyLib.ExportData.Export("Web");
  29. /// string FileName = "UserList.csv";
  30. /// int[] ColList = {2, 3, 4, 5, 6};
  31. /// oExport.ExportDetails(dsUsers.Tables[0], ColList, Export.EXPORT_FORMAT.CSV, FileName);
  32. /// }
  33. /// catch(Exception Ex)
  34. /// {
  35. /// lblError.Text = Ex.Message;
  36. /// }
  37. /// }
  38. ///
  39. /// VB.Net Example to be used in WindowsForms
  40. /// -----------------------------------------
  41. /// Imports MyLib.ExportData
  42. ///
  43. /// Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
  44. ///
  45. /// Try
  46. ///
  47. /// 'Declarations
  48. /// Dim dsUsers As DataSet = (CType(Session("dsUsers"), DataSet)).Copy()
  49. /// Dim oExport As New MyLib.ExportData.Export("Win")
  50. /// Dim FileName As String = "C:\\UserList.xls"
  51. /// Dim ColList() As Integer = New Integer() {2, 3, 4, 5, 6}
  52. /// oExport.ExportDetails(dsUsers.Tables(0), ColList, Export.EXPORT_FORMAT.CSV, FileName)
  53. ///
  54. /// Catch Ex As Exception
  55. /// lblError.Text = Ex.Message
  56. /// End Try
  57. ///
  58. /// End Sub
  59. ///
  60. /// </summary>
  61.  
  62. # endregion // Summary
  63.  
  64. public class Export
  65. {
  66. public enum APPLICATION_TYPE
  67. {
  68. Web,
  69. Win
  70. }
  71. System.Web.HttpResponse response;
  72. private APPLICATION_TYPE appType;
  73.  
  74. public Export()
  75. {
  76. appType = APPLICATION_TYPE.Win;
  77. //response = System.Web.HttpContext.Current.Response;
  78. }
  79.  
  80. public Export(APPLICATION_TYPE ApplicationType)
  81. {
  82. appType = ApplicationType;
  83. //if(appType != "Web" && appType != "Win") throw new Exception("Provide valid application format (Web/Win)");
  84. if (appType == APPLICATION_TYPE.Web) response = System.Web.HttpContext.Current.Response;
  85. }
  86.  
  87. #region ExportDetails OverLoad : Type#1
  88.  
  89. // Function : ExportDetails
  90. // Arguments : DetailsTable, FormatType, FileName
  91. // Purpose : To get all the column headers in the datatable and
  92. // exorts in CSV / Excel format with all columns
  93.  
  94. public void ExportDetails(DataTable DetailsTable, BROL_EXPORT_FORMAT FormatType, string FileName)
  95. {
  96. try
  97. {
  98. if(DetailsTable.Rows.Count == 0)
  99. throw new Exception("There are no details to export.");
  100.  
  101. // Create Dataset
  102. DataSet dsExport = new DataSet("Export");
  103. DataTable dtExport = DetailsTable.Copy();
  104. dtExport.TableName = "Values";
  105. dsExport.Tables.Add(dtExport);
  106.  
  107. // Getting Field Names
  108. string[] sHeaders = new string[dtExport.Columns.Count];
  109. string[] sFileds = new string[dtExport.Columns.Count];
  110.  
  111. for (int i=0; i < dtExport.Columns.Count; i++)
  112. {
  113. sHeaders[i] = dtExport.Columns[i].ColumnName;
  114. sFileds[i] = dtExport.Columns[i].ColumnName;
  115. }
  116.  
  117. if (appType == APPLICATION_TYPE.Web)
  118. Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);
  119. else if (appType == APPLICATION_TYPE.Win)
  120. Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);
  121. }
  122. catch(Exception Ex)
  123. {
  124. throw Ex;
  125. }
  126. }
  127.  
  128. #endregion // ExportDetails OverLoad : Type#1
  129.  
  130. #region ExportDetails OverLoad : Type#2
  131.  
  132. // Function : ExportDetails
  133. // Arguments : DetailsTable, ColumnList, FormatType, FileName
  134. // Purpose : To get the specified column headers in the datatable and
  135. // exorts in CSV / Excel format with specified columns
  136.  
  137. public void ExportDetails(DataTable DetailsTable, int[] ColumnList, BROL_EXPORT_FORMAT FormatType, string FileName)
  138. {
  139. try
  140. {
  141. if(DetailsTable.Rows.Count == 0)
  142. throw new Exception("There are no details to export");
  143.  
  144. // Create Dataset
  145. DataSet dsExport = new DataSet("Export");
  146. DataTable dtExport = DetailsTable.Copy();
  147. dtExport.TableName = "Values";
  148. dsExport.Tables.Add(dtExport);
  149.  
  150. if(ColumnList.Length > dtExport.Columns.Count)
  151. throw new Exception("ExportColumn List should not exceed Total Columns");
  152.  
  153. // Getting Field Names
  154. string[] sHeaders = new string[ColumnList.Length];
  155. string[] sFileds = new string[ColumnList.Length];
  156.  
  157. for (int i=0; i < ColumnList.Length; i++)
  158. {
  159. if((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))
  160. throw new Exception("ExportColumn Number should not exceed Total Columns Range");
  161.  
  162. sHeaders[i] = dtExport.Columns[ColumnList[i]].ColumnName;
  163. sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;
  164. }
  165.  
  166. if (appType == APPLICATION_TYPE.Web)
  167. Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);
  168. else if (appType == APPLICATION_TYPE.Win)
  169. Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);
  170. }
  171. catch(Exception Ex)
  172. {
  173. throw Ex;
  174. }
  175. }
  176.  
  177. #endregion // ExportDetails OverLoad : Type#2
  178.  
  179. #region ExportDetails OverLoad : Type#3
  180.  
  181. // Function : ExportDetails
  182. // Arguments : DetailsTable, ColumnList, Headers, FormatType, FileName
  183. // Purpose : To get the specified column headers in the datatable and
  184. // exorts in CSV / Excel format with specified columns and
  185. // with specified headers
  186.  
  187. public void ExportDetails(DataTable DetailsTable, int[] ColumnList, string[] Headers, BROL_EXPORT_FORMAT FormatType,
  188. string FileName)
  189. {
  190. try
  191. {
  192. if(DetailsTable.Rows.Count == 0)
  193. throw new Exception("There are no details to export");
  194.  
  195. // Create Dataset
  196. DataSet dsExport = new DataSet("Export");
  197. DataTable dtExport = DetailsTable.Copy();
  198. dtExport.TableName = "Values";
  199. dsExport.Tables.Add(dtExport);
  200.  
  201. if(ColumnList.Length != Headers.Length)
  202. throw new Exception("ExportColumn List and Headers List should be of same length");
  203. else if(ColumnList.Length > dtExport.Columns.Count || Headers.Length > dtExport.Columns.Count)
  204. throw new Exception("ExportColumn List should not exceed Total Columns");
  205.  
  206. // Getting Field Names
  207. string[] sFileds = new string[ColumnList.Length];
  208.  
  209. for (int i=0; i < ColumnList.Length; i++)
  210. {
  211. if((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))
  212. throw new Exception("ExportColumn Number should not exceed Total Columns Range");
  213.  
  214. sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;
  215. }
  216.  
  217. if (appType == APPLICATION_TYPE.Web)
  218. Export_with_XSLT_Web(dsExport, Headers, sFileds, FormatType, FileName);
  219. else if (appType == APPLICATION_TYPE.Win)
  220. Export_with_XSLT_Windows(dsExport, Headers, sFileds, FormatType, FileName);
  221. }
  222. catch(Exception Ex)
  223. {
  224. throw Ex;
  225. }
  226. }
  227.  
  228. #endregion // ExportDetails OverLoad : Type#3
  229.  
  230. #region Export_with_XSLT_Web
  231.  
  232. // Function : Export_with_XSLT_Web
  233. // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName
  234. // Purpose : Exports dataset into CSV / Excel format
  235.  
  236. private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, BROL_EXPORT_FORMAT FormatType, string FileName)
  237. {
  238. try
  239. {
  240. // Appending Headers
  241. response.Clear();
  242. response.Buffer= true;
  243. switch (FormatType)
  244. {
  245. case BROL_EXPORT_FORMAT.CSV:
  246. response.ContentType = "text/csv";
  247. response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
  248. break;
  249. case BROL_EXPORT_FORMAT.Excel:
  250. response.ContentType = "application/vnd.ms-excel";
  251. response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
  252. break;
  253. default:
  254. throw new Exception("Format d'exportation non suporté : " + FormatType.ToString());
  255. }
  256.  
  257. // XSLT to use for transforming this dataset.
  258. MemoryStream stream = new MemoryStream( );
  259. XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
  260.  
  261. CreateStylesheet(writer, sHeaders, sFileds, FormatType);
  262. writer.Flush( );
  263. stream.Seek( 0, SeekOrigin.Begin);
  264.  
  265. XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
  266. XslCompiledTransform xslTran = new XslCompiledTransform();
  267.  
  268. System.IO.StringWriter sw = new System.IO.StringWriter();
  269. xslTran.Transform(new XmlTextReader(stream), writer);
  270.  
  271. //Writeout the Content
  272. response.Write(sw.ToString());
  273. sw.Close();
  274. writer.Close();
  275. stream.Close();
  276. response.End();
  277. }
  278. catch(ThreadAbortException Ex)
  279. {
  280. string ErrMsg = Ex.Message;
  281. }
  282. catch(Exception Ex)
  283. {
  284. throw Ex;
  285. }
  286. }
  287.  
  288. #endregion // Export_with_XSLT
  289.  
  290. #region Export_with_XSLT_Windows
  291.  
  292. // Function : Export_with_XSLT_Windows
  293. // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName
  294. // Purpose : Exports dataset into CSV / Excel format
  295.  
  296. private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, BROL_EXPORT_FORMAT FormatType, string FileName)
  297. {
  298. try
  299. {
  300. // XSLT to use for transforming this dataset.
  301. MemoryStream stream = new MemoryStream( );
  302. XmlTextWriter writer = new XmlTextWriter(stream, Encoding.GetEncoding("iso-8859-1"));
  303.  
  304. if(FormatType!=BROL_EXPORT_FORMAT.CSV && FormatType!=BROL_EXPORT_FORMAT.Excel)
  305. {
  306. throw new Exception("Format d'exportation non suporté : " + FormatType.ToString());
  307. }
  308. CreateStylesheet(writer, sHeaders, sFileds, FormatType);
  309. writer.Flush( );
  310. stream.Seek( 0, SeekOrigin.Begin);
  311.  
  312. XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
  313. XslTransform xslTran = new XslTransform();
  314. xslTran.Load(new XmlTextReader(stream), null, null);
  315.  
  316. System.IO.StringWriter sw = new System.IO.StringWriter();
  317. xslTran.Transform(xmlDoc, null, sw, null);
  318.  
  319. //Writeout the Content
  320. StreamWriter strwriter = new StreamWriter(FileName,false, Encoding.GetEncoding("iso-8859-1"));
  321. strwriter.WriteLine(sw.ToString());
  322. strwriter.Close();
  323.  
  324. sw.Close();
  325. writer.Close();
  326. stream.Close();
  327. }
  328. catch(Exception Ex)
  329. {
  330. throw Ex;
  331. }
  332. }
  333.  
  334. #endregion // Export_with_XSLT
  335.  
  336. #region CreateStylesheet
  337.  
  338. // Function : WriteStylesheet
  339. // Arguments : writer, sHeaders, sFileds, FormatType
  340. // Purpose : Creates XSLT file to apply on dataset's XML file
  341.  
  342. private void CreateStylesheet(XmlTextWriter writer, string[] sHeaders, string[] sFileds, BROL_EXPORT_FORMAT FormatType)
  343. {
  344. try
  345. {
  346. // xsl:stylesheet
  347. string ns = "http://www.w3.org/1999/XSL/Transform";
  348. writer.Formatting = Formatting.Indented;
  349. writer.WriteStartDocument( );
  350. writer.WriteStartElement("xsl","stylesheet",ns);
  351. writer.WriteAttributeString("version","1.0");
  352. writer.WriteStartElement("xsl:output");
  353. writer.WriteAttributeString("method","text");
  354. writer.WriteAttributeString("version","4.0");
  355. writer.WriteEndElement( );
  356.  
  357. // xsl-template
  358. writer.WriteStartElement("xsl:template");
  359. writer.WriteAttributeString("match","/");
  360.  
  361. // xsl:value-of for headers
  362. for(int i=0; i< sHeaders.Length; i++)
  363. {
  364. writer.WriteString("\"");
  365. writer.WriteStartElement("xsl:value-of");
  366. writer.WriteAttributeString("select", "'" + sHeaders[i].Replace("'"," ") + "'");
  367. writer.WriteEndElement( ); // xsl:value-of
  368. writer.WriteString("\"");
  369. if (i != sFileds.Length - 1) writer.WriteString( (FormatType == BROL_EXPORT_FORMAT.CSV ) ? "," : " " );
  370. }
  371.  
  372. // xsl:for-each
  373. writer.WriteStartElement("xsl:for-each");
  374. writer.WriteAttributeString("select","Export/Values");
  375. writer.WriteString("\r\n");
  376.  
  377. // xsl:value-of for data fields
  378. for(int i=0; i< sFileds.Length; i++)
  379. {
  380. writer.WriteString("\"");
  381. writer.WriteStartElement("xsl:value-of");
  382. writer.WriteAttributeString("select", sFileds[i]);
  383. writer.WriteEndElement( ); // xsl:value-of
  384. writer.WriteString("\"");
  385. if (i != sFileds.Length - 1) writer.WriteString( (FormatType == BROL_EXPORT_FORMAT.CSV ) ? "," : " " );
  386. }
  387.  
  388. writer.WriteEndElement( ); // xsl:for-each
  389. writer.WriteEndElement( ); // xsl-template
  390. writer.WriteEndElement( ); // xsl:stylesheet
  391. writer.WriteEndDocument( );
  392. }
  393. catch(Exception Ex)
  394. {
  395. throw Ex;
  396. }
  397. }
  398.  
  399. #endregion // WriteStylesheet
  400.  
  401. }
  402. }

Structure et Fichiers du projet

Afficher/masquer...


Répertoires contenus dans /var/www/bin/sniplets/bibliobrol/broldev/src/model/ 
IcôneNomTailleModification
IcôneNomTailleModification
| _ Répertoire parent0 octets1714277552 28/04/2024 06:12:32
| _config0 octets1541007188 31/10/2018 18:33:08
| _enums0 octets1541007189 31/10/2018 18:33:09
| _exceptions0 octets1541007189 31/10/2018 18:33:09
| _drawing0 octets1541007188 31/10/2018 18:33:08
| _win320 octets1541007190 31/10/2018 18:33:10
| _file0 octets1541007190 31/10/2018 18:33:10
| _comparators0 octets1541007188 31/10/2018 18:33:08
Fichiers contenus dans /var/www/bin/sniplets/bibliobrol/broldev/src/model/ 
IcôneNomTailleModificationAction
IcôneNomTailleModificationAction
Afficher le fichier .cs|.csWebHelper.cs841 octets31/10/2018 18:32:48-refusé-
Afficher le fichier .cs|.csHistory.cs6.96 Ko31/10/2018 18:32:48-refusé-
Afficher le fichier .cs|.csValueObject.cs664 octets31/10/2018 18:32:48-refusé-
Afficher le fichier .cs|.csExport.cs13.3 Ko31/10/2018 18:32:47-refusé-
Afficher le fichier .cs|.csDisposableObject.cs883 octets31/10/2018 18:32:47-refusé-
Afficher le fichier .cs|.csStat.cs3.63 Ko31/10/2018 18:32:48-refusé-
Afficher le fichier .cs|.csTextHelper.cs8.11 Ko31/10/2018 18:32:48-refusé-
Afficher le fichier .cs|.csUnits.cs2.07 Ko31/10/2018 18:32:48-refusé-

Utilisation de l'explorateur de code

  • Navigation :
    • Un clic sur une icône de répertoire ouvre ce répertoire pour en afficher les fichiers.
    • Lorsque le répertoire en cours ne contient pas de sous-répertoires il est possible de remonter vers le répertoire parent.
    • La structure de répertoires en treetable (tableau en forme d'arborescence) n'est plus possibledans cette version.
    • Un clic sur une icône de fichier ouvre ce fichier pour en afficher le code avec la coloration syntaxique adaptée en fonction du langage principal utilisé dans le fichier.
  • Affichage :
    • Il est possible de trier les répertoires ou les fichiers selon certains critères (nom, taille, date).
  • Actions :
    • Les actions possible sur les fichiers dépendent de vos droits d'utilisateur sur le site. Veuillez activer le mode utilisateur pour activer les actions.

Document créé le 16/10/2009, dernière modification le 26/10/2018
Source du document imprimé : https://www.gaudry.be/cs-broldev-source-rf-model//Export.cs.html

L'infobrol est un site personnel dont le contenu n'engage que moi. Le texte est mis à disposition sous licence CreativeCommons(BY-NC-SA). Plus d'info sur les conditions d'utilisation et sur l'auteur.