现在的位置: 首页C#>正文
asp.net从数据库导出数据到word、excel、txt文本文件
2009年03月13日 C# 暂无评论 ⁄ 被围观 阅读(2,393)+
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
using System;
using System.Data;
using System.Drawing;
using System.Data.SqlClient;
using Excel;
using Word;
using System.IO;
namespace Common
{
///
/// 把数据导入到.doc、.txt、.xls文件中
///
public class Export
{
private const string DATAWORDPATH = @"C:\\folder\\doc\\datadoc";
private const string IMAGEWORDPATH = @"C:\\folder\\doc\\imagedoc";
private const string IMAGEPATH = @"C:\\folder\\image";
private const string EXCELPATH = @"C:\\folder\\excel";
private const string TXTPATH = @"C:\\folder\\txt";
private const string IMAGEPOSTFIX = ".bmp";
private const string WORDPOSTFIX = ".doc";
private const string EXCELPOSTFIX = ".xls";
private const string TXTPOSTFIX = ".txt";
private const int DATADISTANCE = 5;
private const int TABDISTANCE = 8;

public Export()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
///
/// 获得数据集Dataset--------------------------------用于调试
///
/// Dataset
public DataSet GetData()
{
try
{
string sConnectionString;
sConnectionString = "workstation id=GUOFU;packet size=4096;user id=sa;data source=GUOFU;persist security info=True;initial catalog=YC;password=sc";
SqlConnection objConn = new SqlConnection(sConnectionString);
objConn.Open();
SqlDataAdapter daPoint = new SqlDataAdapter("Select * From Point", objConn);
DataSet dsYC = new DataSet("YC");
daPoint.FillSchema(dsYC,SchemaType.Mapped, "Point");
daPoint.Fill(dsYC,"Point");
daPoint = new SqlDataAdapter("Select * From Employee", objConn);
daPoint.FillSchema(dsYC,SchemaType.Mapped, "Employee");
daPoint.Fill(dsYC,"Employee");
return dsYC;
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}

}

///
/// 把数据文件导入到.xls文件
///
/// public void ExportToExcel(DataSet ds)
{

if(ds.Tables.Count!=0)
{
//生成.xls文件完整路径名
string tempFileName = GetTempFileName();
object filename = EXCELPATH+tempFileName+EXCELPOSTFIX;
object Nothing = System.Reflection.Missing.Value;

//创建excel文件,文件名用系统时间生成精确到毫秒
Excel.Application myExcel = new Excel.ApplicationClass();
myExcel.Application.Workbooks.Add(Nothing);

try
{
//把Dataset中的数据插入excel文件中
int totalCount = 0;
for(int k =0;k {
int row = ds.Tables[k].Rows.Count;
int column = ds.Tables[k].Columns.Count;

for(int i = 0;i
{
myExcel.Cells[totalCount+2,1+i] = ds.Tables[k].Columns[i].ColumnName;
}

for(int i = 0;i {
for(int j =0;j {
myExcel.Cells[totalCount+3+i,1+j] = "\'" + ds.Tables[k].Rows[i][j].ToString();
}
}
totalCount = totalCount + row +4;
}

try
{
//保存excel文件到指定的目录下,文件名用系统时间生成精确到毫秒
myExcel.ActiveWorkbook._SaveAs(filename,Nothing,Nothing,Nothing,Nothing,Nothing,XlSaveAsAccessMode.xlExclusive,Nothing,Nothing,Nothing,Nothing);
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+EXCELPATH+tempFileName+EXCELPOSTFIX);
return;
}
//让生成的excel文件可见
myExcel.Visible = true;
}
catch(Exception e)
{
System.Windows.Forms.MessageBox.Show("向excel文件中写入数据出错: " + e.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show("No Data");
}
}

///
/// 把数据导入到.doc文件
///
/// public void ExportToWord(DataSet ds)
{
if(ds.Tables.Count!=0)
{
string tempFileName = null;
object filename = null;

object tableBehavior = Word.WdDefaultTableBehavior.wdWord9TableBehavior;
object autoFitBehavior = Word.WdAutoFitBehavior.wdAutoFitFixed;

object unit = Word.WdUnits.wdStory;
object extend = System.Reflection.Missing.Value;
object breakType = (int)Word.WdBreakType.wdSectionBreakNextPage;

object count = 1;
object character = Word.WdUnits.wdCharacter;

object Nothing = System.Reflection.Missing.Value;

try
{
tempFileName = GetTempFileName();

//生成.doc文件完整路径名
filename = DATAWORDPATH+tempFileName+WORDPOSTFIX;

//创建一个word文件,文件名用系统时间生成精确到毫秒
Word.Application myWord= new Word.ApplicationClass();
Word._Document myDoc = new Word.DocumentClass();
myDoc = myWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
myDoc.Activate();

//向把dataset中的表插入到word的文件中

for(int totalTable = 0;totalTable {
myWord.Application.Selection.TypeText(ds.Tables[totalTable].TableName+"表的数据如下");
myWord.Application.Selection.TypeParagraph();
myWord.Application.Selection.TypeParagraph();
Word.Range para = myWord.Application.Selection.Range;
myDoc.Tables.Add(para,ds.Tables[totalTable].Rows.Count+1,ds.Tables[totalTable].Columns.Count,ref tableBehavior,ref autoFitBehavior);
for(int column = 0; column {
myDoc.Tables.Item(totalTable+1).Cell(1,column+1).Range.InsertBefore(ds.Tables[0].Columns[column].ColumnName.Trim());
}
for(int row = 0;row {
for(int column = 0;column {
myDoc.Tables.Item(totalTable+1).Cell(row+2,column+1).Range.InsertBefore(ds.Tables[totalTable].Rows[row][column].ToString().Trim());
}
}
myWord.Application.Selection.EndKey(ref unit,ref extend);
myWord.Application.Selection.TypeParagraph();
myWord.Application.Selection.TypeParagraph();
myWord.Application.Selection.InsertBreak(ref breakType);
}
myWord.Application.Selection.TypeBackspace();
myWord.Application.Selection.Delete(ref character,ref count);
myWord.Application.Selection.HomeKey(ref unit,ref extend);

//保存word文件到指定的目录下
try
{
myDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
myWord.Visible = true;
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+DATAWORDPATH+tempFileName+WORDPOSTFIX);
return;
}
//让生成的excel文件可见
myWord.Visible = true;
}
catch(Exception ex)
{
System.Windows.Forms.MessageBox.Show("向word文件中写入数据出错: " + ex.Message);
}
}
else
{
System.Windows.Forms.MessageBox.Show("No Data");
}
}
///
/// 把图片文件导入到.doc文件
///
/// public void ExportToWord(Bitmap bp)
{
string tempFileName = null;
string bmpPath = null;
object filename = null;
object Nothing = null;
tempFileName = GetTempFileName();

//生成.bmp文件完整路径名
bmpPath = IMAGEPATH+tempFileName+IMAGEPOSTFIX;

//生成.doc文件完整路径名
filename = IMAGEWORDPATH+tempFileName+WORDPOSTFIX;
Nothing = System.Reflection.Missing.Value;

//创建一个word文件,文件名用系统时间生成精确到毫秒
Word.Application myWord= new Word.ApplicationClass();
Word._Document myDoc = new Word.DocumentClass();
myDoc = myWord.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);

try
{
//把bitmap对象保存到系统所生成文件完整路径中
bp.Save(bmpPath);
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+bmpPath);
return;
}

try
{
//往word文件中插入图片
myDoc.InlineShapes.AddPicture(bmpPath,ref Nothing,ref Nothing,ref Nothing);
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+bmpPath);
return;
}

try
{
//保存word文件到指定的目录下
myDoc.SaveAs(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+IMAGEWORDPATH+tempFileName+WORDPOSTFIX);
return;
}
//让生成的word文件可见
myWord.Visible = true;
}

///
/// 把数据文件导入到.txt文件
///
/// public void ExportToTxt(DataSet ds)
{

if(ds.Tables.Count!=0)
{
string tempFileName = null;
tempFileName = GetTempFileName();

//创建一个.txt文件,文件名用系统时间生成精确到毫秒
FileInfo file = new FileInfo(TXTPATH+tempFileName+TXTPOSTFIX);
StreamWriter textFile = null;
try
{
textFile = file.CreateText();
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+TXTPATH+tempFileName+TXTPOSTFIX);
return;
}

//把Dataset中的数据写入.txt文件中
for(int totaltable = 0;totaltable {
//统计dataset中当前表的行数
int row = ds.Tables[totaltable].Rows.Count;

//统计dataset中当前表的列数
int column = ds.Tables[totaltable].Columns.Count;

//用于统计当前表中每列记录中字符数最长的字符串的长度之和
int totalLength = 0;

//用于统计标题的长度(dataset中的表名的length+"表的数据如下"的length)
int titleLength = 0;

//统计每列记录中字符数最长的字符串的长度
int[] columnLength = new int[column];
for(int i = 0;i
{
columnLength[i] = ds.Tables[totaltable].Columns[i].ColumnName.ToString().Length;
}
for(int i = 0;i {
for(int j = 0;j {
if(ds.Tables[totaltable].Rows[i][j].ToString().Length>columnLength[j])
{
columnLength[j]=ds.Tables[totaltable].Rows[i][j].ToString().Length;
}
}
}

//统计当前表中每列记录中字符数最长的字符串的长度之和
for(int i = 0;i
{
totalLength = totalLength+columnLength[i]+DATADISTANCE;
}
totalLength = totalLength+2*TABDISTANCE-DATADISTANCE;

//统计标题的长度(dataset中的当前表名的length+"表的数据如下"的length)
titleLength = ds.Tables[totaltable].TableName.ToString().Length+"表的数据如下".Length*2;

//把标题写入.txt文件中
for(int i = 0;i<(int)((totalLength-titleLength)/2);i++)
{
textFile.Write(\' \');
}
textFile.Write(ds.Tables[totaltable].TableName+"表的数据如下");
textFile.WriteLine();
for(int i = 0;i {
textFile.Write(\'*\');
}
textFile.WriteLine();
textFile.Write("\\t");
//把dataset中当前表的字段名写入.txt文件中
for(int i = 0;i {
textFile.Write(ds.Tables[totaltable].Columns[i].ColumnName.ToString());
for(int k = 0;k {
textFile.Write(\' \');
}
}
textFile.WriteLine();
for(int i = 0;i {
textFile.Write(\'-\');
}
textFile.WriteLine();
textFile.Write("\\t");

//把dataset中当前表的数据写入.txt文件中
for(int i = 0;i {
for(int j = 0;j {
textFile.Write(ds.Tables[totaltable].Rows[i][j].ToString());
for(int k = 0;k {
textFile.Write(\' \');
}
}
textFile.WriteLine();
textFile.Write("\\t");
}
textFile.WriteLine();
for(int i = 0;i {
textFile.Write(\'-\');
}
textFile.WriteLine();
textFile.WriteLine();
textFile.WriteLine();
}

//关闭当前的StreamWriter流
textFile.Close();
System.Windows.Forms.MessageBox.Show("数据文件已保存到"+" "+file.FullName);
}
else
{
System.Windows.Forms.MessageBox.Show("No Data");
}
}

public string GetTempFileName()
{
return DateTime.Now.ToString("yyyyMMddhhmmssfff");
}
}
}

补充:使用以上方法必须对dcom进行配置,给用户使用office的权限。
具体配置方法如下:
1:在服务器上安装office的Excel软件.
2:在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"
3:依次双击"组件服务"->"计算机"->"我的电脑"->"DCOM配置"
4:在"DCOM配置"中找到"Microsoft Excel 应用程序",在它上面点击右键,然后点击"属性",弹出"Microsoft Excel 应用程序属性"对话框
5:点击"标识"标签,选择"交互式用户"
6:点击"安全"标签,在"启动和激活权限"上点击"自定义",然后点击对应的"编辑"按钮,在弹出的"安全性"对话框中填加一个"NETWORK SERVICE"用户(注意要选择本计算机名),并给它赋予"本地启动"和"本地激活"权限.
7:依然是"安全"标签,在"访问权限"上点击"自定义",然后点击"编辑",在弹出的"安全性"对话框中也填加一个"NETWORK SERVICE"用户,然后赋予"本地访问"权限.
这样,我们便配置好了相应的Excel的DCOM权限.
注意:我是在WIN2003上配置的,在2000上,是配置ASPNET用户

若不进行配置会出现错误
检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。
原因是用户没有使用Excel的权限。
导出到word同样要配置使用word的权限。
继续补充: 导出到txt我用了上面的方法有问题,

1
2
3
4
5
6
7
8
9
try
{
textFile = file.CreateText();
}
catch
{
System.Windows.Forms.MessageBox.Show("系统找不到指定目录下的文件: "+TXTPATH+tempFileName+TXTPOSTFIX);
return;
}

总是在这里跳到catch里面。导出到word,excel都能用,继续研究txt的使用方法。

给我留言

留言无头像?


[face=9] [face=8] [face=7] [face=6] [face=5] [face=4] [face=3] [face=30] [face=2] [face=29] [face=28] [face=27] [face=26] [face=25] [face=24] [face=23] [face=22] [face=21] [face=20] [face=1] [face=19] [face=18] [face=17] [face=16] [face=15] [face=14] [face=13] [face=12] [face=11] [face=10] [em=9] [em=8] [em=7] [em=6] [em=5] [em=4] [em=3] [em=30] [em=2] [em=29] [em=28] [em=27] [em=26] [em=25] [em=24] [em=23] [em=22] [em=21] [em=20] [em=1] [em=19] [em=18] [em=17] [em=16] [em=15] [em=14] [em=13] [em=12] [em=11] [em=10] ;) :| :x :twisted: :roll: :oops: :o :mrgreen: :lol: :idea: :evil: :cry: :arrow: :P :D :?: :? :) :( :!: 8O 8)