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;
101 object nothing = System.Reflection.Missing.Value;
102 doc = word.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);
103 doc.Paragraphs.Last.Range.Text = strtext.ToString();
104 object myfileName = FileName;
105 //将WordDoc文档对象的内容保存为doc文档
106 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);
107 //关闭WordDoc文档对象
108 doc.Close(ref nothing, ref nothing, ref nothing);
109 //关闭WordApp组件对象
110 word.Quit(ref nothing, ref nothing, ref nothing);
111 GC.Collect();
112 DateTime end = DateTime.Now;
113 TimeSpan ts = end - start;
114 MessageUtil.ShowMessage("文件保存成功,用时" + ts.ToString());
115 }
116 catch (System.Exception ex)
117 {
118 MessageUtil.ShowError(ex.Message);
119 }
120 }
121 /// <summary>
122 /// 将字符串存储为txt文档格式的文件。
123 /// </summary>
124 /// <param name="strtext">要保存的字符串内容。</param>
125 private static void SaveAsTxtFile(object strtext)
126 {
127 SaveFileDialog sfd = new SaveFileDialog();
128 sfd.Title = "请选择文件存放路径";
129 sfd.FileName = "导出数据";
130 sfd.Filter = "文本文档(*.txt)|*.txt";
131 if (sfd.ShowDialog() != DialogResult.OK)
132 {
133 return;
134 }
135 string FileName = sfd.FileName.ToLower();
136 if (!FileName.Contains(".txt"))
137 {
138 FileName += ".txt";
139 }
140 if (FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length <= 5)
141 {
142 MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!");
143 return;
144 }
145 try
146 {
147 DateTime start = DateTime.Now;
148 StreamWriter sw = new StreamWriter(FileName, false);
149 sw.Write(strtext.ToString());
150 sw.Flush();
151 sw.Close();
152 DateTime end = DateTime.Now;
153 TimeSpan ts = end - start;
154 MessageUtil.ShowMessage("文件保存成功,用时" + ts.ToString());
155 }
156 catch (Exception ex)
157 {
158 MessageUtil.ShowError(ex.Message);
159 }
160 }
161 /// <summary>
162 /// 将数据存储为Excel文件。
163 /// </summary>
164 /// <param name="p_dt">要保存的数据表。</param>
165 private static void SaveAsExcelTableFile(object p_dt)
166 {
167 System.Data.DataTable dt = (System.Data.DataTable)p_dt;
168 if (dt.Rows.Count == 0)
169 {
170 MessageUtil.ShowError("没有可保存的数据");
171 return;
172 }
173 SaveFileDialog sfd = new SaveFileDialog();
174 sfd.Title = "请选择文件存放路径";
175 sfd.FileName = "导出数据";
176 sfd.Filter = "Excel文档(*.xls)|*.xls";
177 if (sfd.ShowDialog() != DialogResult.OK)
178 {
179 return;
180 }
181 string FileName = sfd.FileName.ToLower();
182 if (!FileName.Contains(".xls"))
183 {
184 FileName += ".xls";
185 }
186 if (FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length <= 5)
187 {
188 MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!");
189 return;
190 }
191 if (sfd.FileName != "")
192 {
193 Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
194 if (excelApp == null)
195 {
196 MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
197 return;
198 }
199 else
200 {
201 MessageUtil.ShowThreadMessage("正在导出数据,请稍候...");
202 DateTime start = DateTime.Now;
203 Microsoft.Office.Interop.Excel.Workbooks workbooks = excelApp.Workbooks;
204 Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
205 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
206
207 for (int col = 1; col <= dt.Columns.Count; col++)
208 {
209 worksheet.Cells[1, col] = dt.Columns[col - 1].Caption.ToString();
210 }
211 for (int i = 0; i < dt.Rows.Count; i++)
212 {
213 for (int j = 0; j < dt.Columns.Count; j++)
214 {
215 worksheet.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
216 }
217 }
218 workbook.Saved = true;
219 workbook.SaveCopyAs(sfd.FileName);
220 //释放资源
221 System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
222 worksheet = null;
223 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
224 workbook = null;
225 workbooks.Close();
226 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
227 workbooks = null;
228 excelApp.Quit();
229 System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
230 excelApp = null;
231 //使用垃圾回收可以关闭EXCEL.EXE进程
232 GC.Collect();
233 DateTime end = DateTime.Now;
234 int iTimeSpan = (end.Minute - start.Minute) * 60 + (end.Second - start.Second);
235 MessageUtil.ShowMessage("数据导出完毕,用时" + iTimeSpan.ToString() + "");
236 }
237 }
238 }
239 /// <summary>
240 /// 将数据集存储为Excel文件。
241 /// </summary>
242 /// <param name="p_ds">要导出的数据集。</param>
243 private static void SaveAsExcelSetFile(object p_ds)
244 {
245 System.Data.DataSet ds = (System.Data.DataSet)p_ds;
246 if (ds == null || ds.Tables.Count == 0)
247 {
248 MessageUtil.ShowError("没有可保存的数据");
249 return;
250 }
251 SaveFileDialog sfd = new SaveFileDialog();
252 sfd.Title = "请选择文件存放路径";
253 sfd.FileName = "导出数据";
254 sfd.Filter = "Excel文档(*.xls)|*.xls";
255 if (sfd.ShowDialog() != DialogResult.OK)
256 {
257 return;
258 }
259 string FileName = sfd.FileName.ToLower();
260 if (!FileName.Contains(".xls"))
261 {
262 FileName += ".xls";
263 }
264 if (FileName.Substring(FileName.LastIndexOf(Path.DirectorySeparatorChar)).Length <= 5)
265 {
266 MessageUtil.ShowThreadMessage("文件保存失败,文件名不能为空!");
267 return;
268 }
269 if (sfd.FileName != "")
270 {
271 Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
272 if (excelApp == null)
273 {
274 MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
275 return;
276 }
277 else
278 {
279 MessageUtil.ShowThreadMessage("正在导出数据,请稍候...");
280 DateTime start = DateTime.Now;
281 Microsoft.Office.Interop.Excel.Workbooks workbooks = excelApp.Workbooks;
282 Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
283 Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
284 object objMissing = System.Reflection.Missing.Value;
285 for (int m = 0; m < ds.Tables.Count; m++)
286 {
287 System.Data.DataTable dt = ds.Tables[m];
288 worksheet = (Worksheet)workbook.ActiveSheet;
289 worksheet.Name = dt.TableName;
290 for (int col = 1; col <= dt.Columns.Count; col++)
291 {
292 worksheet.Cells[1, col] = dt.Columns[col - 1].Caption.ToString();
293 }
294 for (int i = 1; i <= dt.Rows.Count; i++)
295 {
296 for (int j = 1; j <= dt.Columns.Count; j++)
297 {
298 worksheet.Cells[i + 1, j] = dt.Rows[i - 1][j - 1].ToString();
299 }
300 }
301 if (m < ds.Tables.Count - 1)
302 {
303 workbook.Sheets.Add(objMissing, objMissing, 1, XlSheetType.xlWorksheet);
304 }
305 }
306 workbook.Saved = true;
307 workbook.SaveCopyAs(sfd.FileName);
308 //释放资源
309 System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
310 worksheet = null;
311 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
312 workbook = null;
313 workbooks.Close();
314 System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
315 workbooks = null;
316 excelApp.Quit();
317 System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
318 excelApp = null;
319 GC.Collect();
320 DateTime end = DateTime.Now;
321 int iTimeSapn = (end.Minute - start.Minute) * 60 + (end.Second - start.Second);
322 MessageUtil.ShowMessage("数据导出完毕,用时" + (iTimeSapn / 60).ToString() + "" + (iTimeSapn % 60).ToString() + "");
323 }
324 }
325 }
326 }
327 }
posted @ 2011-12-18 20:32  MY依然  阅读(1774)  评论(1编辑  收藏  举报