Query_SOP.cs 20 KB

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