1
yhj
2024-07-24 5e5d945e91568b973faa27d8ab0bcef99fc4a6c5
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#region
 
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using CSFrameworkV5.Common;
using CSFrameworkV5.Core;
using CSFrameworkV5.Library.CommonForms;
 
#endregion
 
namespace CSFrameworkV5.Library.CommonClass
{
    /// <summary>
    ///     导入数据通用接口
    /// </summary>
    public interface IImporterSource
    {
        /// <summary>
        ///     是否连接
        /// </summary>
        bool IsConnected { get; }
 
        /// <summary>
        ///     创建连接
        /// </summary>
        /// <returns></returns>
        DbConnection CreateConnection();
 
        /// <summary>
        ///     获取用于预览的数据
        /// </summary>
        /// <returns></returns>
        DataTable GetData(string tableName);
 
        /// <summary>
        ///     取数据库清单
        /// </summary>
        /// <returns></returns>
        List<string> GetDatabaseList();
 
        /// <summary>
        ///     取表结构
        /// </summary>
        /// <returns></returns>
        List<string> GetFields(string tableName);
 
        /// <summary>
        ///     取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        DataTable GetTable(string tableName, string orderBy);
 
        /// <summary>
        ///     取数据库中所有资料表
        /// </summary>
        /// <returns></returns>
        List<string> GetTableNameList();
 
        /// <summary>
        ///     测试连接
        /// </summary>
        /// <returns></returns>
        bool TestConnection(out string msg);
    }
 
    /// <summary>
    ///     导入数据到目标表的接口
    /// </summary>
    public abstract class IImporterTarget
    {
        protected DataTable _DataSource;
        protected DataTable _DataTarget;
 
        private List<OperateReportItem> _ReportList =
            new List<OperateReportItem>();
 
        protected string _ReportTitle = "导入数据";
 
        public IImporterTarget()
        {
        }
 
        public IImporterTarget(DataTable dataTarget)
        {
            _DataTarget = dataTarget;
        }
 
        /// <summary>
        ///     本次导入错误信息
        /// </summary>
        public string ErrorInfo { get; set; }
 
        /// <summary>
        ///     返回导入的记录数
        /// </summary>
        public int LastImportCounter { get; set; }
 
        /// <summary>
        ///     导入失败的记录数
        /// </summary>
        public int LastImportFailed { get; set; }
 
        protected void AddReport(bool isError, string stepText, string content,
            string refID)
        {
            if (_ReportList != null)
                _ReportList.Add(new OperateReportItem(isError, stepText, refID,
                    content));
        }
 
        protected virtual void BeginImport(DataTable dataSource)
        {
        }
 
        /// <summary>
        ///     清空目标表的数据
        /// </summary>
        public abstract void ClearData();
 
        protected virtual void EndImport(int success, int failed)
        {
        }
 
        /// <summary>
        ///     获取目标表的字段清单
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public List<FieldEntity> GetFieldList()
        {
            var fieldListTarget = new List<FieldEntity>();
            foreach (DataColumn col in _DataTarget.Columns)
                fieldListTarget.Add(new FieldEntity(col.ColumnName,
                    col.ColumnName));
 
            return fieldListTarget;
        }
 
        protected virtual object GetFieldValue(DataRow sourceRow,
            DataRow targetRow, FieldMapping mapping)
        {
            var T = targetRow.Table.Columns[mapping.TargetField].DataType;
            var o = sourceRow[mapping.SourceField];
 
            //日期类型兼容
            if (T == typeof(DateTime))
            {
                if (o == null || o.ToStringEx().Trim() == string.Empty)
                    return DBNull.Value;
 
                return ConvertEx.ToDateTime(o);
            }
 
            if (T == typeof(int) || T == typeof(int) || T == typeof(long))
                return ConvertEx.ToInt(o);
 
            if (T == typeof(double) || T == typeof(float) ||
                T == typeof(decimal)) return ConvertEx.ToDecimal(o);
 
            return sourceRow[mapping.SourceField];
        }
 
        /// <summary>
        ///     获取字段映射关系
        /// </summary>
        /// <returns></returns>
        public abstract List<FieldMapping> GetMapping();
 
        /// <summary>
        ///     开始导入数据
        /// </summary>
        /// <param name="source">数据源</param>
        /// <param name="fieldMapping">字段映射</param>
        /// <param name="progress">进度条控件</param>
        /// <returns>返回操作报告</returns>
        public virtual List<OperateReportItem> Import(
            DataTable source,
            List<FieldMapping> fieldMapping,
            IProgressBar progress)
        {
            _DataSource = source;
            _ReportList.Clear();
 
            LastImportCounter = 0;
            LastImportFailed = 0;
 
            progress.Position = 1;
            progress.MinValue = 0;
            progress.MaxValue = source.Rows.Count;
            progress.Reset();
 
            DataRow targetRow;
            var isImport = false; //需要导入当前记录
            var index = 0;
 
            //开始导入
            BeginImport(_DataSource);
 
            foreach (DataRow R in source.Rows)
            {
                if (IsEmptyRow(R)) continue; //不导入空记录
 
                index = source.Rows.IndexOf(R);
 
                targetRow = _DataTarget.NewRow();
 
                foreach (var mp in fieldMapping)
                    if (mp.SourceField != "" && mp.TargetField != "")
                    {
                        isImport = true; //有匹配成功的字段
 
                        targetRow[mp.TargetField] =
                            GetFieldValue(R, targetRow, mp);
                    }
 
                //没有映射关系的字段不导入数据
                if (isImport) //当前记录需要导入
                {
                    targetRow.EndEdit();
 
                    var errMsg = "";
                    //提交数据
                    if (PostImportedData(targetRow, out errMsg))
                    {
                        _ReportList.Add(new OperateReportItem(false,
                            _ReportTitle, "行号:" + index.ToStringEx(),
                            "导入成功."));
                        LastImportCounter++;
                    }
                    else
                    {
                        _ReportList.Add(new OperateReportItem(true,
                            _ReportTitle, "<错误行:" + index.ToStringEx() + ">",
                            errMsg));
                        LastImportFailed++;
                    }
                }
 
                progress.Position++;
            }
 
            AddReport(false, _ReportTitle, "导入结束。", "");
            AddReport(false, _ReportTitle,
                string.Format("成功{0},失败{1}", LastImportCounter,
                    LastImportFailed), "");
 
            EndImport(LastImportCounter, LastImportFailed);
 
            return _ReportList;
        }
 
        protected bool IsEmptyRow(DataRow R)
        {
            var str = "";
            for (var i = 0; i <= R.Table.Columns.Count - 1; i++)
            {
                str = ConvertEx.ToString(R[i]).Trim();
                str = str.Replace("0", "").Replace(".", "");
                if (str != "") return false;
            }
 
            return true;
        }
 
        /// <summary>
        ///     匹配字段名
        /// </summary>
        /// <param name="data"></param>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public string MatchField(string fieldName)
        {
            foreach (DataColumn col in _DataTarget.Columns)
                if (col.ColumnName.Trim() == fieldName.Trim())
                    return fieldName.Trim();
 
            return "";
        }
 
        /// <summary>
        ///     提交数据
        /// </summary>
        /// <param name="drTarge">当前记录</param>
        /// <returns></returns>
        protected abstract bool PostImportedData(DataRow drTarge,
            out string errMsg);
    }
 
    /// <summary>
    ///     数据导入接口基类
    /// </summary>
    public class ImporterDataSourceBase : IImporterSource
    {
        #region IImporterDataSource Members
 
        public virtual DbConnection CreateConnection()
        {
            throw new Exception("CreateConnection方法没有实现!");
        }
 
        public virtual bool TestConnection(out string msg)
        {
            msg = "";
            try
            {
                using (var conn = CreateConnection())
                {
                    conn.Open();
                    conn.Close();
                    return true;
                }
            }
            catch (Exception ex)
            {
                msg = "连接数据库失败!" + ex.Message;
                return false;
            }
        }
 
        /// <summary>
        ///     是否连接
        /// </summary>
        public bool IsConnected
        {
            get
            {
                string msg;
                return TestConnection(out msg);
            }
        }
 
        public virtual DataTable GetTable(string tableName, string orderBy)
        {
            throw new Exception("GetTable方法没有实现!");
        }
 
        /// <summary>
        ///     取所有表名
        /// </summary>
        /// <returns></returns>
        public virtual List<string> GetTableNameList()
        {
            var list = new List<string>();
 
            using (var conn = CreateConnection())
            {
                var dt = conn.GetSchema("Tables");
                foreach (DataRow row in dt.Rows)
                    if (row[3].ToStringEx() == "TABLE" ||
                        row[3].ToStringEx() == "BASE TABLE")
                        list.Add(row[2].ToStringEx());
            }
 
            return list;
        }
 
        /// <summary>
        ///     取指定表所有字段名称
        /// </summary>
        /// <returns></returns>
        public virtual List<string> GetFields(string tableName)
        {
            var list = new List<string>();
 
            DbConnection conn = null;
            OleDbCommand cmd = null;
            OleDbDataReader dr = null;
 
            try
            {
                using (conn = CreateConnection())
                {
                    using (cmd = new OleDbCommand())
                    {
                        var sql = "SELECT TOP 1 * FROM " + tableName;
                        cmd.CommandText = CodeSafeHelper.GetSafeSQL(sql);
                        cmd.Connection = conn as OleDbConnection;
                        using (dr = cmd.ExecuteReader())
                        {
                            for (var i = 0; i < dr.FieldCount; i++)
                                list.Add(dr.GetName(i));
                        }
                    }
                }
            }
            finally
            {
                if (conn != null) conn.Dispose();
 
                if (cmd != null) cmd.Dispose();
 
                if (dr != null) dr.Dispose();
            }
 
            return list;
        }
 
        public virtual List<string> GetDatabaseList()
        {
            throw new Exception("GetDatabaseList方法没有实现!");
        }
 
        /// <summary>
        ///     获取用于预览的数据
        /// </summary>
        /// <returns></returns>
        public virtual DataTable GetData(string tableName)
        {
            return GetTable(tableName, "");
        }
 
        #endregion
    }
 
    /// <summary>
    ///     从Excel文件导入数据
    /// </summary>
    public class ImportDataFromExcel : ImporterDataSourceBase
    {
        private string _FileName = "";
 
        public ImportDataFromExcel(string fileName)
        {
            _FileName = fileName;
        }
 
        public override DbConnection CreateConnection()
        {
            // IMEX=1 可把混合型作为文本型读取,避免null值         
            var conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                       _FileName +
                       ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
            return new OleDbConnection(conn);
        }
 
        public override DataTable GetTable(string tableName, string orderBy)
        {
            DataTable dt = null;
 
            var sql = "SELECT * FROM " + tableName +
                      (!string.IsNullOrWhiteSpace(orderBy)
                          ? " ORDER BY " + orderBy
                          : "");
 
            using (var conn = CreateConnection())
            {
                var cmd = conn.CreateCommand() as OleDbCommand;
                cmd.CommandText = CodeSafeHelper.GetSafeSQL(sql);
                dt = new DataTable();
                DbDataAdapter adp = new OleDbDataAdapter(cmd);
                adp.Fill(dt);
            }
 
            return dt;
        }
    }
 
    /// <summary>
    ///     字段实体类定义
    /// </summary>
    public class FieldEntity
    {
        private string _FieldName;
        private string _TitleName;
 
        public FieldEntity(string fieldName, string titleName)
        {
            _FieldName = fieldName;
            _TitleName = titleName;
        }
 
        public string FieldName
        {
            get => _FieldName;
            set => _FieldName = value;
        }
 
        public string TitleName
        {
            get => _TitleName;
            set => _TitleName = value;
        }
    }
 
    /// <summary>
    ///     字段名称映射
    /// </summary>
    public class FieldMapping
    {
        private string _SourceField;
        private string _TargetField;
 
        public FieldMapping(string sourceField, string targetField)
        {
            _SourceField = sourceField;
            _TargetField = targetField;
        }
 
        /// <summary>
        ///     映射关系是否有效
        /// </summary>
        public bool IsValid => !string.IsNullOrEmpty(_SourceField) &&
                               !string.IsNullOrEmpty(_TargetField);
 
        /// <summary>
        ///     来源字段
        /// </summary>
        public string SourceField
        {
            get => _SourceField;
            set => _SourceField = value;
        }
 
        /// <summary>
        ///     目标表字段
        /// </summary>
        public string TargetField
        {
            get => _TargetField;
            set => _TargetField = value;
        }
    }
 
    /// <summary>
    ///     进度条
    /// </summary>
    public interface IProgressBar
    {
        int MaxValue { get; set; }
 
        int MinValue { get; set; }
 
        int Position { get; set; }
        void Reset();
    }
}