ExportData.cs
13 KB
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
using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
namespace ExcelHelper
{
public class ExportData
{
static StreamWriter writer = null;
/// <summary>
/// 导入记事本
/// </summary>
/// <param name="lv">ListView</param>
public static void SaveToNotePad(ListView lv)
{
#region
FileStream outputfile = null; // 写文件
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.DefaultExt = "xls";
saveDlg.Filter = "文本文件(*.txt)|*.txt|文本文件(*.ini)|*.ini|所有文件(*.*)|*.*";
saveDlg.Title = "文件另存为";
try
{
if (saveDlg.ShowDialog() == DialogResult.OK)
{
outputfile = new FileStream(saveDlg.FileName, FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(outputfile);
writer.BaseStream.Seek(0, SeekOrigin.End);
for (int i = 0; i < lv.Items.Count; i++)
{
DoWrite(lv.Columns[0].Text + ":" + lv.Items[i].Text);
for (int j = 1; j < lv.Columns.Count; j++)
{
DoWrite(lv.Columns[j].Text + ":" + lv.Items[i].SubItems[j].Text);
}
DoWrite("--------");
}
writer.Close();
MessageBox.Show("已将数据成功导入记事本:" + saveDlg.FileName + " 中!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
outputfile = null;
writer = null;
saveDlg.Dispose();
}
#endregion
}
/// <summary>
/// 导入记事本
/// </summary>
/// <param name="dv">DataGridView</param>
public static void SaveToNotePad(DataGridView dv)
{
#region
//if (File.Exists(filepath))
//{
// Response.Write("<script>(confirm('文件存在!是不是要替换?');</script>");
//}
FileStream outputfile = null; // 写文件
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.DefaultExt = "xls";
saveDlg.Filter = "文本文件(*.txt)|*.txt|文本文件(*.ini)|*.ini|所有文件(*.*)|*.*";
saveDlg.Title = "文件另存为";
try
{
if (saveDlg.ShowDialog() == DialogResult.OK)
{
if (File.Exists(saveDlg.FileName)) File.Delete(saveDlg.FileName);
outputfile = new FileStream(saveDlg.FileName, FileMode.Create, FileAccess.Write);//OpenOrCreate
writer = new StreamWriter(outputfile);
writer.BaseStream.Seek(0, SeekOrigin.End);
for (int i = 0; i < dv.RowCount; i++)
{
for (int j = 0; j < dv.Columns.Count; j++)
{
DoWrite(dv.Columns[j].Name.ToString() + ":" + dv.Rows[i].Cells[j].Value.ToString());
}
DoWrite("--------");
}
writer.Close();
MessageBox.Show("已将数据成功导入记事本:" + saveDlg.FileName + " 中!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
outputfile = null;
writer = null;
saveDlg.Dispose();
}
#endregion
}
/// <summary>
/// 11.5,Writed by Fufu
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static bool SaveToTxt(string text)
{
FileStream outputfile = null; // 写文件
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.DefaultExt = "xls";
saveDlg.Filter = "文本文件(*.txt)|*.txt|文本文件(*.ini)|*.ini|所有文件(*.*)|*.*";
saveDlg.Title = "文件另存为";
try
{
if (saveDlg.ShowDialog() == DialogResult.OK)
{
if (File.Exists(saveDlg.FileName)) File.Delete(saveDlg.FileName);
outputfile = new FileStream(saveDlg.FileName, FileMode.Create, FileAccess.Write);//OpenOrCreate
writer = new StreamWriter(outputfile);
writer.BaseStream.Seek(0, SeekOrigin.End);
writer.Write(text);
writer.Close();
//MessageBox.Show("已将数据成功导入记事本:" + saveDlg.FileName + " 中!");
return true;
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
outputfile = null;
writer = null;
saveDlg.Dispose();
return false;
}
return false;
}
public static void DoWrite(String line)
{
line += "\r\n"; // 加上换行符
byte[] binfo = new System.Text.UTF8Encoding(true).GetBytes(line);
char[] info = new System.Text.UTF8Encoding(true).GetChars(binfo);
writer.Write(info, 0, info.Length);//writer.WriteLine(line);
writer.Flush();
}
/// <summary>
/// 以操作Excel控件的方式将DataGridView数据导出到Excel add by sunny 2007/1/18
/// </summary >
/// <param name= "GridView " >DataGridView对象 </param >
/// <param name= "strExcelFile " >Excel文件名 </param >
/// <param name= "strError " >out参数,返回出错信息 </param >
/// <returns >
/// -1 出错
/// 0 成功
/// </returns >
public static int DataGridViewToExcel(System.Windows.Forms.DataGridView GridView)
{
#region
int nRet = 0;
SaveFileDialog saveDlg1 = new SaveFileDialog();
saveDlg1.DefaultExt = "xls";
saveDlg1.Filter = "Microsoft Office Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
saveDlg1.Title = "文件另存为";//saveDlg1.FileName
//saveDlg1.InitialDirectory = Directory.GetCurrentDirectory();
//if (saveDlg1.ShowDialog() == DialogResult.Cancel) return nRet;
if (saveDlg1.ShowDialog() == DialogResult.Cancel) return -1;
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks workbooks = xlApp.Workbooks;
Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
try
{
//~~
// 写字段名
for (int i = 0; i < GridView.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = GridView.Columns[i].HeaderText.ToString();
}
// 写记录
for (int i = 0; i < GridView.Rows.Count; i++)
{
for (int j = 0; j < GridView.Columns.Count; j++)
{
//Fu_我的很多dgv里面都是复杂类,无法用这条语句导出
//worksheet.Cells[i + 2, j + 1] = GridView.Rows[i].Cells[j].Value.ToString();
//Fu_11.5_重写,获取格式化后的值
//worksheet.Cells[i + 2, j + 1] = GridView.Rows[i].Cells[j].EditedFormattedValue == null ? "" : GridView.Rows[i].Cells[j].EditedFormattedValue.ToString();
string value = GridView.Rows[i].Cells[j].EditedFormattedValue == null ? "" : GridView.Rows[i].Cells[j].EditedFormattedValue.ToString();
if (value.Length > 11)
{
value = "'" + value;
}
worksheet.Cells[i + 2, j + 1] = value;
}
}
worksheet.Columns.EntireColumn.AutoFit();//自动适应每列的宽度 add by sunny.li
//下面这句会报错
//Excel.Range rg = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, GridView.Columns.Count]);
//Fu_csdn上的写法 , 膜拜大神...
Excel.Range rg = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, GridView.Columns.Count]];
rg.Font.Bold = true;
workbook.Saved = true;
workbook.SaveCopyAs(saveDlg1.FileName);
// 关掉内存中的进程
// xlApp.Quit();
nRet = 0;
}
catch (Exception ex)
{
//strError = ex.ToString();
//MessageBox.Show(ex.ToString());
nRet = -1;
}
return nRet;
#endregion
}
/// <summary>
/// 读取Excel文件,将内容存储在DataSet中
/// </summary>
/// <param name="opnFileName">带路径的Excel文件名</param>
/// <returns>DataSet</returns>
public static DataSet ExcelToDataSet(string TableName)
{
#region
string strExcel = "";
OpenFileDialog openDlg1 = new OpenFileDialog();
openDlg1.DefaultExt = "xls";
openDlg1.Filter = "Microsoft Office Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
openDlg1.Title = "打开";
//saveDlg1.InitialDirectory = Directory.GetCurrentDirectory();
if (openDlg1.ShowDialog() == DialogResult.Cancel) return null;
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + openDlg1.FileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter da = null;
DataSet ds = new DataSet();
strExcel = "select * from [sheet1$]";
//strExcel = string.Format("select * from [{0}$]", "sheet1");
try
{
da = new OleDbDataAdapter(strExcel, strConn);
da.Fill(ds, TableName);
//用bcp导入数据
//using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(Login.Cn()))
//{
// //bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
// bcp.BatchSize = 100;//每次传输的行数
// bcp.NotifyAfter = 100;//进度提示的行数
// bcp.DestinationTableName = TableName;//目标表
// bcp.WriteToServer(ds.Tables[0]);
//}
return ds;
}
catch (Exception ex)
{
MessageBox.Show("导入出错:" + ex, "错误信息");
return ds;
}
finally
{
conn.Close();
conn.Dispose();
}
#endregion
}
////进度显示
//void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
//{
// this.Text = e.RowsCopied.ToString();
// this.Update();
//}
/// <summary>
/// 直接导出Sql表数据到excel --用excel的QueryTable进行批量数据的导入代码
/// </summary>
/// <param name="connectionString">连接字符串</param>
/// <param name="sql">查询语句</param>
/// <param name="fileName">文件名</param>
/// <param name="sheetName">表名</param>
/// <returns>真假值</returns>
//public static bool SQLDataToExcel(string connectionString, string sql, string fileName, string sheetName)
//{
// #region
// //SQLDataToExcel("Provider=SQLOLEDB.1;sever=localhost;uid=sa;password=123;database=autowarehouse;",
// //"select * from tblmaterialno", @"c:\testOle.xls", "tblmaterialno");
// Excel.Application app = new Excel.ApplicationClass();
// Excel.Workbook wb = (Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
// Excel.Worksheet ws = wb.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;
// ws.Name = sheetName;
// try
// {
// Excel.QueryTable qt = ws.QueryTables.Add("OLEDB;" + connectionString,
// ws.get_Range("A1", Missing.Value), sql);
// qt.Refresh(false);//是否异步查询
// }
// catch (Exception ex)
// {
// string str = ex.Message;
// }
// finally
// {
// wb.Saved = true;
// wb.SaveCopyAs(fileName);//保存
// app.Quit();//关闭进程
// }
// return true;
// #endregion
//}
}
}