Query_SOP.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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.Net.Sockets;
  9. using System.Data;
  10. using UAS_MES_NEW.DataOperate;
  11. using UAS_MES_NEW.PublicMethod;
  12. using Aspose.Cells;
  13. using Aspose.Cells.Drawing;
  14. using Aspose.Cells.Rendering;
  15. using UAS_MES_NEW.PublicForm;
  16. using System.Web.Script.Serialization;
  17. using System.Drawing.Imaging;
  18. namespace UAS_MES_NEW.Query
  19. {
  20. public partial class Query_SOP : Form
  21. {
  22. DataHelper dh = new DataHelper();
  23. string usercode;
  24. string sourcecode;
  25. public Query_SOP()
  26. {
  27. InitializeComponent();
  28. }
  29. public Query_SOP(string iUserCode, string iSource)
  30. {
  31. usercode = iUserCode;
  32. sourcecode = iSource;
  33. InitializeComponent();
  34. }
  35. private void Form3_Load(object sender, EventArgs e)
  36. {
  37. CheckForIllegalCrossThreadCalls = false;
  38. }
  39. void uploadfile()
  40. {
  41. pr_code.Text = FilePath.Text.Substring(FilePath.Text.LastIndexOf(@"\") + 1).Replace(".xls", "").Replace(".xlsx", "");
  42. pr_code_Leave(new object(), new EventArgs());
  43. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where instr('" + pr_code.Text + "',ps_prodcode)>0 ", "select");
  44. if (dt.Rows.Count == 0)
  45. {
  46. DataTable dt1 = (DataTable)dh.ExecuteSql("select pr_code from product where instr('" + pr_code.Text + "',pr_code)>0", "select");
  47. if (dt1.Rows.Count > 0)
  48. {
  49. string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
  50. pr_code.Text = dt1.Rows[0]["pr_code"].ToString();
  51. dh.ExecuteSql("insert into productsop(ps_id,ps_code,ps_prodcode,ps_indate,ps_inman)values(productsop_seq.nextval,'" + code + "','" + pr_code.Text + "',sysdate,'" + usercode + "')", "insert");
  52. }
  53. else
  54. {
  55. MessageBox.Show("产品编号" + pr_code.Text + "不存在");
  56. return;
  57. }
  58. }
  59. else
  60. {
  61. pr_code.Text = dt.Rows[0]["ps_prodcode"].ToString();
  62. }
  63. string dir = Application.StartupPath + @"\" + pr_code.Text;
  64. if (!Directory.Exists(dir))
  65. {
  66. Directory.CreateDirectory(dir);
  67. }
  68. // 使用Aspose.Cells加载Excel文件
  69. Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(FilePath.Text);
  70. int total = workbook.Worksheets.Count;
  71. dh.ExecuteSql("update ProductSOP set ps_attachsop='' where ps_prodcode='" + pr_code.Text + "'", "update");
  72. OperatResult.AppendText("一共Sheet: " + total + "\n");
  73. //串行处理每个Sheet,避免并发导致缺页
  74. List<string> successIds = new List<string>();
  75. List<string> failedSheets = new List<string>();
  76. for (int i = 0; i < total; i++)
  77. {
  78. Worksheet sheet = workbook.Worksheets[i];
  79. string sheetName = sheet.Name;
  80. OperatResult.AppendText("[" + (i + 1) + "/" + total + "] 处理Sheet: " + sheetName + "\n");
  81. try
  82. {
  83. //处理TextBox(放大文字×2,居中对齐)
  84. for (int k = 0; k < sheet.TextBoxes.Count; k++)
  85. {
  86. Aspose.Cells.Drawing.TextBox tb = sheet.TextBoxes[k];
  87. if (tb.Text != null && tb.Text.Length > 1)
  88. {
  89. tb.Text = tb.Text;
  90. tb.Width = tb.Width * 2;
  91. tb.Height = tb.Height * 2;
  92. tb.TextHorizontalAlignment = TextAlignmentType.Center;
  93. }
  94. }
  95. string fp_id = "";
  96. if (JPG.Checked)
  97. {
  98. fp_id = SaveFileToJPG(sheet, dir);
  99. }
  100. else
  101. {
  102. fp_id = SaveFileToPDF(sheet, dir);
  103. }
  104. if (fp_id != "")
  105. {
  106. successIds.Add(fp_id);
  107. OperatResult.AppendText(" -> 成功, fp_id=" + fp_id + "\n");
  108. }
  109. else
  110. {
  111. failedSheets.Add(sheetName);
  112. OperatResult.AppendText(" -> 失败\n");
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. failedSheets.Add(sheetName);
  118. OperatResult.AppendText(" -> 异常: " + ex.Message + "\n");
  119. }
  120. }
  121. //所有Sheet处理完成后,一次性拼接fp_id写入数据库
  122. if (successIds.Count > 0)
  123. {
  124. string idList = "";
  125. foreach (string id in successIds)
  126. {
  127. idList += id + ";";
  128. }
  129. dh.ExecuteSql("update ProductSOP set ps_attachsop='" + idList + "' where ps_prodcode='" + pr_code.Text + "'", "update");
  130. OperatResult.AppendText("已写入" + successIds.Count + "个文件到ProductSOP\n");
  131. }
  132. if (failedSheets.Count > 0)
  133. {
  134. string msg = "以下Sheet上传失败,可能缺页:\n" + string.Join(", ", failedSheets.ToArray());
  135. OperatResult.AppendText(msg + "\n");
  136. MessageBox.Show(msg, "上传部分失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  137. }
  138. else
  139. {
  140. OperatResult.AppendText("全部" + total + "个Sheet上传成功\n");
  141. }
  142. }
  143. /// <summary>
  144. /// 使用Aspose.Cells SheetRender将sheet转换为JPG图片并上传
  145. /// </summary>
  146. private string SaveFileToJPG(Worksheet sheet, string dir)
  147. {
  148. string fp_id = "";
  149. string filePath = dir + @"\" + sheet.Name + ".jpg";
  150. //图片只添加一次(放在重试循环外,避免重试时重复添加)
  151. try
  152. {
  153. //电子受控章:第20列,Y偏移20像素
  154. int picIdx1 = sheet.Pictures.Add(0, 20, @"图片\电子受控章.png");
  155. Picture pic1 = sheet.Pictures[picIdx1];
  156. pic1.Width = 113;
  157. pic1.Height = 38;
  158. pic1.UpperDeltaY = 20;
  159. //签名:第15列,Y偏移600像素
  160. int picIdx2 = sheet.Pictures.Add(0, 15, @"图片\签名.png");
  161. Picture pic2 = sheet.Pictures[picIdx2];
  162. pic2.Width = 100;
  163. pic2.Height = 38;
  164. pic2.UpperDeltaY = 600;
  165. }
  166. catch (Exception ex)
  167. {
  168. OperatResult.AppendText("添加图片异常: " + ex.Message + "\n");
  169. }
  170. //转换为图片并上传(失败重试2次)
  171. for (int retry = 0; retry < 2; retry++)
  172. {
  173. try
  174. {
  175. //使用SheetRender转图片,Aspose.Cells的渲染引擎比Spire.XLS更稳定
  176. ImageOrPrintOptions options = new ImageOrPrintOptions();
  177. options.ImageFormat = ImageFormat.Jpeg;
  178. options.Quality = 85;
  179. options.OnePagePerSheet = true;
  180. SheetRender sr = new SheetRender(sheet, options);
  181. if (sr.PageCount > 0)
  182. {
  183. sr.ToImage(0, filePath);
  184. }
  185. OperatResult.AppendText("解析图片【" + sheet.Name + ".jpg】\n");
  186. fp_id = UploadFile(filePath, sheet.Name + ".jpg");
  187. if (fp_id != "")
  188. {
  189. break;
  190. }
  191. if (retry == 0)
  192. {
  193. OperatResult.AppendText("首次上传失败,重试中...\n");
  194. }
  195. }
  196. catch (Exception ex)
  197. {
  198. OperatResult.AppendText("SaveFileToJPG异常: " + ex.Message + (retry == 0 ? " 重试中..." : "") + "\n");
  199. }
  200. }
  201. return fp_id;
  202. }
  203. /// <summary>
  204. /// 使用Aspose.Cells将sheet转换为PDF并上传
  205. /// </summary>
  206. private string SaveFileToPDF(Worksheet sheet, string dir)
  207. {
  208. string fp_id = "";
  209. string filePath = dir + @"\" + sheet.Name + ".pdf";
  210. for (int retry = 0; retry < 2; retry++)
  211. {
  212. try
  213. {
  214. //创建只含1个sheet的独立workbook,Copy复制当前sheet内容
  215. Aspose.Cells.Workbook singleWb = new Aspose.Cells.Workbook();
  216. singleWb.Worksheets[0].Copy(sheet);
  217. singleWb.Save(filePath, SaveFormat.Pdf);
  218. OperatResult.AppendText("解析PDF【" + sheet.Name + ".pdf】\n");
  219. fp_id = UploadFile(filePath, sheet.Name + ".pdf");
  220. if (fp_id != "")
  221. {
  222. break;
  223. }
  224. if (retry == 0)
  225. {
  226. OperatResult.AppendText("首次上传失败,重试中...\n");
  227. }
  228. }
  229. catch (Exception ex)
  230. {
  231. OperatResult.AppendText("SaveFileToPDF异常: " + ex.Message + (retry == 0 ? " 重试中..." : "") + "\n");
  232. }
  233. }
  234. return fp_id;
  235. }
  236. /// <summary>
  237. /// 上传文件到服务器
  238. /// </summary>
  239. private string UploadFile(string filePath, string fileName)
  240. {
  241. Dictionary<string, object> dic = new Dictionary<string, object>();
  242. dic.Add("em_name", "管理员");
  243. dic.Add("em_code", "ADMIN");
  244. dic.Add("caller", "ProductSOP");
  245. OperatResult.AppendText("上传文件【" + fileName + "】\n");
  246. return UploadFilesToRemoteUrl("http://erp.ubtob.net:11773/mes/MEScommon/uploadFiles.action?_noc=1", filePath, dic);
  247. }
  248. /// <summary>
  249. /// 请求上传图片到阿里云
  250. /// </summary>
  251. /// <param name="url">上传地址</param>
  252. /// <param name="filepath">本地文件路径</param>
  253. /// <param name="dic">上传的数据信息</param>
  254. /// <returns></returns>
  255. public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
  256. {
  257. try
  258. {
  259. ServicePointManager.DefaultConnectionLimit = 50;
  260. string boundary = DateTime.Now.Ticks.ToString("x");
  261. byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
  262. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
  263. request.Method = "POST";
  264. request.Timeout = 10 * 10000;
  265. request.ContentType = "multipart/form-data; boundary=" + boundary;
  266. Stream rs = request.GetRequestStream();
  267. var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
  268. string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
  269. if (dic != null)
  270. {
  271. foreach (string key in dic.Keys)
  272. {
  273. rs.Write(boundarybytes, 0, boundarybytes.Length);
  274. string formitem = string.Format(formdataTemplate, key, dic[key]);
  275. byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
  276. rs.Write(formitembytes, 0, formitembytes.Length);
  277. }
  278. }
  279. string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
  280. {
  281. rs.Write(boundarybytes, 0, boundarybytes.Length);
  282. var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
  283. var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
  284. rs.Write(headerbytes, 0, headerbytes.Length);
  285. using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
  286. {
  287. var buffer = new byte[1024];
  288. var bytesRead = 0;
  289. while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
  290. {
  291. rs.Write(buffer, 0, bytesRead);
  292. }
  293. }
  294. var cr = Encoding.UTF8.GetBytes("\r\n");
  295. rs.Write(cr, 0, cr.Length);
  296. }
  297. rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  298. var response = request.GetResponse() as HttpWebResponse;
  299. StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  300. string Content = newReader.ReadToEnd();
  301. Dictionary<string, object> dic1 = new Dictionary<string, object>();
  302. List<Dictionary<string, object>> dic2 = null;
  303. dic1 = BaseUtil.ToDictionary(Content);
  304. dic2 = dic1["data"] as List<Dictionary<string, object>>;
  305. string fp_id = "";
  306. if (dic2[0]["filepath"] != null)
  307. {
  308. fp_id = dic2[0]["filepath"].ToString();
  309. }
  310. if (response.StatusCode == HttpStatusCode.OK)
  311. {
  312. return fp_id;
  313. }
  314. }
  315. catch (Exception e)
  316. {
  317. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP", "上传失败", pr_code.Text, "");
  318. Console.WriteLine(e.Message + e.StackTrace);
  319. }
  320. return "";
  321. }
  322. private void ChooseFile_Click(object sender, EventArgs e)
  323. {
  324. ChoosePath.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
  325. DialogResult result = ChoosePath.ShowDialog();
  326. if (result == DialogResult.OK)
  327. {
  328. FilePath.Text = ChoosePath.FileName;
  329. }
  330. }
  331. private void UploadSOP_Click(object sender, EventArgs e)
  332. {
  333. Thread thread = new Thread(uploadfile);
  334. SetLoadingWindow stw = new SetLoadingWindow(thread, "上传文件");
  335. stw.StartPosition = FormStartPosition.CenterScreen;
  336. stw.ShowDialog();
  337. if (JPG.Checked)
  338. {
  339. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【图片格式】", "上传成功", pr_code.Text, "");
  340. }
  341. else
  342. {
  343. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", pr_code.Text, "");
  344. }
  345. }
  346. private void OperatResult_TextChanged(object sender, EventArgs e)
  347. {
  348. //OperatResult.SelectionStart = Text.Length;
  349. OperatResult.ScrollToCaret();
  350. }
  351. TcpServer tcpserver = new TcpServer();
  352. private void SendSop_Click(object sender, EventArgs e)
  353. {
  354. try
  355. {
  356. IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
  357. string IPAddress = "";
  358. for (int i = 0; i < IpEntry.AddressList.Length; i++)
  359. {
  360. if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
  361. {
  362. IPAddress = IpEntry.AddressList[i].ToString();
  363. }
  364. }
  365. dh.ExecuteSql("update SOPSOURCE set SS_BRDIP='" + IPAddress + "'", "update");
  366. DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + pr_code.Text + "'", "select");
  367. if (dt.Rows.Count > 0)
  368. {
  369. tcpserver.Start();
  370. Thread.Sleep(5000);
  371. List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
  372. string PS_ATTACHSOP = dt.Rows[0]["PS_ATTACHSOP"].ToString();
  373. PS_ATTACHSOP = PS_ATTACHSOP.Substring(0, PS_ATTACHSOP.Length - 1).Replace(";", ",");
  374. dt = (DataTable)dh.ExecuteSql("select fp_path, fp_name from filepath where fp_id in (" + PS_ATTACHSOP + ") and nvl(fp_path, ' ') <> ' '", "select");
  375. JavaScriptSerializer jss = new JavaScriptSerializer();
  376. Dictionary<string, object> map1 = new Dictionary<string, object>();
  377. Dictionary<string, object> map = new Dictionary<string, object>();
  378. string path;
  379. string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
  380. for (int i = 0; i < dt.Rows.Count; i++)
  381. {
  382. Dictionary<string, string> dic1 = new Dictionary<string, string>();
  383. path = dt.Rows[i]["fp_path"].ToString();
  384. path = encryptBASE64(path.Replace("/app/uas/webapps/postattach", pathroot)).Replace("\\s*|\r|\n|\t", "");
  385. dic1.Add("path", path);
  386. dic1.Add("filename", dt.Rows[i]["fp_name"].ToString().Replace(" ", "").Replace("(", "").Replace(")", ""));
  387. dic1.Add("ps_prodcode", pr_code.Text);
  388. listr.Add(dic1);
  389. }
  390. map1.Add("ps_code", "");
  391. map1.Add("url", listr);
  392. map.Add("success", true);
  393. map.Add("data", map1);
  394. tcpserver.Send(jss.Serialize(map));
  395. tcpserver.Stop();
  396. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", pr_code.Text, "");
  397. MessageBox.Show("产品编号" + pr_code.Text + "广播成功");
  398. }
  399. else
  400. {
  401. MessageBox.Show("产品编号" + pr_code.Text + "未维护SOP文档");
  402. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", pr_code.Text, "");
  403. }
  404. }
  405. catch (Exception ex)
  406. {
  407. LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", pr_code.Text, "");
  408. Console.WriteLine(ex.Message + ex.StackTrace);
  409. }
  410. }
  411. public string encryptBASE64(string key)
  412. {
  413. byte[] bytes = Encoding.Default.GetBytes(key);
  414. return Convert.ToBase64String(bytes);
  415. }
  416. public static string EncodeBase64(string code_type, string code)
  417. {
  418. string encode = "";
  419. byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code);
  420. try
  421. {
  422. encode = Convert.ToBase64String(bytes);
  423. }
  424. catch
  425. {
  426. encode = code;
  427. }
  428. return encode;
  429. }
  430. private void pr_code_KeyDown(object sender, KeyEventArgs e)
  431. {
  432. if (e.KeyCode == Keys.Enter)
  433. {
  434. LoadPrCode();
  435. }
  436. }
  437. private void LoadPrCode()
  438. {
  439. DataTable dt = (DataTable)dh.ExecuteSql("select pr_code,pr_spec,pr_detail from product where instr('" + pr_code.Text + "',pr_code)>0", "select");
  440. if (dt.Rows.Count > 0)
  441. {
  442. pr_spec.Clear();
  443. pr_spec.AppendText(dt.Rows[0]["pr_spec"].ToString());
  444. pr_detail.Text = dt.Rows[0]["pr_detail"].ToString();
  445. pr_code.Text = dt.Rows[0]["pr_code"].ToString();
  446. }
  447. else
  448. {
  449. MessageBox.Show("产品编号" + pr_code.Text + "不存在");
  450. }
  451. }
  452. private void pr_code_Leave(object sender, EventArgs e)
  453. {
  454. LoadPrCode();
  455. }
  456. private void pr_spec_Click(object sender, EventArgs e)
  457. {
  458. }
  459. }
  460. }