程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> WinForm導出文件為Word、Excel、文本文件的辦法

WinForm導出文件為Word、Excel、文本文件的辦法

編輯:C#入門知識

WinForm導出文件為Word、Excel、文本文件的辦法。本站提示廣大學習愛好者:(WinForm導出文件為Word、Excel、文本文件的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是WinForm導出文件為Word、Excel、文本文件的辦法正文


很久沒有寫文章了,上面把本身比來法式頂用到的一個小小的導出文件的辦法給在家分享一下,迎接年夜家來排磚,感謝~不說空話了,直接上代碼:

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>
/// 將內容導出為文件類。
/// </summary>
/// <remarks>
/// 作者:SunYujing
/// 日期:2011-12-18
/// </remarks>
  public class ExportFile
  {
    /// <summary>
/// 將字符串存儲為word文檔格局的文件的辦法(多線程)。
/// </summary>
/// <param name="strText">要保留的字符串內容。</param>
    public static void SaveAsWord(string p_str)
    {
      Thread thread = new Thread(SaveAsWordFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(p_str);
    }
    /// <summary>
/// 將字符串存儲為txt格局的文件的辦法(多線程)。
/// </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>
/// 導出數據表數據到Excel(多線程)。
/// </summary>
    public static void SaveAsExcel(System.Data.DataTable dataTable)
    {
      if (dataTable == null)
      {
        MessageUtil.ShowError("請先指定要導出的數據表");
        return;
      }
      Thread thread = new Thread(SaveAsExcelTableFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(dataTable);
    }
    /// <summary>
/// 導出數據集數據到Excel(多線程)。
/// </summary>
    public static void SaveAsExcel(System.Data.DataSet dataSet)
    {
      if (dataSet == null)
      {
        MessageUtil.ShowError("請先指定要導出的數據集");
        return;
      }
      Thread thread = new Thread(SaveAsExcelSetFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(dataSet);
    }
    /// <summary>
/// 將字符串存儲為word文檔格局的文件。
/// </summary>
/// <param name="strtext">要保留的字符串內容。</param>
    private static void SaveAsWordFile(object strtext)
    {
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請選擇文件寄存途徑";
      sfd.FileName = "導出數據";
      sfd.Filter = "Word文檔(*.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("文件保留掉敗,文件名不克不及為空!");
        return;
      }
      try
      {
        DateTime start = DateTime.Now;
        MessageUtil.ShowThreadMessage("正在保留文件,請稍候...");
        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;
        //將WordDoc文檔對象的內容保留為doc文檔
        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);
        //封閉WordDoc文檔對象
        doc.Close(ref nothing, ref nothing, ref nothing);
        //封閉WordApp組件對象
        word.Quit(ref nothing, ref nothing, ref nothing);
        GC.Collect();
        DateTime end = DateTime.Now;
        TimeSpan ts = end - start;
        MessageUtil.ShowMessage("文件保留勝利,用時" + ts.ToString());
      }
      catch (System.Exception ex)
      {
        MessageUtil.ShowError(ex.Message);
      }
    }
    /// <summary>
/// 將字符串存儲為txt文檔格局的文件。
/// </summary>
/// <param name="strtext">要保留的字符串內容。</param>
    private static void SaveAsTxtFile(object strtext)
    {
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請選擇文件寄存途徑";
      sfd.FileName = "導出數據";
      sfd.Filter = "文本文檔(*.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("文件保留掉敗,文件名不克不及為空!");
        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("文件保留勝利,用時" + ts.ToString());
      }
      catch (Exception ex)
      {
        MessageUtil.ShowError(ex.Message);
      }
    }
    /// <summary>
/// 將數據存儲為Excel文件。
/// </summary>
/// <param name="p_dt">要保留的數據表。</param>
    private static void SaveAsExcelTableFile(object p_dt)
    {
      System.Data.DataTable dt = (System.Data.DataTable)p_dt;
      if (dt.Rows.Count == 0)
      {
        MessageUtil.ShowError("沒有可保留的數據");
        return;
      }
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請選擇文件寄存途徑";
      sfd.FileName = "導出數據";
      sfd.Filter = "Excel文檔(*.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("文件保留掉敗,文件名不克不及為空!");
        return;
      }
      if (sfd.FileName != "")
      {
        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
        if (excelApp == null)
        {
          MessageBox.Show("沒法創立Excel對象,能夠您的機械未裝置Excel");
          return;
        }
        else
        {
          MessageUtil.ShowThreadMessage("正在導出數據,請稍候...");
          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);
          //釋放資本
          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;
          //應用渣滓收受接管可以封閉EXCEL.EXE過程
          GC.Collect();
          DateTime end = DateTime.Now;
          int iTimeSpan = (end.Minute - start.Minute) * 60 + (end.Second - start.Second);
          MessageUtil.ShowMessage("數據導出終了,用時" + iTimeSpan.ToString() + "秒");
        }
      }
    }
    /// <summary>
/// 將數據集存儲為Excel文件。
/// </summary>
/// <param name="p_ds">要導出的數據集。</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("沒有可保留的數據");
        return;
      }
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請選擇文件寄存途徑";
      sfd.FileName = "導出數據";
      sfd.Filter = "Excel文檔(*.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("文件保留掉敗,文件名不克不及為空!");
        return;
      }
      if (sfd.FileName != "")
      {
        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
        if (excelApp == null)
        {
          MessageBox.Show("沒法創立Excel對象,能夠您的機械未裝置Excel");
          return;
        }
        else
        {
          MessageUtil.ShowThreadMessage("正在導出數據,請稍候...");
          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);
          //釋放資本
          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("數據導出終了,用時" + (iTimeSapn / 60).ToString() + "分" + (iTimeSapn % 60).ToString() + "秒");
        }
      }
    }
  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved