using System; using System.IO; using System.Text; using System.Windows.Forms; using System.Net; using System.Collections.Generic; using System.Threading; using System.Data; using System.Drawing.Imaging; using System.Drawing; using UAS_MES_NEW.Entity; using UAS_MES_NEW.PublicMethod; using Aspose.Cells; using UAS_MES_NEW.DataOperate; using UAS_MES_NEW.PublicForm; using Aspose.Cells.Drawing; using Aspose.Cells.Rendering; using System.Web.Script.Serialization; using Seagull.BarTender.Print; namespace UAS_MES_NEW.Query { public partial class Query_SOP : Form { DataHelper dh; string usercode; string sourcecode; DataTable Dbfind; public Query_SOP() { usercode = ""; sourcecode = ""; InitializeComponent(); } private void Form3_Load(object sender, EventArgs e) { CheckForIllegalCrossThreadCalls = false; ps_prodcode.TableName = "productsop"; ps_prodcode.SelectField = "ps_code # 流水号,ps_prodcode # SOP编号"; ps_prodcode.FormName = Name; ps_prodcode.DBTitle = "SOP查询"; ps_prodcode.SetValueField = new string[] { "ps_code", "ps_prodcode" }; ps_prodcode.Condition = ""; ps_prodcode.DbChange += nr_rule_DBChange; pr_code.TableName = "product"; pr_code.SelectField = "pr_code # 产品编号,pr_detail # 产品名称,pr_spec # 产品规格"; pr_code.FormName = Name; pr_code.DBTitle = "物料查询"; pr_code.Condition = "pr_code not like '%LX%'"; pr_code.SetValueField = new string[] { "pr_code" }; DateTime targetMonth = DateCode.Value.AddMonths(2); DateTime endOfMonth = new DateTime(targetMonth.Year, targetMonth.Month, DateTime.DaysInMonth(targetMonth.Year, targetMonth.Month)); DateCode.Value = endOfMonth; dh = SystemInf.dh; } private void nr_rule_DBChange(object sender, EventArgs e) { Dbfind = ps_prodcode.ReturnData; BaseUtil.SetFormValue(this.Controls, Dbfind); } void uploadfile() { if (FilePath.Text == "") { MessageBox.Show("文件不能为空!"); return; } //if (pr_code.Text == "") //{ // MessageBox.Show("产品编号不能为空!"); // return; //} if (JPG.Checked) { ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", ""); pr_code_Leave(new object(), new EventArgs()); DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select"); if (dt.Rows.Count == 0) { string code = LogicHandler.GetPiInoutCode("ProductSOP", "1"); ps_code.Text = code; if (VaildDate.Checked) { dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_vailddate,ps_prcode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING',to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd'),'" + pr_code.Text + "')", "insert"); } else { dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_prcode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING','" + pr_code.Text + "')", "insert"); } } else { string ps_id = dt.Rows[0]["ps_id"].ToString(); dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + ps_id + "'", "delete"); ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString(); } Workbook workbook = new Workbook(FilePath.Text); List list = new List(); List filename = new List(); if (VaildDate.Checked) { dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update"); } else { dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update"); } OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n"); for (int i = 0; i < workbook.Worksheets.Count; i++) { OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n"); if (JPG.Checked) { //try //{ // ---------- 输出目录 ---------- if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text)) { Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text); } string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\"; Worksheet she = workbook.Worksheets[i]; // ---------- 基础参数 ---------- int lastColIndex = she.Cells.MaxDataColumn + 3; string lastColLetter = CellsHelper.ColumnIndexToName(lastColIndex); const int headerRows = 3; // 表头行数(每页都保留) int dataRowsPerPage = int.Parse(RowCount.Value.ToString()); // 计算"内容最大行"时包含图片和形状的底部锚点行 int contentMaxRow = she.Cells.MaxDataRow; for (int p = 0; p < she.Pictures.Count; p++) { if (she.Pictures[p].LowerRightRow > contentMaxRow) contentMaxRow = she.Pictures[p].LowerRightRow; } for (int s = 0; s < she.Shapes.Count; s++) { if (she.Shapes[s].LowerRightRow > contentMaxRow) contentMaxRow = she.Shapes[s].LowerRightRow; } // ========== ★ 修改点1:totalRows 向上取整到完整页数 ========== // 原来:int totalRows = contentMaxRow + 1; → 最后一页只到实际数据行,空白被截掉 // 现在:先算实际数据行数和页数,再把 totalRows 补足为 headerRows + 总页数 × 每页行数 // 这样最后一页即使数据不足,也会保留完整的 dataRowsPerPage 行空白 int actualDataRows = Math.Max(contentMaxRow + 1 - headerRows, 0); int totalPages = (int)Math.Ceiling(actualDataRows / (double)dataRowsPerPage); if (totalPages == 0) totalPages = 1; int totalRows = headerRows + totalPages * dataRowsPerPage; // ========== ★ 修改点1结束 ========== int totalDataRows = Math.Max(totalRows - headerRows, 0); // 水印在原表中的目标行/列 int wmRowGlobal = int.Parse(Y.Value.ToString()); int wmCol = int.Parse(X.Value.ToString()); int imageIndex = 1; for (int page = 0; page < totalPages; page++) { // ---------- 1. 复制原表到临时工作表 ---------- int newSheetIndex = workbook.Worksheets.Add(); Worksheet newshe = workbook.Worksheets[newSheetIndex]; newshe.Copy(she); newshe.Name = $"Temp_{page}"; // 本页在原表中的数据行区间(原表坐标,0-based) int dataStartRow = headerRows + page * dataRowsPerPage; int dataEndRow = Math.Min(headerRows + (page + 1) * dataRowsPerPage - 1, totalRows - 1); // ---------- 2. 按页过滤原表图片(Pictures) ---------- for (int p = newshe.Pictures.Count - 1; p >= 0; p--) { Aspose.Cells.Drawing.Picture pic = newshe.Pictures[p]; int topRow = pic.UpperLeftRow; bool isHeaderPic = topRow < headerRows; bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow; if (!isHeaderPic && !belongsToPage) { newshe.Pictures.RemoveAt(p); } } // ---------- 3. 按页过滤原表形状(Shapes:文本框/箭头/连接线等) ---------- for (int s = newshe.Shapes.Count - 1; s >= 0; s--) { Aspose.Cells.Drawing.Shape shape; try { shape = newshe.Shapes[s]; } catch { // 下标已经失效,直接跳过 continue; } int topRow = shape.UpperLeftRow; bool isHeaderShape = topRow < headerRows; bool belongsToPage = topRow >= dataStartRow && topRow <= dataEndRow; if (!isHeaderShape && !belongsToPage) { try { newshe.Shapes.RemoveAt(s); } catch { // GroupShape组合形状无法直接RemoveAt,就隐藏 shape.IsHidden = true; } } } // ---------- 4. 清空非本页单元格内容 ---------- for (int r = 0; r < totalRows; r++) { if (r < headerRows) continue; if (r >= dataStartRow && r <= dataEndRow) continue; newshe.Cells.ClearRange(r, 0, r, lastColIndex); } // ---------- 5. 删除非本页整行 ---------- for (int r = totalRows - 1; r >= 0; r--) { if (r < headerRows) continue; if (r >= dataStartRow && r <= dataEndRow) continue; newshe.Cells.DeleteRow(r); } // ---------- 6. 页面设置 ---------- int printMaxRow = newshe.Cells.MaxDataRow; for (int p = 0; p < newshe.Pictures.Count; p++) { if (newshe.Pictures[p].LowerRightRow > printMaxRow) printMaxRow = newshe.Pictures[p].LowerRightRow; } for (int s = 0; s < newshe.Shapes.Count; s++) { if (newshe.Shapes[s].LowerRightRow > printMaxRow) printMaxRow = newshe.Shapes[s].LowerRightRow; } int newTotalRows = printMaxRow + 1; // ========== ★ 修改点2:PrintArea 固定页高,最后一页空白行也显示 ========== // 原来:最后一页 PrintArea 只到 newTotalRows(实际内容行),空白被截掉 // 现在:打印区高度取 max(实际内容行, 表头+每页行数),保证每页等高 int pageHeight = headerRows + dataRowsPerPage; int printEndRow = Math.Max(newTotalRows, pageHeight); if (i == 0) { newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{25}"; } else { newshe.PageSetup.PrintArea = $"A1:{lastColLetter}{printEndRow}"; } // ========== ★ 修改点2结束 ========== newshe.PageSetup.CenterHorizontally = true; newshe.PageSetup.CenterVertically = true; newshe.PageSetup.LeftMargin = 2; newshe.PageSetup.RightMargin = 2; newshe.PageSetup.TopMargin = 2; newshe.PageSetup.BottomMargin = 2; newshe.PageSetup.SetFooter(0, ""); newshe.PageSetup.SetFooter(1, ""); newshe.PageSetup.SetFooter(2, ""); // ---------- 7. 插入水印(额外图片,坐标映射到压缩后本页) ---------- if (File.Exists(PrintPath.Text)) { int rowOffset = headerRows + int.Parse(Y.Value.ToString()); newshe.Pictures.Add(rowOffset, int.Parse(X.Value.ToString()), PrintPath.Text); } // ---------- 8. 页脚 ---------- string pageFooter = $"第 {imageIndex} 页 / 共 {totalPages} 页"; newshe.PageSetup.SetFooter(1, pageFooter); // ---------- 9. 渲染为 PNG ---------- ImageOrPrintOptions options = new ImageOrPrintOptions(); options.ImageFormat = ImageFormat.Png; options.OnePagePerSheet = true; options.PrintingPage = PrintingPageType.Default; SheetRender sr = new SheetRender(newshe, options); if (sr.PageCount > 0) { using (Bitmap bitmap = sr.ToImage(0)) { string imagename = $"{she.Name}_{imageIndex}.png"; string imagePath = Path.Combine(path, imagename); bitmap.Save(imagePath, ImageFormat.Png); OperatResult.AppendText("解析图片【" + imagePath + "】\n"); // ---------- 10. 上传 ---------- Dictionary dic = new Dictionary(); dic.Add("em_name", "管理员"); dic.Add("em_code", "ADMIN"); dic.Add("caller", "ProductSOP"); OperatResult.AppendText("上传文件【" + imagePath + "】\n"); string fp_id = UploadFilesToRemoteUrl( "https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", imagePath, dic); // ---------- 11. 入库 ---------- string ps_id = dh.getFieldDataByCondition( "ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString(); dh.ExecuteSql( "insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) " + "select ProductSOPdetail_seq.nextval,ps_id,'" + imagename + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert"); } } // ---------- 12. 删除临时工作表 ---------- workbook.Worksheets.RemoveAt(newSheetIndex); imageIndex++; } //} //catch (Exception ex) //{ // OperatResult.AppendText(ex.Message + ex.StackTrace); //} } } } else if (PDF.Checked) { ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".pdf", ""); pr_code_Leave(new object(), new EventArgs()); DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select"); if (dt.Rows.Count == 0) { string code = LogicHandler.GetPiInoutCode("ProductSOP", "1"); ps_code.Text = code; if (VaildDate.Checked) { dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode,ps_vailddate)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING',to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd'))", "insert"); } else { dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman,ps_status,ps_statuscode)values(productsop_seq.nextval,'" + code + "','" + ps_prodcode.Text + "',sysdate,'" + User.UserName + "','在录入','ENTERING')", "insert"); } } else { string psid = dt.Rows[0]["ps_id"].ToString(); dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + psid + "'", "delete"); ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString(); } if (VaildDate.Checked) { dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "',ps_vailddate=to_date('" + DateCode.Value.ToString("yyyy-MM-dd") + "','yyyy-mm-dd') where ps_prodcode='" + ps_prodcode.Text + "'", "update"); } else { dh.ExecuteSql("update ProductSOP set ps_attachsop='',ps_inman='" + User.UserName + "' where ps_prodcode='" + ps_prodcode.Text + "'", "update"); } Dictionary dic = new Dictionary(); dic.Add("em_name", "管理员"); dic.Add("em_code", "ADMIN"); dic.Add("caller", "ProductSOP"); OperatResult.AppendText("上传文件【" + ps_prodcode.Text + "" + "】\n"); string fp_id = UploadFilesToRemoteUrl("https://mes.lihantech.cn/mes/MEScommon/uploadFiles.action?_noc=1", FilePath.Text, dic); string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString(); dh.ExecuteSql("insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) select ProductSOPdetail_seq.nextval,ps_id,'" + ps_prodcode.Text + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert"); } } /// /// 请求上传图片到阿里云 /// /// 上传地址 /// 本地文件路径 /// 上传的数据信息 /// public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary dic) { try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11; ServicePointManager.DefaultConnectionLimit = 50; string boundary = DateTime.Now.Ticks.ToString("x"); byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1); request.Method = "POST"; request.Timeout = 10 * 10000; request.ContentType = "multipart/form-data; boundary=" + boundary; Stream rs = request.GetRequestStream(); var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n"; if (dic != null) { foreach (string key in dic.Keys) { rs.Write(boundarybytes, 0, boundarybytes.Length); string formitem = string.Format(formdataTemplate, key, dic[key]); byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem); rs.Write(formitembytes, 0, formitembytes.Length); } } string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n"; { rs.Write(boundarybytes, 0, boundarybytes.Length); var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath)); var headerbytes = System.Text.Encoding.UTF8.GetBytes(header); rs.Write(headerbytes, 0, headerbytes.Length); using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[1024]; var bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { rs.Write(buffer, 0, bytesRead); } } var cr = Encoding.UTF8.GetBytes("\r\n"); rs.Write(cr, 0, cr.Length); } rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); var response = request.GetResponse() as HttpWebResponse; StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string Content = newReader.ReadToEnd(); Dictionary dic1 = new Dictionary(); List> dic2 = null; dic1 = BaseUtil.ToDictionary(Content); dic2 = dic1["data"] as List>; string fp_id = ""; if (dic2[0]["filepath"] != null) { fp_id = dic2[0]["filepath"].ToString(); } if (response.StatusCode == HttpStatusCode.OK) { return fp_id; } } catch (Exception e) { LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, ""); Console.WriteLine(e.Message + e.StackTrace); } return ""; } private void ChooseFile_Click(object sender, EventArgs e) { ChoosePath.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls|(*.pdf)|*.pdf"; DialogResult result = ChoosePath.ShowDialog(); if (result == DialogResult.OK) { FilePath.Text = ChoosePath.FileName; } } private void UploadSOP_Click(object sender, EventArgs e) { Thread thread = new Thread(uploadfile); SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件"); stw.StartPosition = FormStartPosition.CenterScreen; stw.ShowDialog(); if (JPG.Checked) { LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, ""); } else { LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, ""); } } private void OperatResult_TextChanged(object sender, EventArgs e) { //OperatResult.SelectionStart = Text.Length; OperatResult.ScrollToCaret(); } private void SendSop_Click(object sender, EventArgs e) { try { if (ps_prodcode.Text == "") { MessageBox.Show("线别和SOP文档不能为空"); return; } if (SendDGV.Rows.Count > 0) { List> listr = new List>(); JavaScriptSerializer jss = new JavaScriptSerializer(); Dictionary map1 = new Dictionary(); Dictionary map = new Dictionary(); string path; string pathroot = dh.GetConfig("filePathUrl", "sys").ToString(); dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE,sr_releaseman,sr_readman)" + "select soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "','" + User.UserName + "',em_code from employee ", "insert"); LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, ""); MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功"); } else { MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档"); LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, ""); } } catch (Exception ex) { LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, ""); Console.WriteLine(ex.Message + ex.StackTrace); } } public string encryptBASE64(string key) { Console.WriteLine(key); byte[] bytes = Encoding.Default.GetBytes(key); return Convert.ToBase64String(bytes); } public static string EncodeBase64(string code_type, string code) { string encode = ""; byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code); try { encode = Convert.ToBase64String(bytes); } catch { encode = code; } return encode; } private void pr_code_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { LoadPrCode(); } } private BindingSource bs = new BindingSource(); // 类成员变量 private void LoadPrCode() { DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select"); if (dt.Rows.Count > 0) { string ps_id = dt.Rows[0]["ps_id"].ToString(); dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey from ProductSOPdetail left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1) where psd_psid=" + ps_id, "select"); if (dt.Rows.Count > 0) { // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用) if (SendDGV.InvokeRequired) SendDGV.Invoke(new Action(() => BindData(dt))); else BindData(dt); } } } private void BindData(DataTable dt) { // 使用 BindingSource 避免直接置 null if (SendDGV.DataSource == null) { bs.DataSource = dt; SendDGV.DataSource = bs; } else { bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态 } // 可选:刷新显示 SendDGV.Refresh(); } private void pr_code_Leave(object sender, EventArgs e) { //LoadPrCode(); } bool AllChecked = false; private void ChooseALL_Click(object sender, EventArgs e) { if (AllChecked) { foreach (DataGridViewRow dr in SendDGV.Rows) dr.Cells[0].Value = false; AllChecked = false; } else { foreach (DataGridViewRow dr in SendDGV.Rows) dr.Cells[0].Value = true; AllChecked = true; } } private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e) { LoadPrCode(); } private void GetSOP_Click(object sender, EventArgs e) { LoadPrCode(); } private void ChoosePrint_Click(object sender, EventArgs e) { ChoosePath.Filter = "(*.png)|*.png"; DialogResult result = ChoosePath.ShowDialog(); if (result == DialogResult.OK) { PrintPath.Text = ChoosePath.FileName; } } private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) return; } } }