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 }

WinForm导出文件的更多相关文章

  1. winform导入导出excel,后台动态添加控件

    思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...

  2. C# Winform 通过FlowLayoutPanel及自定义的编辑控件,实现快速构建C/S版的编辑表单页面

    个人理解,开发应用程序的目的,不论是B/S或是C/S结构类型,无非就是实现可供用户进行查.增.改.删,其中查询用到最多,开发设计的场景也最为复杂,包括但不限于:表格记录查询.报表查询.导出文件查询等等 ...

  3. Winform 通过FlowLayoutPanel及自定义的编辑控件,实现快速构建C/S版的编辑表单页面 z

    http://www.cnblogs.com/zuowj/p/4504130.html 不论是B/S或是C/S结构类型,无非就是实现可供用户进行查.增.改.删,其中查询用到最多,开发设计的场景 也最为 ...

  4. C# winform 导出导入Excel/Doc 完整实例教程[网上看到的]

    还真没做过winform的导出导入,今天上网百度了一下.结果--- 所以还是我自己写个吧.之前做过web的,半搬半做就OK. 1添加引用:Aspose.Cells.dll(我们就叫工具包吧,可以从网上 ...

  5. Winform开发的应用环境和相关技术介绍

    随着时间的推移,Winform也算是能够坚持下来最久的技术之一了,它的昔日辉煌和现今的依旧活跃,导致了它依旧拥有者很庞大的用户群体,虽然目前很多技术日新月异的,曾经的ASP.ASP.NET WebFo ...

  6. C#+Aspose.Cells 导出Excel及设置样式 (Webform/Winform)

    在项目中用到,特此记录下来,Aspose.Cells 不依赖机器装没有装EXCEL都可以导出,很方便.具体可以参考其他 http://www.aspose.com/docs/display/cells ...

  7. Oracle 11g导出来的dmp导入到 10g的数据库(IMP-00010:不是有效的导出文件,头部验证失败)

    原文地址:http://www.cnblogs.com/alxc/archive/2011/03/25/1995279.html 因为喜欢新的东西,所以基本上电脑的开发工具都是最新的,oracle也装 ...

  8. Winform入门见解

    winform算是C#比较快速的入门的一个了,简单的控件拖拽然后写上每个控件对应的事件.然后就可以了.需要美观的点 可以用Skin皮肤就完成了.我们先不说复杂的,就来个普通的三层架构来增删改查 分页和 ...

  9. ABP开发框架前后端开发系列---(14)基于Winform的ABP快速开发框架

    前面介绍了很多ABP系列的文章,一步一步的把我们日常开发中涉及到的Web API服务构建.登录日志和操作审计日志.字典管理模块.省份城市的信息维护.权限管理模块中的组织机构.用户.角色.权限.菜单等内 ...

随机推荐

  1. [PReact] Use Link State to Automatically Handle State Changes

    Storing and updating values inside a component’s local state (known as controlled components) is suc ...

  2. linux下的打包和压缩

    linux中常见的两种压缩包文件的格式是.tar..gz和.tar.gz..tar仅仅是将文件简单地打包,文件的大小没有变化,也就是说.tar文件仅仅是一个包,没有被压缩:.tar.gz文件是打包后用 ...

  3. sequence配置

    在实现分库分表的情况下,数据库自增主键已经无法保证在集群中是全局唯一的主键了,因此mycat提供了全局的sequence,并且提供了本地配置.数据库配置等多种实现方式. 本地文件方式 采用该方式,my ...

  4. js导出报表

    原文链接:https://blog.csdn.net/qq_37936542/article/details/78376156 需求:项目中有一个学生签到模块需要导出每天的签到数据,一开始用poi在后 ...

  5. XxPay支付系统-boot版本了解一下

    了解一下 之前看了龙果支付系统,也没看透,用公司框架改写,然后就改的比较乱

  6. form表单上传附件的几种方法

    问题描述:在网页开发过程中,当需要上传附件(图片,音频,视频等)时,常规方法是使用form表单进行提交,这里总结一下form表单提交的几种方法. 参考地址:http://www.cnblogs.com ...

  7. Android 5.0中使用JobScheduler

    在这篇文章中,你会学习到在Android 5.0中怎样使用JobScheduler API. JobScheduler API同意开发人员在符合某些条件时创建运行在后台的任务. 介绍 在Android ...

  8. 授人玫瑰 手留余香 --纪念python3.2.3官方文档翻译结束

    当你点击看到这篇文章的时候.你已经得到了祝福. 一个来自夜深人静的码农,在2014年5月19号的01:18分.默默为你献上祝福. 希望你.我和他,每个在IT行业中奋斗的人.能找到属于自己一片天空. 在 ...

  9. 学汇编的时候可以拿IDA之类的反汇编工具辅助学习,再用gdb或者IDA动态调试,跟踪每条指令的 执行结果。都不难

    作者:潘安仁链接:https://www.zhihu.com/question/40720890/answer/87926792来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明 ...

  10. PHP移动互联网开发笔记(5)——基础函数库

    一.数学函数库 ● floor 舍一取整(向下取整) float floor (float $value); <?php echo(floor(0.60)."<br>&qu ...