xiaojiao
9 天以前 b532ba8806996246ab7a0896bf34b884c47dee7e
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
541
542
543
544
545
546
547
548
549
550
551
552
553
using FastReport;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Drawing.Printing;
using OfficeOpenXml;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
 
namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {
        //public static string ReportPath = System.IO.Directory.GetCurrentDirectory();
        private bool isInputError = false;
        //public static string ReportPath = "E:\\KHGITHUB\\ZhongCheAGVCangKu\\ZhongCheAGVCangKu\\代码管理\\打印机\\WindowsFormsApp6\\WindowsFormsApp6\\FRX";
        //public static string ReportPath = "E:\\项目发布文件夹\\中车打印机";
        public static string ReportPath = Application.StartupPath;
        public Form1()
        {
            InitializeComponent();
            // 新增这行:设置EPPlus的许可证上下文
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            try
            {
                // 读取文件所有行
                string[] lines = System.IO.File.ReadAllLines("D:\\打印机车型轴承品牌下拉框文件夹\\车型.txt");
                string[] lines2 = System.IO.File.ReadAllLines("D:\\打印机车型轴承品牌下拉框文件夹\\轴承型号.txt");
                string[] lines3 = System.IO.File.ReadAllLines("D:\\打印机车型轴承品牌下拉框文件夹\\轴承品牌.txt");
 
                // 添加到下拉框
                this.comboBox3.Items.AddRange(lines2);
                this.comboBox2.Items.AddRange(lines);
                this.comboBox4.Items.AddRange(lines3);
            }
            catch (Exception ex)
            {
                // 读取失败时提示
                MessageBox.Show("读取文件失败:" + ex.Message);
            }
        }
 
        private void btn_print_Click(object sender, EventArgs e)
        {
            try
            {
                PrintDocument pd = new PrintDocument();
                //string name = Txt_barcode1.Text;
                //if (name == "")
                //{
                //    MessageBox.Show("请输入打印数据", "提示", MessageBoxButtons.OKCancel);
                //    return;
                //}
                Dictionary<string, string> printData = GetInputTxtData();
 
                //if (printData.Count == 0)
                //{
                //    MessageBox.Show("请输入打印数据", "提示", MessageBoxButtons.OK);
                //    return;
                //}
 
 
                if (isInputError)
                {
                    MessageBox.Show("输入数据有误或者不完整,请先检查后再打印", "提示", MessageBoxButtons.OK);
                    return;
                }
 
                // 这里做下拉框的绑定
                if (comboBox1.Text == "" || comboBox2.Text == ""
                    || comboBox3.Text == "" || comboBox4.Text == ""
                    || textBox1.Text.Trim() == "" || textBox3.Text.Trim() == "")
                {
                    MessageBox.Show("输入数据有误或者不完整,请先检查后再打印", "提示", MessageBoxButtons.OK);
                    return;
                }
                //string MFile = ReportPath + "\\FRX\\wl.frx";//FastReport设计后的文件保存的路径。
                // 替换原来的 string MFile = ReportPath + "\\FRX\\wl.frx";
                string MFile = Path.Combine(ReportPath, "FRX", "wl.frx");
                if (!File.Exists(MFile))
                {
                    MessageBox.Show(ReportPath.ToString());
                    MessageBox.Show("未找到托盘条码打印样式文件!");
                    return;
                }
                Report report = new Report();
                report.Load(MFile);
                report.PrintSettings.ShowDialog = false;
                PrinterSettings oitem = new PrinterSettings();
                if (report.ShowPrintDialog(out oitem) && oitem.Copies > 0)
                {
                    report.PrintSettings.ShowDialog = false;
                    report.SetParameterValue("Name", printData.Keys.ToList()[0]);//给参数赋值(条码)
                                                                //report.SetParameterValue("No", "456");
                                                                //report.SetParameterValue("Qty", "7");
                                                                //report.SetParameterValue("Supplier", "8");
                    report.SetParameterValue("Barcode", printData[printData.Keys.ToList()[0].ToString()]);
                    report.Print();
                }
                else
                {
                    MessageBox.Show("取消打印");
                }
                report.Dispose();
 
                #region 原打印逻辑
                //string MFile = ReportPath + "\\FRX\\wl.frx";//FastReport设计后的文件保存的路径。
                //if (!File.Exists(MFile))
                //{
                //    throw new Exception("未找到托盘条码打印样式文件!!!");
                //}
                //Report report = new Report();
                //report.Load(MFile);
                //report.PrintSettings.ShowDialog = false;
                //System.Drawing.Printing.PrinterSettings oitem = new System.Drawing.Printing.PrinterSettings();
 
                //if (report.ShowPrintDialog(out oitem) && oitem.Copies > 0)
                //{
                //    report.PrintSettings.ShowDialog = false;
                //    report.SetParameterValue("Name", name);//给参数赋值(条码)
                //                                           //report.SetParameterValue("No", "456");
                //                                           //report.SetParameterValue("Qty", "7");
                //                                           //report.SetParameterValue("Supplier", "8");
                //    report.SetParameterValue("Barcode", name);
                //    report.Print();
                //}
                //report.Dispose(); 
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打印异常:{ex.Message}");
            }
        }
 
        /// <summary>
        /// 获取输入框输入数据    todo应做文本输入格式校验
        /// </summary>
        /// <returns></returns>
        //private List<string> GetInputTxtData()
        //{
        //    List<string> data = new List<string>();
 
        //    string barcode1 = Txt_barcode1.Text; if (!string.IsNullOrWhiteSpace(barcode1)) { data.Add(barcode1); }
        //    string barcode2 = Txt_barcode2.Text; if (!string.IsNullOrWhiteSpace(barcode2)) { data.Add(barcode2); }
        //    string barcode3 = Txt_barcode3.Text; if (!string.IsNullOrWhiteSpace(barcode3)) { data.Add(barcode3); }
        //    string barcode4 = Txt_barcode4.Text; if (!string.IsNullOrWhiteSpace(barcode4)) { data.Add(barcode4); }
        //    string barcode6 = Txt_barcode6.Text; if (!string.IsNullOrWhiteSpace(barcode6)) { data.Add(barcode6); }
        //    if (data.Count > 1) data.Distinct();  //去除重复条码
 
        //    return data;
        //}
 
        private Dictionary<string, string> GetInputTxtData()
        {
            Dictionary<string, string> partCode = new Dictionary<string, string>();
            string Row = "{";
 
            Row += "'轴承条码':"+$"'{Txt_barcode1.Text}',";
            Row += "'车型':"+$"'{comboBox2.Text}',";
            Row += "'轴承型号':"+$"'{comboBox3.Text}',";
            Row += "'轴承品牌':"+$"'{comboBox4.Text}',";
            Row += "'轴承类别':"+$"'{comboBox1.Text}',";
            Row += "'轴承批次号':"+$"'{textBox1.Text}',";
            Row += "'轴承重量':" + $"'{textBox2.Text}',";
            Row += "'日期':" + $"'{textBox3.Text}',";
            Row += "}";
 
            partCode.Add(Txt_barcode1.Text, Row);
 
            return partCode;
        }
 
        /// <summary>
        /// 肖佼 加的验证方法
        /// </summary>
        /// <param name="sender"></param>
        private void Validaltetion(object sender, CancelEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (string.IsNullOrEmpty(textBox.Text))
            {
                errorProvider1.SetError(textBox, "不能为空");
                isInputError = true;
            }
            else
            {
                errorProvider1.SetError(textBox, ""); // 清除错误提示  
                isInputError = false;
            }
        }
 
        /// <summary>
        /// 输入框文本输入验证   为空时清除,不为空时验证输入是否合法
        /// </summary> 
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateTextBox(object sender, CancelEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (string.IsNullOrEmpty(textBox.Text))
            {
                errorProvider1.SetError(textBox, ""); // 清除错误提示  
                isInputError = false;
            }
            else
            {
                if (!textBox.Text.Contains(","))  // 如果不包含&符号 则提示格式异常  包含则检测格式中的&是否正常
                {
                    errorProvider1.SetError(textBox, "格式不正确");
                    isInputError = true;
                }
                else
                {
                    if (CharCount(textBox.Text))
                    {
                        bool k = false;
                        for (int i = 0; i < textBox.Text.Length; i++)
                        {
                            if (textBox.Text[i] == '(')
                            {
                                k = true;
                            }
 
                            if(textBox.Text[i] == ')')
                            {
                                k = true;
                            }
                            if(textBox.Text[i] == ',')
                            {
                                k = true;
                            }
                        }
 
                        if (k)
                        {
                            errorProvider1.SetError(textBox, "格式不正确,符号不可为中文符号");
                            isInputError = true;
                        }
                        else
                        {
                            errorProvider1.SetError(textBox, ""); // 清除错误提示  
                            isInputError = false;
                        }
 
                        
                    }
                    else
                    {
                        errorProvider1.SetError(textBox, "格式不正确");
                        isInputError = true;
                    }
                }
            }
        }
 
        /// <summary>
        /// 窗体载入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void 打印机_Load(object sender, EventArgs e)
        //{
        //    //载入时为每个输入框 订阅文本校验事件
        //    Txt_barcode1.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode2.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode3.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode4.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode5.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode6.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode7.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode8.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode9.Validating += new CancelEventHandler(ValidateTextBox);
        //    Txt_barcode10.Validating += new CancelEventHandler(ValidateTextBox);
        //}
        
        // 肖佼 更改的打印机_Load
        private void 打印机_Load(object sender, EventArgs e)
        {
            //载入时为每个输入框 订阅文本校验事件
            Txt_barcode1.Validating += new CancelEventHandler(Validaltetion);
            //Txt_barcode2.Validating += new CancelEventHandler(Validaltetion);
            //Txt_barcode3.Validating += new CancelEventHandler(Validaltetion);
            //Txt_barcode4.Validating += new CancelEventHandler(Validaltetion);
            textBox1.Validating += new CancelEventHandler(Validaltetion);
            textBox2.Validating += new CancelEventHandler(Validaltetion);
            //Txt_barcode5.Validating += new CancelEventHandler(ValidateTextBox);
            //Txt_barcode6.Validating += new CancelEventHandler(Validaltetion);
            //Txt_barcode7.Validating += new CancelEventHandler(ValidateTextBox);
            //Txt_barcode8.Validating += new CancelEventHandler(ValidateTextBox);
            //Txt_barcode9.Validating += new CancelEventHandler(ValidateTextBox);
            //Txt_barcode10.Validating += new CancelEventHandler(ValidateTextBox);
        }
 
 
 
        private bool CharCount(string str)
        {
            int SumCount = 4;
            int strCoutn = 0;
            foreach (var item in str.ToCharArray())
            {
                if (item.Equals(',')) strCoutn++;
            }
            return strCoutn == SumCount;
        }
 
        private void btn_SelectFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.InitialDirectory = "c:\\"; // 设置初始目录
            openFileDialog.Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx"; // 设置文件过滤器
            openFileDialog.Title = "选择Excel文件";
            openFileDialog.FilterIndex = 2;
            openFileDialog.RestoreDirectory = true;
 
            if (openFileDialog.ShowDialog() == DialogResult.OK) // 显示对话框
            {
                // 获取选中文件的路径
                string filePath = openFileDialog.FileName;
                txt_file.Text = filePath;
            }
        }
 
        private void btn_filePrint_Click(object sender, EventArgs e)
        {
            try
            {
                string filePath = txt_file.Text;
                if (string.IsNullOrEmpty(filePath))
                {
                    MessageBox.Show("请先选择文件");
                    return;
                }
 
                FileInfo file = new FileInfo(filePath);
                if (!file.Exists)
                {
                    MessageBox.Show("未找到上传的文件,请重新选择");
                    return;
                }
                string errormsg = string.Empty;
                //List<string> partCode = new List<string>();
                Dictionary<string,string> partCode = new Dictionary<string,string>();
                List<string> line_Name = new List<string>();
 
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    if (package.Workbook.Worksheets.Count == 0 || package.Workbook.Worksheets.FirstOrDefault().Dimension.End.Row <= 1)
                    {
                        MessageBox.Show("表格未导入数据");
                        return;
                    }
 
                    ExcelWorksheet sheet = package.Workbook.Worksheets.FirstOrDefault();
                    if (sheet != null)
                    {
                        //string columnCNName = sheet.Cells[1, 1].Value?.ToString()?.Trim();
                        //if (columnCNName != "part_code")
                        //{
                        //    MessageBox.Show($"导入模板异常,请检查文件中的A1项是否为'part_code'");
                        //    return;
                        //}
                        
                        for (int m = sheet.Dimension.Start.Row + 1, n = sheet.Dimension.End.Row; m <= n; m++)
                        {
                            string Temp_Row = "{";
                            string value = "";
                            for (int j = sheet.Dimension.Start.Column, k = sheet.Dimension.End.Column; j <= k; j++)
                            {
                                string tempstr = $"'{sheet.Cells[1, j].Value?.ToString()}':'{sheet.Cells[m, j].Value?.ToString()}',";
                                Temp_Row += tempstr;
                                if (j == 1)
                                {
                                    // line_Name.Add(value);
                                    value = sheet.Cells[m, j].Value?.ToString();
                                    
                                }
                                //if (value != null)
                                //{
                                //    //todo 数据验证  --格式验证 等
                                //    if (CharCount(value))
                                //    {
                                //        partCode.Add(value);
                                //    }
                                //    else
                                //    {
                                //        errormsg += $"第{m}行编码验证未通过,格式异常。{Environment.NewLine}";
                                //        continue;
                                //    }
                                //}
                                //else
                                //{
                                //    errormsg += $"第{m}行编码验证未通过,不能为空。{Environment.NewLine}";
                                //    continue;
                                //}
                            }
                            Temp_Row += "}";
                            //partCode.Add(Temp_Row);
                            partCode[value] = Temp_Row;
                        }
                    }
                }
                if (!string.IsNullOrEmpty(errormsg))
                {
                    MessageBox.Show(errormsg);
                    return;
                }
                else
                {
                    //string MFile = ReportPath + "\\FRX\\wl.frx";//FastReport设计后的文件保存的路径。
 
                    // 替换原来的 string MFile = ReportPath + "\\FRX\\wl.frx";
                    string MFile = Path.Combine(ReportPath, "FRX", "wl.frx");
                    if (!File.Exists(MFile))
                    {
                        MessageBox.Show("未找到托盘条码打印样式文件!!!");
                        return;
                    }
 
                    Report report = new Report();
                    report.Load(MFile);
                    report.PrintSettings.ShowDialog = false;
                    PrinterSettings oitem = new PrinterSettings();
                    if (report.ShowPrintDialog(out oitem) && oitem.Copies > 0)
                    {
                        //foreach (string data in partCode)
                        //{
 
                        //    report.SetParameterValue("Barcode", data);
 
                        //}
                        //foreach (var item in line_Name)
                        //{
                        //    report.PrintSettings.ShowDialog = false;
                        //    report.SetParameterValue("Name", item);//给参数赋值(条码)
                        //                                                         //report.SetParameterValue("No", "456");
                        //                                                         //report.SetParameterValue("Qty", "7");
                        //                                                         //report.SetParameterValue("Supplier", "8");
                        //}
                        //report.Print();
                        foreach (KeyValuePair<string, string> kvp in partCode)
                        {
                            report.PrintSettings.ShowDialog = false;
                            report.SetParameterValue("Name", kvp.Key);//给参数赋值(条码)
 
                            report.SetParameterValue("Barcode", kvp.Value);
                            report.Print();
                        }
                    }
                    else
                    {
                        MessageBox.Show("取消打印");
                        return;
                    }
                    report.Dispose();
 
                    MessageBox.Show("打印成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打印异常:{ex.Message}");
            }
 
            //try
            //{
            //    string filePath = txt_file.Text;
            //    if (string.IsNullOrEmpty(filePath))
            //    {
            //        MessageBox.Show("请先选择文件");
            //        return;
            //    }
 
            //    FileInfo file = new FileInfo(filePath);
            //    if (!file.Exists)
            //    {
            //        MessageBox.Show("文件不存在,请检查路径");
            //        return;
            //    }
 
            //    // 1. 强制设置EPPlus许可证(必须)
            //    ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            //    List<string> dataList = new List<string>();
 
            //    using (ExcelPackage package = new ExcelPackage(file))
            //    {
            //        // 2. 修复索引问题:用First()取第一个工作表(最安全)
            //        if (package.Workbook.Worksheets.Count == 0)
            //        {
            //            MessageBox.Show("表格中无任何工作表");
            //            return;
            //        }
            //        ExcelWorksheet sheet = package.Workbook.Worksheets.First();
 
            //        // 3. 读取前20行A列(列索引1),覆盖你的数据范围
            //        int readMaxRow = 20; // 可根据你的表格调整
            //        for (int row = 1; row <= readMaxRow; row++)
            //        {
            //            // 读取A列单元格,处理空值
            //            string cellValue = sheet.Cells[row, 1].Value?.ToString()?.Trim();
            //            if (!string.IsNullOrEmpty(cellValue))
            //            {
            //                dataList.Add($"第{row}行:{cellValue}");
            //            }
            //        }
            //    }
 
            //    // 4. 弹窗显示读取结果(直观验证)
            //    if (dataList.Count > 0)
            //    {
            //        MessageBox.Show("✅ 读取到的数据:\n" + string.Join("\n", dataList));
            //    }
            //    else
            //    {
            //        MessageBox.Show("❌ 未读取到任何数据,请检查:\n1. 表格A列是否有数据\n2. 数据是否为非空文本");
            //    }
            //}
            //catch (Exception ex)
            //{
            //    // 显示完整错误信息(方便定位)
            //    MessageBox.Show($"❌ 读取失败:\n错误信息:{ex.Message}\n调用堆栈:{ex.StackTrace}");
            //}
        }
 
        private void label14_Click(object sender, EventArgs e)
        {
 
        }
 
        private void Txt_barcode1_TextChanged(object sender, EventArgs e)
        {
 
        }
 
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }
 
        private void groupBox2_Enter(object sender, EventArgs e)
        {
 
        }
    }
}