WinForm How to export files as Word, Excel, text files

Source: Internet
Author: User

For a long time did not write the article, the following one of their recent procedures used in a small export file method to share at home, welcome everyone to row bricks, thank you not to say nonsense, directly on the code:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Windows.Forms;using System.threading;using microsoft.office.interop.word;using system.io;using microsoft.office.interop.excel;using Sun.winform.util;namespace sun.winform.files{///<summary>///export the content as a file class. </summary>///<remarks>///sunyujing///Date: 2011-12-18///</remarks> public class Exportfile {/ <summary>///the method of storing a string as a file in Word Document Format (multithreaded). </summary>///<param name= "StrText" > String content to save.      </param> public static void Saveasword (string p_str) {Thread thread = new Thread (saveaswordfile); Thread.      Setapartmentstate (ApartmentState.STA); Thread.    Start (P_STR); }///<summary>///the method of storing the string as a file in TXT format (multithreaded). </summary>///<param name= "p_str" ></param> public static void Saveastxt (String p_str) {T      Hread thread = new Thread (saveastxtfile); Thread. Setapartmentstate (ApartmentState.STA); Thread.    Start (P_STR); }///<summary>///Export data table data to Excel (multithreaded).      </summary> public static void Saveasexcel (System.Data.DataTable DataTable) {if (datatable = = null)        {Messageutil.showerror (Specify the data table to export first);      Return      } thread thread = new Thread (saveasexceltablefile); Thread.      Setapartmentstate (ApartmentState.STA); Thread.    Start (dataTable); }///<summary>///export DataSet data to Excel (multithreaded).        </summary> public static void Saveasexcel (System.Data.DataSet dataset) {if (DataSet = = null) {        Messageutil.showerror ("Specify the dataset to be exported first");      Return      } thread thread = new Thread (saveasexcelsetfile); Thread.      Setapartmentstate (ApartmentState.STA); Thread.    Start (DataSet); ///<summary>///store the string as a file in Word document format. </summary>///<param name= "strtext" > String content to save. </param> private static void Saveaswordfile (object strtext) {SaveFileDialog sfd = new SavEfiledialog (); SfD.      Title = "Please select file path"; SfD.      FileName = "Export Data"; SfD.      Filter = "Word document (*.doc) |*.doc"; if (SFD.      ShowDialog ()! = DialogResult.OK) {return; } string FileName = sfd.      Filename.tolower (); if (!      Filename.contains (". Doc")) {FileName + = ". Doc"; } if (Filename.substring (Filename.lastindexof (Path.directoryseparatorchar)). Length <= 5) {messageutil.showthreadmessage ("File save failed, filename cannot be empty!        ");      Return        } try {DateTime start = DateTime.Now;        Messageutil.showthreadmessage ("Saving file, please wait ...");        Microsoft.Office.Interop.Word.ApplicationClass Word = new Microsoft.Office.Interop.Word.ApplicationClass ();        Microsoft.office.interop.word._document Doc;        Object nothing = System.Reflection.Missing.Value; Doc = Word.        Documents.Add (ref nothing, ref no, ref nothing, ref nothing); Doc. Paragraphs.Last.Range.Text = strtext.        ToString (); Object myFileName =FileName; Saves the contents of the WordDoc Document object as Doc document Doc. SaveAs (ref myfilename, ref-nothing, ref-nothing, ref-nothing, ref-nothing, ref-nothing, ref-nothing, ref-nothing, ref noth        ING, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing); Close the WordDoc Document object doc.        Close (ref nothing, ref nothing, ref nothing); Close the WordApp Component Object Word.        Quit (ref nothing, ref no, ref nothing); Gc.        Collect ();        DateTime end = DateTime.Now;        TimeSpan ts = End-start; Messageutil.showmessage ("File saved successfully, time" + TS.)      ToString ()); } catch (System.Exception ex) {Messageutil.showerror (ex.      Message); }}///<summary>///the string as a file in TXT document format. </summary>///<param name= "strtext" > String content to save.      </param> private static void Saveastxtfile (object strtext) {SaveFileDialog sfd = new SaveFileDialog (); SfD.      Title = "Please select file path"; SfD.      FileName = "Export Data"; SfD. Filter = "Text Document (*.txt) |*.txt "; if (SFD.      ShowDialog ()! = DialogResult.OK) {return; } string FileName = sfd.      Filename.tolower (); if (!      Filename.contains (". txt")) {FileName + = ". txt"; } if (Filename.substring (Filename.lastindexof (Path.directoryseparatorchar)). Length <= 5) {messageutil.showthreadmessage ("File save failed, filename cannot be empty!        ");      Return        } try {DateTime start = DateTime.Now;        StreamWriter SW = new StreamWriter (FileName, false); Sw. Write (strtext.        ToString ()); Sw.        Flush (); Sw.        Close ();        DateTime end = DateTime.Now;        TimeSpan ts = End-start; Messageutil.showmessage ("File saved successfully, time" + TS.)      ToString ()); } catch (Exception ex) {Messageutil.showerror (ex.      Message); }}///<summary>///store the data as an Excel file. </summary>///<param name= "P_DT" > Data table to save. </param> private static void Saveasexceltablefile (object P_dt) {System.Data.DataTable dt = (System.Data.DataTable) P_dt; if (dt.        Rows.Count = = 0) {messageutil.showerror ("No data to be saved");      Return      } SaveFileDialog sfd = new SaveFileDialog (); SfD.      Title = "Please select file path"; SfD.      FileName = "Export Data"; SfD.      Filter = "Excel document (*.xls) |*.xls"; if (SFD.      ShowDialog ()! = DialogResult.OK) {return; } string FileName = sfd.      Filename.tolower (); if (!      Filename.contains (". xls")) {FileName + = ". xls"; } if (Filename.substring (Filename.lastindexof (Path.directoryseparatorchar)). Length <= 5) {messageutil.showthreadmessage ("File save failed, filename cannot be empty!        ");      Return } if (SFD. FileName = "") {Microsoft.Office.Interop.Excel.Application excelapp = new MICROSOFT.OFFICE.INTEROP.EXCEL.APP        Lication ();          if (excelapp = = null) {MessageBox.Show ("Unable to create Excel object, may not have Excel installed on your machine");        Return } else {Messageutil.showthreadmessage ("in progressData, please wait ... ");          DateTime start = DateTime.Now;          Microsoft.Office.Interop.Excel.Workbooks Workbooks = excelapp.workbooks; Microsoft.Office.Interop.Excel.Workbook Workbook = workbooks.          ADD (Xlwbatemplate.xlwbatworksheet); Microsoft.Office.Interop.Excel.Worksheet Worksheet = (Worksheet) workbook.          WORKSHEETS[1]; for (int col = 1; col <= dt. Columns.count; col++) {worksheet. Cells[1, col] = dt. COLUMNS[COL-1].          Caption.tostring (); } for (int i = 0; i < dt. Rows.Count; i++) {for (int j = 0; j < dt. Columns.count; J + +) {worksheet. Cells[i + 2, j + 1] = dt. ROWS[I][J].            ToString (); }} workbook.          Saved = true; Workbook. SaveCopyAs (SFD).          FileName);          Release Resources System.Runtime.InteropServices.Marshal.ReleaseComObject (worksheet);          worksheet = null; System.Runtime.InteropServices.Marshal.ReleaseComObject (workbook);         workbook = null; Workbooks.          Close ();          System.Runtime.InteropServices.Marshal.ReleaseComObject (workbooks);          workbooks = null;          Excelapp.quit ();          System.Runtime.InteropServices.Marshal.ReleaseComObject (excelapp);          Excelapp = null; Use garbage collection to shut down the EXCEL.EXE process GC.          Collect ();          DateTime end = DateTime.Now; int itimespan = (end. Minute-start. Minute) * + (end. Second-start.          Second);        Messageutil.showmessage ("Data export completed, time" + itimespan.tostring () + "seconds"); }}}///<summary>///Save the DataSet as an Excel file. </summary>///<param name= "P_ds" > Datasets to be exported. </param> private static void Saveasexcelsetfile (object p_ds) {System.Data.DataSet ds = (System.Data.Data      Set) P_ds; if (ds = = null | | ds.        Tables.count = = 0) {messageutil.showerror ("No data to be saved");      Return      } SaveFileDialog sfd = new SaveFileDialog (); SfD.      Title = "Please select file path"; SfD. FIlename = "Export Data"; SfD.      Filter = "Excel document (*.xls) |*.xls"; if (SFD.      ShowDialog ()! = DialogResult.OK) {return; } string FileName = sfd.      Filename.tolower (); if (!      Filename.contains (". xls")) {FileName + = ". xls"; } if (Filename.substring (Filename.lastindexof (Path.directoryseparatorchar)). Length <= 5) {messageutil.showthreadmessage ("File save failed, filename cannot be empty!        ");      Return } if (SFD. FileName = "") {Microsoft.Office.Interop.Excel.Application excelapp = new MICROSOFT.OFFICE.INTEROP.EXCEL.APP        Lication ();          if (excelapp = = null) {MessageBox.Show ("Unable to create Excel object, may not have Excel installed on your machine");        Return          } else {Messageutil.showthreadmessage ("Exporting data, please wait ...");          DateTime start = DateTime.Now;          Microsoft.Office.Interop.Excel.Workbooks Workbooks = excelapp.workbooks; Microsoft.Office.Interop.Excel.Workbook Workbook = workbooks. ADD (XLWBATEMPLATE.XLWBAtworksheet);          Microsoft.Office.Interop.Excel.Worksheet Worksheet = null;          Object objmissing = System.Reflection.Missing.Value; for (int m = 0; m < ds. Tables.count; m++) {System.Data.DataTable dt = ds.            TABLES[M]; Worksheet = (worksheet) workbook.            ActiveSheet; Worksheet. Name = dt.            TableName; for (int col = 1; col <= dt. Columns.count; col++) {worksheet. Cells[1, col] = dt. COLUMNS[COL-1].            Caption.tostring (); } for (int i = 1; I <= dt. Rows.Count; i++) {for (int j = 1; j <= dt. Columns.count; J + +) {worksheet. Cells[i + 1, j] = dt. ROWS[I-1][J-1].              ToString (); }} if (M < ds. tables.count-1) {workbook.            Sheets.add (Objmissing, objmissing, 1, xlsheettype.xlworksheet); }} workbook.          Saved = true; Workbook. SavecopyAs (SFD).          FileName);          Release Resources System.Runtime.InteropServices.Marshal.ReleaseComObject (worksheet);          worksheet = null;          System.Runtime.InteropServices.Marshal.ReleaseComObject (workbook);          workbook = null; Workbooks.          Close ();          System.Runtime.InteropServices.Marshal.ReleaseComObject (workbooks);          workbooks = null;          Excelapp.quit ();          System.Runtime.InteropServices.Marshal.ReleaseComObject (excelapp);          Excelapp = null; Gc.          Collect ();          DateTime end = DateTime.Now; int ITIMESAPN = (end. Minute-start. Minute) * + (end. Second-start.          Second); Messageutil.showmessage ("Data export completed, time" + (ITIMESAPN/60). ToString () + "min" + (itimesapn% 60).        ToString () + "seconds"); }      }    }  }}

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
WinForm How to export files as Word, Excel, text files

This address: http://www.paobuke.com/develop/c-develop/pbk23123.html






Related content implementation of a state machine C # List sorting various usages and Comparisons C # simple method for calculating time intervals (recommended) C # uses regular expressions to filter HTML tags
C # A workaround that passes multiple parameters to a thread (two) in-depth parsing of generic classes in C # and generic interfaces in C # Dotnetcharting's usage examples are detailed in C # 's path. GetFullPath get the parent directory implementation method

WinForm How to export files as Word, Excel, text files

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.