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 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}"); } } /// /// 获取输入框输入数据 todo应做文本输入格式校验 /// /// //private List GetInputTxtData() //{ // List data = new List(); // 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 GetInputTxtData() { Dictionary partCode = new Dictionary(); 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; } /// /// 肖佼 加的验证方法 /// /// 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; } } /// /// 输入框文本输入验证 为空时清除,不为空时验证输入是否合法 /// /// /// 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; } } } } /// /// 窗体载入事件 /// /// /// //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 partCode = new List(); Dictionary partCode = new Dictionary(); List line_Name = new List(); 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 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 dataList = new List(); // 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) { } } }