Query_SOP.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Windows.Forms;
  5. using System.Net;
  6. using System.Collections.Generic;
  7. using System.Threading;
  8. using System.Data;
  9. using System.Drawing.Imaging;
  10. using System.Drawing;
  11. using UAS_MES_NEW.Entity;
  12. using UAS_MES_NEW.PublicMethod;
  13. using Aspose.Cells;
  14. using UAS_MES_NEW.DataOperate;
  15. using UAS_MES_NEW.PublicForm;
  16. using Aspose.Cells.Drawing;
  17. using Aspose.Cells.Rendering;
  18. using System.Web.Script.Serialization;
  19. namespace UAS_MES_NEW.Query
  20. {
  21. public partial class Query_SOP : Form
  22. {
  23. DataHelper dh;
  24. string usercode;
  25. string sourcecode;
  26. DataTable Dbfind;
  27. public Query_SOP()
  28. {
  29. usercode = "";
  30. sourcecode = "";
  31. InitializeComponent();
  32. }
  33. private void Form3_Load(object sender, EventArgs e)
  34. {
  35. CheckForIllegalCrossThreadCalls = false;
  36. ps_prodcode.TableName = "productsop";
  37. ps_prodcode.SelectField = "ps_code # 流水号,ps_prodcode # SOP编号";
  38. ps_prodcode.FormName = Name;
  39. ps_prodcode.DBTitle = "SOP查询";
  40. ps_prodcode.SetValueField = new string[] { "ps_code", "ps_prodcode" };
  41. ps_prodcode.Condition = "";
  42. ps_prodcode.DbChange += nr_rule_DBChange;
  43. dh = SystemInf.dh;
  44. }
  45. private void nr_rule_DBChange(object sender, EventArgs e)
  46. {
  47. Dbfind = ps_prodcode.ReturnData;
  48. BaseUtil.SetFormValue(this.Controls, Dbfind);
  49. }
  50. void uploadfile()
  51. {
  52. if (FilePath.Text == "")
  53. {
  54. MessageBox.Show("文件不能为空!");
  55. return;
  56. }
  57. ps_prodcode.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", "");
  58. pr_code_Leave(new object(), new EventArgs());
  59. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "' ", "select");
  60. if (dt.Rows.Count == 0)
  61. {
  62. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  63. ps_code.Text = code;
  64. 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,'" + usercode + "','在录入','ENTERING')", "insert");
  65. }
  66. else
  67. {
  68. string ps_id = dt.Rows[0]["ps_id"].ToString();
  69. dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + ps_id + "'", "delete");
  70. ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
  71. }
  72. Workbook workbook = new Workbook(FilePath.Text);
  73. List<Worksheet> list = new List<Worksheet>();
  74. List<string> filename = new List<string>();
  75. dh.ExecuteSql("update ProductSOP set ps_attachsop='' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
  76. OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
  77. for (int i = 0; i < workbook.Worksheets.Count; i++)
  78. {
  79. if (workbook.Worksheets[i].Name != "物料清单")
  80. {
  81. OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
  82. string path = Application.StartupPath + @"\" + ps_prodcode.Text + @"\";
  83. Worksheet she = workbook.Worksheets[i];
  84. if (JPG.Checked)
  85. {
  86. try
  87. {
  88. if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
  89. {
  90. Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
  91. }
  92. string sheetname = she.Name;
  93. // 获取工作表中的所有图片
  94. List<Picture> pictures = new List<Picture>();
  95. foreach (Aspose.Cells.Drawing.Picture picture in she.Pictures)
  96. {
  97. pictures.Add(picture);
  98. }
  99. // 获取使用的行数
  100. int totalRows = she.Cells.MaxDataRow + 1;
  101. int imageIndex = 1;
  102. // 每40行生成一张图片
  103. for (int startRow = 0; startRow < totalRows; startRow += 40)
  104. {
  105. int endRow = Math.Min(startRow + 39, totalRows - 1);
  106. // 创建图片选项
  107. ImageOrPrintOptions options = new ImageOrPrintOptions();
  108. options.ImageFormat = ImageFormat.Png;
  109. options.OnePagePerSheet = false;
  110. options.PrintingPage = PrintingPageType.IgnoreBlank;
  111. she.PageSetup.PrintArea = $"A{startRow + 1}:AH{endRow + 1}";
  112. if (File.Exists(PrintPath.Text))
  113. {
  114. //she.Pictures.Add(int.Parse(X.Value.ToString()), int.Parse(Y.Value.ToString()), PrintPath.Text);
  115. she.Pictures.Add(startRow + int.Parse(Y.Value.ToString()), int.Parse(X.Value.ToString()), PrintPath.Text);
  116. }
  117. // 创建SheetRender对象
  118. SheetRender sr = new SheetRender(she, options);
  119. string imagename = $"{she.Name}_{imageIndex}.png";
  120. // 获取渲染后的图像
  121. Bitmap bitmap = sr.ToImage(0);
  122. string imagePath = "";
  123. // 如果有图片在当前行范围内,将它们添加到最终图像中
  124. if (pictures.Count > 0)
  125. {
  126. using (Bitmap finalImage = new Bitmap(bitmap.Width, bitmap.Height))
  127. using (Graphics g = Graphics.FromImage(finalImage))
  128. {
  129. // 绘制Excel内容
  130. g.DrawImage(bitmap, 0, 0);
  131. // 绘制原始Excel中的图片
  132. int yOffset = bitmap.Height;
  133. // 保存图像
  134. imagePath = Path.Combine(path, $"{she.Name}_{imageIndex}.png");
  135. finalImage.Save(imagePath, ImageFormat.Png);
  136. Console.WriteLine($"Saved: {imagePath}");
  137. }
  138. }
  139. else
  140. {
  141. // 如果没有图片,直接保存渲染的图像
  142. imagePath = Path.Combine(path, $"{she.Name}_{imageIndex}.png");
  143. bitmap.Save(imagePath, ImageFormat.Png);
  144. Console.WriteLine($"Saved: {imagePath}");
  145. }
  146. imageIndex++;
  147. OperatResult.AppendText("解析图片【" + imagePath + ".jpg】" + "\n");
  148. Dictionary<string, object> dic = new Dictionary<string, object>();
  149. dic.Add("em_name", "管理员");
  150. dic.Add("em_code", "ADMIN");
  151. dic.Add("caller", "ProductSOP");
  152. OperatResult.AppendText("上传文件【" + imagePath + ".jpg" + "】\n");
  153. string fp_id = UploadFilesToRemoteUrl("http://119.147.24.169:8099/mes/MEScommon/uploadFiles.action?_noc=1", Application.StartupPath + @"\" + ps_prodcode.Text + @"\" + imagename, dic);
  154. string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString();
  155. 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");
  156. }
  157. }
  158. catch (Exception ex)
  159. {
  160. OperatResult.AppendText(ex.Message + ex.StackTrace);
  161. }
  162. filename.Add(she.Name + ".jpg");
  163. }
  164. }
  165. }
  166. }
  167. /// <summary>
  168. /// 请求上传图片到阿里云
  169. /// </summary>
  170. /// <param name="url">上传地址</param>
  171. /// <param name="filepath">本地文件路径</param>
  172. /// <param name="dic">上传的数据信息</param>
  173. /// <returns></returns>
  174. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  175. {
  176. try
  177. {
  178. ServicePointManager.DefaultConnectionLimit = 50;
  179. string boundary = DateTime.Now.Ticks.ToString("x");
  180. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  181. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  182. request.Method = "POST";
  183. request.Timeout = 10 * 10000;
  184. request.ContentType = "multipart/form-data; boundary=" + boundary;
  185. Stream rs = request.GetRequestStream();
  186. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  187. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  188. if (dic != null)
  189. {
  190. foreach (string key in dic.Keys)
  191. {
  192. rs.Write(boundarybytes, 0, boundarybytes.Length);
  193. string formitem = string.Format(formdataTemplate, key, dic[key]);
  194. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  195. rs.Write(formitembytes, 0, formitembytes.Length);
  196. }
  197. }
  198. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  199. {
  200. rs.Write(boundarybytes, 0, boundarybytes.Length);
  201. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  202. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  203. rs.Write(headerbytes, 0, headerbytes.Length);
  204. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  205. {
  206. var buffer = new byte[1024];
  207. var bytesRead = 0;
  208. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  209. {
  210. rs.Write(buffer, 0, bytesRead);
  211. }
  212. }
  213. var cr = Encoding.UTF8.GetBytes("\r\n");
  214. rs.Write(cr, 0, cr.Length);
  215. }
  216. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  217. var response = request.GetResponse() as HttpWebResponse;
  218. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  219. string Content = newReader.ReadToEnd();
  220. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  221. List<Dictionary<string, object>> dic2 = null;
  222. dic1 = BaseUtil.ToDictionary(Content);
  223. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  224. string fp_id = "";
  225. if (dic2[0]["filepath"] != null)
  226. {
  227. fp_id = dic2[0]["filepath"].ToString();
  228. }
  229. if (response.StatusCode == HttpStatusCode.OK)
  230. {
  231. return fp_id;
  232. }
  233. }
  234. catch (Exception e)
  235. {
  236. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", ps_prodcode.Text, "");
  237. Console.WriteLine(e.Message + e.StackTrace);
  238. }
  239. return "";
  240. }
  241. private void ChooseFile_Click(object sender, EventArgs e)
  242. {
  243. ChoosePath.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
  244. DialogResult result = ChoosePath.ShowDialog();
  245. if (result == DialogResult.OK)
  246. {
  247. FilePath.Text = ChoosePath.FileName;
  248. }
  249. }
  250. private void UploadSOP_Click(object sender, EventArgs e)
  251. {
  252. Thread thread = new Thread(uploadfile);
  253. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  254. stw.StartPosition = FormStartPosition.CenterScreen;
  255. stw.ShowDialog();
  256. if (JPG.Checked)
  257. {
  258. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", ps_prodcode.Text, "");
  259. }
  260. else
  261. {
  262. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
  263. }
  264. }
  265. private void OperatResult_TextChanged(object sender, EventArgs e)
  266. {
  267. //OperatResult.SelectionStart = Text.Length;
  268. OperatResult.ScrollToCaret();
  269. }
  270. private void SendSop_Click(object sender, EventArgs e)
  271. {
  272. try
  273. {
  274. if (ps_prodcode.Text == "")
  275. {
  276. MessageBox.Show("线别和SOP文档不能为空");
  277. return;
  278. }
  279. if (SendDGV.Rows.Count > 0)
  280. {
  281. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  282. JavaScriptSerializer jss = new JavaScriptSerializer();
  283. Dictionary<string, object> map1 = new Dictionary<string, object>();
  284. Dictionary<string, object> map = new Dictionary<string, object>();
  285. string path;
  286. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  287. dh.ExecuteSql("insert into soprelease(SR_ID, sr_pscode, SR_STATUS, SR_MACHINETYPE)" +
  288. "values(soprelease_seq.nextval,'" + ps_code.Text + "',0,'" + ps_prodcode.Text + "') ", "insert");
  289. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
  290. MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
  291. }
  292. else
  293. {
  294. MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
  295. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
  296. }
  297. }
  298. catch (Exception ex)
  299. {
  300. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
  301. Console.WriteLine(ex.Message + ex.StackTrace);
  302. }
  303. }
  304. public string encryptBASE64(string key)
  305. {
  306. Console.WriteLine(key);
  307. byte[] bytes = Encoding.Default.GetBytes(key);
  308. return Convert.ToBase64String(bytes);
  309. }
  310. public static string EncodeBase64(string code_type, string code)
  311. {
  312. string encode = "";
  313. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  314. try
  315. {
  316. encode = Convert.ToBase64String(bytes);
  317. }
  318. catch
  319. {
  320. encode = code;
  321. }
  322. return encode;
  323. }
  324. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  325. {
  326. if (e.KeyCode == Keys.Enter)
  327. {
  328. LoadPrCode();
  329. }
  330. }
  331. private BindingSource bs = new BindingSource(); // 类成员变量
  332. private void LoadPrCode()
  333. {
  334. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
  335. if (dt.Rows.Count > 0)
  336. {
  337. string ps_id = dt.Rows[0]["ps_id"].ToString();
  338. dt = (DataTable)dh.ExecuteSql(@"select fp_name,fp_path,'' issend,psd_iskey
  339. from ProductSOPdetail
  340. left join filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1)
  341. where psd_psid=" + ps_id, "select");
  342. if (dt.Rows.Count > 0)
  343. {
  344. // 在 UI 线程安全执行(如果已经在 UI 线程则直接调用)
  345. if (SendDGV.InvokeRequired)
  346. SendDGV.Invoke(new Action(() => BindData(dt)));
  347. else
  348. BindData(dt);
  349. }
  350. }
  351. }
  352. private void BindData(DataTable dt)
  353. {
  354. // 使用 BindingSource 避免直接置 null
  355. if (SendDGV.DataSource == null)
  356. {
  357. bs.DataSource = dt;
  358. SendDGV.DataSource = bs;
  359. }
  360. else
  361. {
  362. bs.DataSource = dt; // 直接替换内部数据,控件不会经历“无数据”状态
  363. }
  364. // 可选:刷新显示
  365. SendDGV.Refresh();
  366. }
  367. private void pr_code_Leave(object sender, EventArgs e)
  368. {
  369. //LoadPrCode();
  370. }
  371. bool AllChecked = false;
  372. private void ChooseALL_Click(object sender, EventArgs e)
  373. {
  374. if (AllChecked)
  375. {
  376. foreach (DataGridViewRow dr in SendDGV.Rows)
  377. dr.Cells[0].Value = false;
  378. AllChecked = false;
  379. }
  380. else
  381. {
  382. foreach (DataGridViewRow dr in SendDGV.Rows)
  383. dr.Cells[0].Value = true;
  384. AllChecked = true;
  385. }
  386. }
  387. private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
  388. {
  389. LoadPrCode();
  390. }
  391. private void GetSOP_Click(object sender, EventArgs e)
  392. {
  393. LoadPrCode();
  394. }
  395. private void ChoosePrint_Click(object sender, EventArgs e)
  396. {
  397. ChoosePath.Filter = "(*.png)|*.png";
  398. DialogResult result = ChoosePath.ShowDialog();
  399. if (result == DialogResult.OK)
  400. {
  401. PrintPath.Text = ChoosePath.FileName;
  402. }
  403. }
  404. private void SendDGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
  405. {
  406. if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
  407. }
  408. }
  409. }