| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520 |
- using System;
- using System.IO;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Collections.Generic;
- using System.Threading;
- using System.Net.Sockets;
- using System.Data;
- using UAS_MES_NEW.DataOperate;
- using UAS_MES_NEW.PublicMethod;
- using Aspose.Cells;
- using Aspose.Cells.Drawing;
- using Aspose.Cells.Rendering;
- using UAS_MES_NEW.PublicForm;
- using System.Web.Script.Serialization;
- using System.Drawing.Imaging;
- namespace UAS_MES_NEW.Query
- {
- public partial class Query_SOP : Form
- {
- DataHelper dh = new DataHelper();
- string usercode;
- string sourcecode;
- public Query_SOP()
- {
- InitializeComponent();
- }
- public Query_SOP(string iUserCode, string iSource)
- {
- usercode = iUserCode;
- sourcecode = iSource;
- InitializeComponent();
- }
- private void Form3_Load(object sender, EventArgs e)
- {
- CheckForIllegalCrossThreadCalls = false;
- }
- void uploadfile()
- {
- pr_code.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 instr('" + pr_code.Text + "',ps_prodcode)>0 ", "select");
- if (dt.Rows.Count == 0)
- {
- DataTable dt1 = (DataTable)dh.ExecuteSql("select pr_code from product where instr('" + pr_code.Text + "',pr_code)>0", "select");
- if (dt1.Rows.Count > 0)
- {
- string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
- pr_code.Text = dt1.Rows[0]["pr_code"].ToString();
- 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");
- }
- else
- {
- MessageBox.Show("产品编号" + pr_code.Text + "不存在");
- return;
- }
- }
- else
- {
- pr_code.Text = dt.Rows[0]["ps_prodcode"].ToString();
- }
- string dir = Application.StartupPath + @"\" + pr_code.Text;
- if (!Directory.Exists(dir))
- {
- Directory.CreateDirectory(dir);
- }
- // 使用Aspose.Cells加载Excel文件
- Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(FilePath.Text);
- int total = workbook.Worksheets.Count;
- dh.ExecuteSql("update ProductSOP set ps_attachsop='' where ps_prodcode='" + pr_code.Text + "'", "update");
- OperatResult.AppendText("一共Sheet: " + total + "\n");
- //串行处理每个Sheet,避免并发导致缺页
- List<string> successIds = new List<string>();
- List<string> failedSheets = new List<string>();
- for (int i = 0; i < total; i++)
- {
- Worksheet sheet = workbook.Worksheets[i];
- string sheetName = sheet.Name;
- OperatResult.AppendText("[" + (i + 1) + "/" + total + "] 处理Sheet: " + sheetName + "\n");
- try
- {
- //处理TextBox(放大文字×2,居中对齐)
- for (int k = 0; k < sheet.TextBoxes.Count; k++)
- {
- Aspose.Cells.Drawing.TextBox tb = sheet.TextBoxes[k];
- if (tb.Text != null && tb.Text.Length > 1)
- {
- tb.Text = tb.Text;
- tb.Width = tb.Width * 2;
- tb.Height = tb.Height * 2;
- tb.TextHorizontalAlignment = TextAlignmentType.Center;
- }
- }
- string fp_id = "";
- if (JPG.Checked)
- {
- fp_id = SaveFileToJPG(sheet, dir);
- }
- else
- {
- fp_id = SaveFileToPDF(sheet, dir);
- }
- if (fp_id != "")
- {
- successIds.Add(fp_id);
- OperatResult.AppendText(" -> 成功, fp_id=" + fp_id + "\n");
- }
- else
- {
- failedSheets.Add(sheetName);
- OperatResult.AppendText(" -> 失败\n");
- }
- }
- catch (Exception ex)
- {
- failedSheets.Add(sheetName);
- OperatResult.AppendText(" -> 异常: " + ex.Message + "\n");
- }
- }
- //所有Sheet处理完成后,一次性拼接fp_id写入数据库
- if (successIds.Count > 0)
- {
- string idList = "";
- foreach (string id in successIds)
- {
- idList += id + ";";
- }
- dh.ExecuteSql("update ProductSOP set ps_attachsop='" + idList + "' where ps_prodcode='" + pr_code.Text + "'", "update");
- OperatResult.AppendText("已写入" + successIds.Count + "个文件到ProductSOP\n");
- }
- if (failedSheets.Count > 0)
- {
- string msg = "以下Sheet上传失败,可能缺页:\n" + string.Join(", ", failedSheets.ToArray());
- OperatResult.AppendText(msg + "\n");
- MessageBox.Show(msg, "上传部分失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
- }
- else
- {
- OperatResult.AppendText("全部" + total + "个Sheet上传成功\n");
- }
- }
- /// <summary>
- /// 使用Aspose.Cells SheetRender将sheet转换为JPG图片并上传
- /// </summary>
- private string SaveFileToJPG(Worksheet sheet, string dir)
- {
- string fp_id = "";
- string filePath = dir + @"\" + sheet.Name + ".jpg";
- //图片只添加一次(放在重试循环外,避免重试时重复添加)
- try
- {
- //电子受控章:第20列,Y偏移20像素
- int picIdx1 = sheet.Pictures.Add(0, 20, @"图片\电子受控章.png");
- Picture pic1 = sheet.Pictures[picIdx1];
- pic1.Width = 113;
- pic1.Height = 38;
- pic1.UpperDeltaY = 20;
- //签名:第15列,Y偏移600像素
- int picIdx2 = sheet.Pictures.Add(0, 15, @"图片\签名.png");
- Picture pic2 = sheet.Pictures[picIdx2];
- pic2.Width = 100;
- pic2.Height = 38;
- pic2.UpperDeltaY = 600;
- }
- catch (Exception ex)
- {
- OperatResult.AppendText("添加图片异常: " + ex.Message + "\n");
- }
- //转换为图片并上传(失败重试2次)
- for (int retry = 0; retry < 2; retry++)
- {
- try
- {
- //使用SheetRender转图片,Aspose.Cells的渲染引擎比Spire.XLS更稳定
- ImageOrPrintOptions options = new ImageOrPrintOptions();
- options.ImageFormat = ImageFormat.Jpeg;
- options.Quality = 85;
- options.OnePagePerSheet = true;
- SheetRender sr = new SheetRender(sheet, options);
- if (sr.PageCount > 0)
- {
- sr.ToImage(0, filePath);
- }
- OperatResult.AppendText("解析图片【" + sheet.Name + ".jpg】\n");
- fp_id = UploadFile(filePath, sheet.Name + ".jpg");
- if (fp_id != "")
- {
- break;
- }
- if (retry == 0)
- {
- OperatResult.AppendText("首次上传失败,重试中...\n");
- }
- }
- catch (Exception ex)
- {
- OperatResult.AppendText("SaveFileToJPG异常: " + ex.Message + (retry == 0 ? " 重试中..." : "") + "\n");
- }
- }
- return fp_id;
- }
- /// <summary>
- /// 使用Aspose.Cells将sheet转换为PDF并上传
- /// </summary>
- private string SaveFileToPDF(Worksheet sheet, string dir)
- {
- string fp_id = "";
- string filePath = dir + @"\" + sheet.Name + ".pdf";
- for (int retry = 0; retry < 2; retry++)
- {
- try
- {
- //创建只含1个sheet的独立workbook,Copy复制当前sheet内容
- Aspose.Cells.Workbook singleWb = new Aspose.Cells.Workbook();
- singleWb.Worksheets[0].Copy(sheet);
- singleWb.Save(filePath, SaveFormat.Pdf);
- OperatResult.AppendText("解析PDF【" + sheet.Name + ".pdf】\n");
- fp_id = UploadFile(filePath, sheet.Name + ".pdf");
- if (fp_id != "")
- {
- break;
- }
- if (retry == 0)
- {
- OperatResult.AppendText("首次上传失败,重试中...\n");
- }
- }
- catch (Exception ex)
- {
- OperatResult.AppendText("SaveFileToPDF异常: " + ex.Message + (retry == 0 ? " 重试中..." : "") + "\n");
- }
- }
- return fp_id;
- }
- /// <summary>
- /// 上传文件到服务器
- /// </summary>
- private string UploadFile(string filePath, string fileName)
- {
- Dictionary<string, object> dic = new Dictionary<string, object>();
- dic.Add("em_name", "管理员");
- dic.Add("em_code", "ADMIN");
- dic.Add("caller", "ProductSOP");
- OperatResult.AppendText("上传文件【" + fileName + "】\n");
- return UploadFilesToRemoteUrl("http://erp.ubtob.net:11773/mes/MEScommon/uploadFiles.action?_noc=1", filePath, dic);
- }
- /// <summary>
- /// 请求上传图片到阿里云
- /// </summary>
- /// <param name="url">上传地址</param>
- /// <param name="filepath">本地文件路径</param>
- /// <param name="dic">上传的数据信息</param>
- /// <returns></returns>
- public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
- {
- try
- {
- 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<string, object> dic1 = new Dictionary<string, object>();
- List<Dictionary<string, object>> dic2 = null;
- dic1 = BaseUtil.ToDictionary(Content);
- dic2 = dic1["data"] as List<Dictionary<string, object>>;
- 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", "上传失败", pr_code.Text, "");
- Console.WriteLine(e.Message + e.StackTrace);
- }
- return "";
- }
- private void ChooseFile_Click(object sender, EventArgs e)
- {
- ChoosePath.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
- 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【图片格式】", "上传成功", pr_code.Text, "");
- }
- else
- {
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", pr_code.Text, "");
- }
- }
- private void OperatResult_TextChanged(object sender, EventArgs e)
- {
- //OperatResult.SelectionStart = Text.Length;
- OperatResult.ScrollToCaret();
- }
- TcpServer tcpserver = new TcpServer();
- private void SendSop_Click(object sender, EventArgs e)
- {
- try
- {
- IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName());
- string IPAddress = "";
- for (int i = 0; i < IpEntry.AddressList.Length; i++)
- {
- if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
- {
- IPAddress = IpEntry.AddressList[i].ToString();
- }
- }
- dh.ExecuteSql("update SOPSOURCE set SS_BRDIP='" + IPAddress + "'", "update");
- DataTable dt = (DataTable)dh.ExecuteSql("select * from productsop where ps_prodcode='" + pr_code.Text + "'", "select");
- if (dt.Rows.Count > 0)
- {
- tcpserver.Start();
- Thread.Sleep(5000);
- List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
- string PS_ATTACHSOP = dt.Rows[0]["PS_ATTACHSOP"].ToString();
- PS_ATTACHSOP = PS_ATTACHSOP.Substring(0, PS_ATTACHSOP.Length - 1).Replace(";", ",");
- dt = (DataTable)dh.ExecuteSql("select fp_path, fp_name from filepath where fp_id in (" + PS_ATTACHSOP + ") and nvl(fp_path, ' ') <> ' '", "select");
- JavaScriptSerializer jss = new JavaScriptSerializer();
- Dictionary<string, object> map1 = new Dictionary<string, object>();
- Dictionary<string, object> map = new Dictionary<string, object>();
- string path;
- string pathroot = dh.GetConfig("filePathUrl", "sys").ToString();
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- Dictionary<string, string> dic1 = new Dictionary<string, string>();
- path = dt.Rows[i]["fp_path"].ToString();
- path = encryptBASE64(path.Replace("/app/uas/webapps/postattach", pathroot)).Replace("\\s*|\r|\n|\t", "");
- dic1.Add("path", path);
- dic1.Add("filename", dt.Rows[i]["fp_name"].ToString().Replace(" ", "").Replace("(", "").Replace(")", ""));
- dic1.Add("ps_prodcode", pr_code.Text);
- listr.Add(dic1);
- }
- map1.Add("ps_code", "");
- map1.Add("url", listr);
- map.Add("success", true);
- map.Add("data", map1);
- tcpserver.Send(jss.Serialize(map));
- tcpserver.Stop();
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", pr_code.Text, "");
- MessageBox.Show("产品编号" + pr_code.Text + "广播成功");
- }
- else
- {
- MessageBox.Show("产品编号" + pr_code.Text + "未维护SOP文档");
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", pr_code.Text, "");
- }
- }
- catch (Exception ex)
- {
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", pr_code.Text, "");
- Console.WriteLine(ex.Message + ex.StackTrace);
- }
- }
- public string encryptBASE64(string 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 void LoadPrCode()
- {
- DataTable dt = (DataTable)dh.ExecuteSql("select pr_code,pr_spec,pr_detail from product where instr('" + pr_code.Text + "',pr_code)>0", "select");
- if (dt.Rows.Count > 0)
- {
- pr_spec.Clear();
- pr_spec.AppendText(dt.Rows[0]["pr_spec"].ToString());
- pr_detail.Text = dt.Rows[0]["pr_detail"].ToString();
- pr_code.Text = dt.Rows[0]["pr_code"].ToString();
- }
- else
- {
- MessageBox.Show("产品编号" + pr_code.Text + "不存在");
- }
- }
- private void pr_code_Leave(object sender, EventArgs e)
- {
- LoadPrCode();
- }
- private void pr_spec_Click(object sender, EventArgs e)
- {
- }
- }
- }
|