欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

WinForm導(dǎo)出文件為Word、Excel、文本文件的方法

 更新時(shí)間:2015年03月06日 09:06:07   投稿:junjie  
這篇文章主要介紹了WinForm導(dǎo)出文件為Word、Excel、文本文件的方法,本文直接給出實(shí)現(xiàn)代碼,代碼中包含相應(yīng)注釋,需要的朋友可以參考下

好久沒有寫文章了,下面把自己最近程序中用到的一個(gè)小小的導(dǎo)出文件的方法給在家分享一下,歡迎大家來(lái)排磚,謝謝~不說(shuō)廢話了,直接上代碼:

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>
/// 將內(nèi)容導(dǎo)出為文件類。
/// </summary>
/// <remarks>
/// 作者:SunYujing
/// 日期:2011-12-18
/// </remarks>
  public class ExportFile
  {
    /// <summary>
/// 將字符串存儲(chǔ)為word文檔格式的文件的方法(多線程)。
/// </summary>
/// <param name="strText">要保存的字符串內(nèi)容。</param>
    public static void SaveAsWord(string p_str)
    {
      Thread thread = new Thread(SaveAsWordFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(p_str);
    }
    /// <summary>
/// 將字符串存儲(chǔ)為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>
/// 導(dǎo)出數(shù)據(jù)表數(shù)據(jù)到Excel(多線程)。
/// </summary>
    public static void SaveAsExcel(System.Data.DataTable dataTable)
    {
      if (dataTable == null)
      {
        MessageUtil.ShowError("請(qǐng)先指定要導(dǎo)出的數(shù)據(jù)表");
        return;
      }
      Thread thread = new Thread(SaveAsExcelTableFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(dataTable);
    }
    /// <summary>
/// 導(dǎo)出數(shù)據(jù)集數(shù)據(jù)到Excel(多線程)。
/// </summary>
    public static void SaveAsExcel(System.Data.DataSet dataSet)
    {
      if (dataSet == null)
      {
        MessageUtil.ShowError("請(qǐng)先指定要導(dǎo)出的數(shù)據(jù)集");
        return;
      }
      Thread thread = new Thread(SaveAsExcelSetFile);
      thread.SetApartmentState(ApartmentState.STA);
      thread.Start(dataSet);
    }
    /// <summary>
/// 將字符串存儲(chǔ)為word文檔格式的文件。
/// </summary>
/// <param name="strtext">要保存的字符串內(nèi)容。</param>
    private static void SaveAsWordFile(object strtext)
    {
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請(qǐng)選擇文件存放路徑";
      sfd.FileName = "導(dǎo)出數(shù)據(jù)";
      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("正在保存文件,請(qǐng)稍候...");
        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文檔對(duì)象的內(nèi)容保存為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);
        //關(guān)閉WordDoc文檔對(duì)象
        doc.Close(ref nothing, ref nothing, ref nothing);
        //關(guān)閉WordApp組件對(duì)象
        word.Quit(ref nothing, ref nothing, ref nothing);
        GC.Collect();
        DateTime end = DateTime.Now;
        TimeSpan ts = end - start;
        MessageUtil.ShowMessage("文件保存成功,用時(shí)" + ts.ToString());
      }
      catch (System.Exception ex)
      {
        MessageUtil.ShowError(ex.Message);
      }
    }
    /// <summary>
/// 將字符串存儲(chǔ)為txt文檔格式的文件。
/// </summary>
/// <param name="strtext">要保存的字符串內(nèi)容。</param>
    private static void SaveAsTxtFile(object strtext)
    {
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請(qǐng)選擇文件存放路徑";
      sfd.FileName = "導(dǎo)出數(shù)據(jù)";
      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("文件保存成功,用時(shí)" + ts.ToString());
      }
      catch (Exception ex)
      {
        MessageUtil.ShowError(ex.Message);
      }
    }
    /// <summary>
/// 將數(shù)據(jù)存儲(chǔ)為Excel文件。
/// </summary>
/// <param name="p_dt">要保存的數(shù)據(jù)表。</param>
    private static void SaveAsExcelTableFile(object p_dt)
    {
      System.Data.DataTable dt = (System.Data.DataTable)p_dt;
      if (dt.Rows.Count == 0)
      {
        MessageUtil.ShowError("沒有可保存的數(shù)據(jù)");
        return;
      }
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請(qǐng)選擇文件存放路徑";
      sfd.FileName = "導(dǎo)出數(shù)據(jù)";
      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("無(wú)法創(chuàng)建Excel對(duì)象,可能您的機(jī)器未安裝Excel");
          return;
        }
        else
        {
          MessageUtil.ShowThreadMessage("正在導(dǎo)出數(shù)據(jù),請(qǐng)稍候...");
          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;
          //使用垃圾回收可以關(guān)閉EXCEL.EXE進(jìn)程
          GC.Collect();
          DateTime end = DateTime.Now;
          int iTimeSpan = (end.Minute - start.Minute) * 60 + (end.Second - start.Second);
          MessageUtil.ShowMessage("數(shù)據(jù)導(dǎo)出完畢,用時(shí)" + iTimeSpan.ToString() + "秒");
        }
      }
    }
    /// <summary>
/// 將數(shù)據(jù)集存儲(chǔ)為Excel文件。
/// </summary>
/// <param name="p_ds">要導(dǎo)出的數(shù)據(jù)集。</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("沒有可保存的數(shù)據(jù)");
        return;
      }
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.Title = "請(qǐng)選擇文件存放路徑";
      sfd.FileName = "導(dǎo)出數(shù)據(jù)";
      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("無(wú)法創(chuàng)建Excel對(duì)象,可能您的機(jī)器未安裝Excel");
          return;
        }
        else
        {
          MessageUtil.ShowThreadMessage("正在導(dǎo)出數(shù)據(jù),請(qǐng)稍候...");
          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("數(shù)據(jù)導(dǎo)出完畢,用時(shí)" + (iTimeSapn / 60).ToString() + "分" + (iTimeSapn % 60).ToString() + "秒");
        }
      }
    }
  }
}

相關(guān)文章

最新評(píng)論