首页 > 代码库 > WinForm导出文件
WinForm导出文件
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Windows.Forms;
6 using System.Threading;
7 using Microsoft.Office.Interop.Word;
8 using System.IO;
9 using Microsoft.Office.Interop.Excel;
10 using Sun.Winform.Util;
11
12 namespace Sun.Winform.Files
13 {
14 /// <summary>
15 /// 将内容导出为文件类。
16 /// </summary>
17 /// <remarks>
18 /// 作者:SunYujing
19 /// 日期:2011-12-18
20 /// </remarks>
21 public class ExportFile
22 {
23 /// <summary>
24 /// 将字符串存储为word文档格式的文件的方法(多线程)。
25 /// </summary>
26 /// <param name="strText">要保存的字符串内容。</param>
27 public static void SaveAsWord(string p_str)
28 {
29 Thread thread = new Thread(SaveAsWordFile);
30 thread.SetApartmentState(ApartmentState.STA);
31 thread.Start(p_str);
32 }
33 /// <summary>
34 /// 将字符串存储为txt格式的文件的方法(多线程)。
35 /// </summary>
36 /// <param name="p_str"></param>
37 public static void SaveAsTxt(string p_str)
38 {
39 Thread thread = new Thread(SaveAsTxtFile);
40 thread.SetApartmentState(ApartmentState.STA);
41 thread.Start(p_str);
42 }
43 /// <summary>
44 /// 导出数据表数据到Excel(多线程)。
45 /// </summary>
46 public static void SaveAsExcel(System.Data.DataTable dataTable)
47 {
48 if (dataTable == null)
49 {
50 MessageUtil.ShowError("请先指定要导出的数据表");
51 return;
52 }
53 Thread thread = new Thread(SaveAsExcelTableFile);
54 thread.SetApartmentState(ApartmentState.STA);
55 thread.Start(dataTable);
56 }
57 /// <summary>
58 /// 导出数据集数据到Excel(多线程)。
59 /// </summary>
60 public static void SaveAsExcel(System.Data.DataSet dataSet)
61 {
62 if (dataSet == null)
63 {
64 MessageUtil.ShowError("请先指定要导出的数据集");
65 return;
66 }
67 Thread thread = new Thread(SaveAsExcelSetFile);
68 thread.SetApartmentState(ApartmentState.STA);
69 thread.Start(dataSet);
70 }
71 /// <summary>
72 /// 将字符串存储为word文档格式的文件。
73 /// </summary>
74 /// <param name="strtext">要保存的字符串内容。</param>
75 private static void SaveAsWordFile(object strtext)
76 {
77 SaveFileDialog sfd = new SaveFileDialog();
78 sfd.Title = "请选择文件存放路径";
79 sfd.FileName = "导出数据";
80 sfd.Filter = "Word文档(*.doc)|*.doc";
81 if (sfd.ShowDialog() != DialogResult.OK)
82 {
83 return;
84 }
85 string FileName = sfd.FileName.ToLower();
86 if (!FileName.Contains(".doc"))
87 {
88 FileName += ".doc";
89 }
90 if (FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length <= 5)
91 {
92 MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!");
93 return;
94 }
95 try
96 {
97 DateTime start = DateTime.Now;
98 MessageUtil.ShowThreadMessage("正在保存文件,请稍候...");
99 Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
100 Microsoft.Office.Interop.Word._Document doc;