VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之WinForm导出文件为Word、Excel、文本文件的

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

好久没有写文章了,下面把自己最近程序中用到的一个小小的导出文件的方法给在家分享一下,欢迎大家来排砖,谢谢~不说废话了,直接上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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() + "秒");
        }
      }
    }
  }
}

相关教程