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 }
WinForm导出文件的更多相关文章
- winform导入导出excel,后台动态添加控件
思路: 导入: 1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();) 2, 获取用户选择文件的后缀名(s ...
- C# Winform 通过FlowLayoutPanel及自定义的编辑控件,实现快速构建C/S版的编辑表单页面
个人理解,开发应用程序的目的,不论是B/S或是C/S结构类型,无非就是实现可供用户进行查.增.改.删,其中查询用到最多,开发设计的场景也最为复杂,包括但不限于:表格记录查询.报表查询.导出文件查询等等 ...
- Winform 通过FlowLayoutPanel及自定义的编辑控件,实现快速构建C/S版的编辑表单页面 z
http://www.cnblogs.com/zuowj/p/4504130.html 不论是B/S或是C/S结构类型,无非就是实现可供用户进行查.增.改.删,其中查询用到最多,开发设计的场景 也最为 ...
- C# winform 导出导入Excel/Doc 完整实例教程[网上看到的]
还真没做过winform的导出导入,今天上网百度了一下.结果--- 所以还是我自己写个吧.之前做过web的,半搬半做就OK. 1添加引用:Aspose.Cells.dll(我们就叫工具包吧,可以从网上 ...
- Winform开发的应用环境和相关技术介绍
随着时间的推移,Winform也算是能够坚持下来最久的技术之一了,它的昔日辉煌和现今的依旧活跃,导致了它依旧拥有者很庞大的用户群体,虽然目前很多技术日新月异的,曾经的ASP.ASP.NET WebFo ...
- C#+Aspose.Cells 导出Excel及设置样式 (Webform/Winform)
在项目中用到,特此记录下来,Aspose.Cells 不依赖机器装没有装EXCEL都可以导出,很方便.具体可以参考其他 http://www.aspose.com/docs/display/cells ...
- Oracle 11g导出来的dmp导入到 10g的数据库(IMP-00010:不是有效的导出文件,头部验证失败)
原文地址:http://www.cnblogs.com/alxc/archive/2011/03/25/1995279.html 因为喜欢新的东西,所以基本上电脑的开发工具都是最新的,oracle也装 ...
- Winform入门见解
winform算是C#比较快速的入门的一个了,简单的控件拖拽然后写上每个控件对应的事件.然后就可以了.需要美观的点 可以用Skin皮肤就完成了.我们先不说复杂的,就来个普通的三层架构来增删改查 分页和 ...
- ABP开发框架前后端开发系列---(14)基于Winform的ABP快速开发框架
前面介绍了很多ABP系列的文章,一步一步的把我们日常开发中涉及到的Web API服务构建.登录日志和操作审计日志.字典管理模块.省份城市的信息维护.权限管理模块中的组织机构.用户.角色.权限.菜单等内 ...
随机推荐
- shiro实现登录安全认证(转)
shiro实现登录安全认证 shiro的优势,不需要再代码里面判断是否登录,是否有执行的权限,实现了从前端页面到后台代码的权限的控制非常的灵活方便 传统的登录认证方式是,从前端页面获取到用户输入的账号 ...
- [RxJS] Implement pause and resume feature correctly through RxJS
Eventually you will feel the need for pausing the observation of an Observable and resuming it later ...
- URL validation failed. The error could have been caused through the use of the browser's navigation
URL validation failed. The error could have been caused through the use of the browser's navigation ...
- 自定义view组件 分类: H1_ANDROID 2013-10-26 21:55 741人阅读 评论(0) 收藏
参考<疯狂android讲义>第2版 2.1节P48,对应CustomViewDemo.zip. 若在开发过程中,发现现有的view均不能满足需要,可以自定义一个view. 自定义一个vi ...
- js进阶 11-20 弹出层如何制作
js进阶 11-20 弹出层如何制作 一.总结 一句话总结:其实就是一个div,控制显示和隐藏即可.设置成绝对定位更好,就可以控制弹出层出现的位置.关闭的画质需要将display重新设置为none就好 ...
- 【C++竞赛 H】The sum problem
Time Limit: 1s Memory Limit: 32MB 问题描述 Given a sequence 1,2,3,-,N, your job is to calculate the numb ...
- PatentTips - 在物联网中进行数据过滤的方法和装置
背景技术 [0001] 本发明涉及物联网,特别涉及在物联网进行数据过滤的方法和装置. [0002] 物联网是新一代信息技术的重要组成部分,特指物物相连的网络.具体地,物联网是指通过各种信息传感设备,如 ...
- 利用Powershell获取公司内部机器的资源信息,作为企业兴许资产管理的基本途径!
今天一个哥们问我是否用Powershell 实现.我好久没有写脚本,脚本的协作和调试还是费了一些时间,兴许调试了下.运作没有问题,大家能够參考以下的脚本来丰富您企业须要做的一些事情,脚本代码例如以下: ...
- Tricks(四十九)—— 按 batch 访问越界的解决办法
使用 min 函数指定访问的最终位置,本质上是增加一个条件判断: done = false; batch_size = 10000; idx = 1; while ~done idx_end = mi ...
- MethodInterceptor拦截器
http://blog.csdn.net/heirenheiren/article/details/39030767