啊鑫
2024-07-11 afbf8700d137710713db61955879d0f5acb73738
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
#region
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Windows.Forms;
using CSFrameworkV5.Common;
using CSFrameworkV5.Library.CommonClass;
using CSFrameworkV5.Library.CommonForms;
using DevExpress.Data;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using ProgressBar = System.Windows.Forms.ProgressBar;
 
#endregion
 
namespace CSFrameworkV5.Library
{
    /// <summary>
    ///     从Excel文件导入数据通用接口
    /// </summary>
    public partial class frmImportExcel : XtraForm
    {
        /// <summary>
        ///     数据源与目标表字段映射关系
        /// </summary>
        private List<FieldMapping> _FieldMapping;
 
        /// <summary>
        ///     连接数据源通用接口
        /// </summary>
        private IImporterSource _MyConn;
 
        /// <summary>
        ///     导入数据到目的地接口
        /// </summary>
        private IImporterTarget _Target;
 
        /// <summary>
        ///     私有构造器
        /// </summary>
        private frmImportExcel()
        {
            InitializeComponent();
        }
 
        private void btnFieldMapping_Click(object sender, EventArgs e)
        {
            if (gcPreview.DataSource != null)
            {
                var source = gcPreview.DataSource as DataTable;
                _FieldMapping =
                    frmImporterFieldMapping.Execute(source, _Target,
                        _FieldMapping);
            }
            else
            {
                Msg.Warning("请先查询数据!");
            }
        }
 
        private void btnImport_Click(object sender, EventArgs e)
        {
            if (_FieldMapping != null && GetMappingCount(_FieldMapping) > 0)
            {
                if (!Msg.AskQuestion("确定要导入数据吗?")) return;
 
                //导入前先清空原有数据
                if (chkEmptyData.Checked) _Target.ClearData();
 
                try
                {
                    CCursor.ShowWaitCursor();
                    btnImport.Enabled = false;
                    Application.DoEvents();
                    var source = gcPreview.DataSource as DataTable;
                    IProgressBar progess =
                        new ImportProgress(progressBar1, label1);
                    var list = _Target.Import(source, _FieldMapping, progess);
                    CCursor.ShowDefaultCursor();
                    frmOperateReport.ShowReport("导入数据", list);
                    Close();
                }
                finally
                {
                    CCursor.ShowDefaultCursor();
                    btnImport.Enabled = true;
                }
            }
            else
            {
                Msg.Warning("请先建立字段映射关系!");
                btnFieldMapping_Click(btnFieldMapping, new EventArgs());
            }
        }
 
        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (!_MyConn.IsConnected)
            {
                Msg.Warning("没有选择Excel文件或者读取文件失败!");
                txtFile.Focus();
                return;
            }
 
            if (txtTables.Text != "")
            {
                var dt = _MyConn.GetData(txtTables.Text);
                gvPreview.Columns.Clear();
                gcPreview.DataSource = null;
                gcPreview.DataSource = dt;
                gvPreview.VisibleColumns[0].SummaryItem.SummaryType =
                    SummaryItemType.Count;
            }
            else
            {
                txtTables.Focus();
            }
        }
 
        private void btnTestConnection_Click(object sender, EventArgs e)
        {
            //测试连接
            string msg;
 
            if (TestConnection(out msg))
            {
                var tables = _MyConn.GetTableNameList(); //取数据源的资料表
                txtTables.Properties.Items.Clear();
                txtTables.Properties.Items.AddRange(tables);
                MessageBox.Show("连接数据库成功!", "提示", MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                txtTables.Focus();
                txtTables.ShowPopup();
            }
            else
            {
                MessageBox.Show(msg, "错误", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }
 
        private void DoOpenFile()
        {
            var dlg = new OpenFileDialog();
            dlg.Filter =
                "Microsoft Excel 97~2003 Files|*.xls|Microsoft Excel 2007~2010 Files|*.xlsx";
            if (dlg.ShowDialog() == DialogResult.OK)
                txtFile.Text = dlg.FileName;
        }
 
        /// <summary>
        ///     执行向导的统一入口
        /// </summary>
        /// <param name="target">数据目地的</param>
        public static void ExecuteImporter(IImporterTarget target,
            List<FieldMapping> fieldMapping)
        {
            var form = new frmImportExcel();
            form._Target = target;
            form._FieldMapping = fieldMapping;
            form.ShowDialog();
        }
 
        /// <summary>
        ///     执行向导的统一入口
        /// </summary>
        /// <param name="target">数据目地的</param>
        public static void ExecuteImporter(IImporterTarget target)
        {
            var form = new frmImportExcel();
            form._Target = target;
            form.ShowDialog();
        }
 
        private void frmImportExcel_Load(object sender, EventArgs e)
        {
            //
        }
 
        private int GetMappingCount(List<FieldMapping> fieldMapping)
        {
            var counter = 0;
            foreach (var fm in fieldMapping)
                if (fm.IsValid)
                    counter++;
 
            return counter;
        }
 
        public bool TestConnection(out string msg)
        {
            msg = "";
            if (txtFile.Text == "")
            {
                msg = "请选择文件!";
                return false;
            }
 
            //Excel数据源实例,如改为SQL导入,在此建立SQL数据源实例
            _MyConn = new ImportDataFromExcel(txtFile.Text);
            var success = _MyConn.TestConnection(out msg);
            return success;
        }
 
        private void txtFile_ButtonClick(object sender,
            ButtonPressedEventArgs e)
        {
            DoOpenFile();
            if (txtFile.Text.Trim() != "")
                btnTestConnection_Click(btnTestConnection, new EventArgs());
        }
 
        private void txtFile_Validating(object sender, CancelEventArgs e)
        {
            //检查文件
 
            if (txtFile.Text.Trim() == "") return;
 
            //防止路径遍历
            //var fileName = txtFile.Text.Replace("..", "").Replace(@"\", "").Replace("/", "");
 
            if (!File.Exists(CodeSafeHelper.GetSafePath(txtFile.Text)))
            {
                Msg.Warning("文件不存在!");
                e.Cancel = true;
            }
 
            var ext =
                TrueFileFormat.GetExtension(
                    CodeSafeHelper.GetSafePath(txtFile.Text));
            if (ext != FileExtension.XLS)
            {
                Msg.Warning("无效的Excel文件!");
                e.Cancel = true;
            }
        }
    }
 
    /// <summary>
    ///     进度条
    /// </summary>
    public class ImportProgress : IProgressBar
    {
        private Label _label;
        private ProgressBar _progress;
 
        public ImportProgress(ProgressBar progress, Label label)
        {
            _progress = progress;
            _label = label;
            Reset();
        }
 
        public int MaxValue
        {
            get => _progress.Maximum;
            set => _progress.Maximum = value;
        }
 
        public int MinValue
        {
            get => _progress.Minimum;
            set => _progress.Minimum = value;
        }
 
        public int Position
        {
            get => _progress.Value;
            set
            {
                _progress.Value = value;
                _progress.Invalidate();
 
                if (_progress.Value >= _progress.Maximum)
                    _label.Text = string.Format("{0} / {1},操作完成.",
                        _progress.Value, _progress.Maximum);
                else
                    _label.Text = string.Format("{0} / {1},正在操作,请稍候...",
                        _progress.Value, _progress.Maximum);
 
                _label.Invalidate();
                Application.DoEvents();
            }
        }
 
        public void Reset()
        {
            _progress.Maximum = MaxValue;
            _progress.Minimum = MinValue;
            _progress.Step = 1;
            _progress.Value = 0;
            _progress.Invalidate();
            _label.Text = "进度条.";
            _label.Invalidate();
        }
    }
}