Query_SOP.cs 20 KB

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