WinForm method of exporting files as Word Excel text files

  • 2020-12-20 03:43:51
  • OfStack

I haven't written an article for a long time. The following is the method of exporting a small file used in my recent program to share 1 at home. Welcome everyone to arrange bricks.


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>
///  The author: SunYujing
///  Date: 2011-12-18
/// </remarks>
  public class ExportFile
  {
    /// <summary>
///  Stores the string as word Method of document format files ( multithreading ) . 
/// </summary>
/// <param name="strText"> The contents of the string to save. </param>
    public static void SaveAsWord(string p_str)
    {
      Thread thread = new Thread(SaveAsWordFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(p_str);
    }
    /// <summary>
///  Stores the string as txt The method of formatting a file ( multithreading ) . 
/// </summary>
/// <param name="p_str"></param>
    public static void SaveAsTxt(string p_str)
    {
      Thread thread = new Thread(SaveAsTxtFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(p_str);
    }
    /// <summary>
///  Export data table data to Excel( multithreading ) . 
/// </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( multithreading ) . 
/// </summary>
    public static void SaveAsExcel(System.Data.DataSet dataSet)
    {
      if (dataSet == null)
      {
        MessageUtil.ShowError(" Specify the data set to export first ");
        return;
      }
      Thread thread = new Thread(SaveAsExcelSetFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(dataSet);
    }
    /// <summary>
///  Stores the string as word File in document format. 
/// </summary>
/// <param name="strtext"> The contents of the string to save. </param>
    private static void SaveAsWordFile(object strtext)
    {
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = " Please select the file storage path ";
      sfd.FileName = " Export data ";
      sfd.Filter = "Word The 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(" Please wait while saving the file ...");
        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 nothing, ref nothing, ref nothing);
        doc.Paragraphs.Last.Range.Text = strtext.ToString();
        object myfileName = FileName;
        // will WordDoc The contents of the document object are saved as doc The document 
        doc.SaveAs(ref myfileName, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing);
        // Shut down WordDoc The document object 
        doc.Close(ref nothing, ref nothing, ref nothing);
        // Shut down WordApp Component object 
        word.Quit(ref nothing, ref nothing, ref nothing);
        GC.Collect();
        DateTime end = DateTime.Now;
        TimeSpan ts = end - start;
        MessageUtil.ShowMessage(" File saved successfully, use " + ts.ToString());
      }
      catch (System.Exception ex)
      {
        MessageUtil.ShowError(ex.Message);
      }
    }
    /// <summary>
///  Stores the string as txt File in document format. 
/// </summary>
/// <param name="strtext"> The contents of the string to save. </param>
    private static void SaveAsTxtFile(object strtext)
    {
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = " Please select the file storage path ";
      sfd.FileName = " Export data ";
      sfd.Filter = " A 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, use " + ts.ToString());
      }
      catch (Exception ex)
      {
        MessageUtil.ShowError(ex.Message);
      }
    }
    /// <summary>
///  Store the data as Excel File. 
/// </summary>
/// <param name="p_dt"> The 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(" There is no data to save ");
        return;
      }
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = " Please select the file storage path ";
      sfd.FileName = " Export data ";
      sfd.Filter = "Excel The 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.Application();
        if (excelApp == null)
        {
          MessageBox.Show(" Unable to create the Excel Object, perhaps your machine is not installed Excel");
          return;
        }
        else
        {
          MessageUtil.ShowThreadMessage(" Please wait while data is being exported ...");
          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;
          // Using garbage collection can be turned off EXCEL.EXE process 
          GC.Collect();
          DateTime end = DateTime.Now;
          int iTimeSpan = (end.Minute - start.Minute) * 60 + (end.Second - start.Second);
          MessageUtil.ShowMessage(" Data export finished , when " + iTimeSpan.ToString() + " seconds ");
        }
      }
    }
    /// <summary>
///  Store the data set as Excel File. 
/// </summary>
/// <param name="p_ds"> The data set to export. </param>
    private static void SaveAsExcelSetFile(object p_ds)
    {
      System.Data.DataSet ds = (System.Data.DataSet)p_ds;
      if (ds == null || ds.Tables.Count == 0)
      {
        MessageUtil.ShowError(" There is no data to save ");
        return;
      }
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = " Please select the file storage path ";
      sfd.FileName = " Export data ";
      sfd.Filter = "Excel The 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.Application();
        if (excelApp == null)
        {
          MessageBox.Show(" Unable to create the Excel Object, perhaps your machine is not installed Excel");
          return;
        }
        else
        {
          MessageUtil.ShowThreadMessage(" Please wait while data is being exported ...");
          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) * 60 + (end.Second - start.Second);
          MessageUtil.ShowMessage(" Data export finished , when " + (iTimeSapn / 60).ToString() + " points " + (iTimeSapn % 60).ToString() + " seconds ");
        }
      }
    }
  }
}


Related articles: