| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459 |
- using System;
- using System.IO;
- using System.Text;
- using System.Windows.Forms;
- using System.Net;
- using System.Collections.Generic;
- using System.Threading;
- using System.Data;
- using System.Drawing.Imaging;
- using System.Drawing;
- using UAS_MES_NEW.Entity;
- using UAS_MES_NEW.PublicMethod;
- using Aspose.Cells;
- using UAS_MES_NEW.DataOperate;
- using UAS_MES_NEW.PublicForm;
- using Aspose.Cells.Drawing;
- using Aspose.Cells.Rendering;
- using System.Web.Script.Serialization;
- namespace UAS_MES_NEW.Query
- {
- public partial class Query_SOP : Form
- {
- DataHelper dh;
- string usercode;
- string sourcecode;
- DataTable Dbfind;
- public Query_SOP()
- {
- usercode = "";
- sourcecode = "";
- InitializeComponent();
- }
- private void Form3_Load(object sender, EventArgs e)
- {
- CheckForIllegalCrossThreadCalls = false;
- ps_prodcode.TableName = "productsop";
- ps_prodcode.SelectField = "ps_prodcode # SOP编号";
- ps_prodcode.FormName = Name;
- ps_prodcode.DBTitle = "SOP查询";
- ps_prodcode.SetValueField = new string[] { "ps_prodcode" };
- ps_prodcode.Condition = "";
- ps_prodcode.DbChange += nr_rule_DBChange;
- li_code.TableName = "line";
- li_code.SelectField = "li_code # 线别编号,li_name # 线别名称";
- li_code.FormName = Name;
- li_code.DBTitle = "线别查询";
- li_code.SetValueField = new string[] { "li_code" };
- li_code.Condition = "";
- li_code.DbChange += nr_rule_DBChange;
- dh = SystemInf.dh;
- }
- private void nr_rule_DBChange(object sender, EventArgs e)
- {
- Dbfind = ps_prodcode.ReturnData;
- BaseUtil.SetFormValue(this.Controls, Dbfind);
- }
- void uploadfile()
- {
- if (FilePath.Text == "")
- {
- MessageBox.Show("文件不能为空!");
- return;
- }
- ps_prodcode.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 ps_prodcode='" + ps_prodcode.Text + "' ", "select");
- if (dt.Rows.Count == 0)
- {
- string code = LogicHandler.GetPiInoutCode("ProductSOP", "1");
- 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");
- }
- else
- {
- string ps_id = dt.Rows[0]["ps_id"].ToString();
- dh.ExecuteSql("delete from ProductSOPdetail where psd_psid='" + ps_id + "'", "delete");
- ps_prodcode.Text = dt.Rows[0]["ps_prodcode"].ToString();
- }
- Workbook workbook = new Workbook(FilePath.Text);
- List<Worksheet> list = new List<Worksheet>();
- List<string> filename = new List<string>();
- dh.ExecuteSql("update ProductSOP set ps_attachsop='' where ps_prodcode='" + ps_prodcode.Text + "'", "update");
- OperatResult.AppendText("一共Sheet: " + workbook.Worksheets.Count + "\n");
- //try
- //{
- for (int i = 0; i < workbook.Worksheets.Count; i++)
- {
- if (workbook.Worksheets[i].Name != "物料清单")
- {
- OperatResult.AppendText("正在解析Sheet" + workbook.Worksheets[i].Name + "\n");
- Worksheet she = workbook.Worksheets[i];
- if (JPG.Checked)
- {
- var myThread = new Thread(() => SaveFileToJPG(she));
- myThread.Start();
- filename.Add(she.Name + ".jpg");
- }
- }
- }
- //}
- //catch (Exception ex)
- //{
- // OperatResult.AppendText(ex.Message + "\n");
- //}
- }
- private void SaveFileToJPG(Worksheet sheet)
- {
- try
- {
- //OperatResult.AppendText("解析图片【" + sheet.Name + ".jpg】添加水印" + "\n");
- if (!Directory.Exists(Application.StartupPath + @"\" + ps_prodcode.Text))
- {
- Directory.CreateDirectory(Application.StartupPath + @"\" + ps_prodcode.Text);
- }
- string sheetname = sheet.Name;
- ProcessWorksheet(sheet, Application.StartupPath + @"\" + ps_prodcode.Text + @"\");
- }
- catch (Exception ex)
- {
- OperatResult.AppendText(ex.Message + ex.StackTrace);
- }
- }
- /// <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", "上传失败", ps_prodcode.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【图片格式】", "上传成功", ps_prodcode.Text, "");
- }
- else
- {
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "上传SOP【PDF格式】", "上传成功", ps_prodcode.Text, "");
- }
- }
- private void OperatResult_TextChanged(object sender, EventArgs e)
- {
- //OperatResult.SelectionStart = Text.Length;
- OperatResult.ScrollToCaret();
- }
- private void SendSop_Click(object sender, EventArgs e)
- {
- try
- {
- if (li_code.Text == "" || ps_prodcode.Text == "")
- {
- MessageBox.Show("线别和SOP文档不能为空");
- return;
- }
- if (SendDGV.Rows.Count > 0)
- {
- List<Dictionary<string, string>> listr = new List<Dictionary<string, string>>();
- 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 < SendDGV.Rows.Count; i++)
- {
- if (SendDGV.Rows[i].Cells["CheckColumn"].FormattedValue.ToString().ToUpper() == "TRUE")
- {
- Dictionary<string, string> dic1 = new Dictionary<string, string>();
- path = SendDGV.Rows[i].Cells["fp_path"].Value.ToString();
- path = encryptBASE64(path.Replace("/app/uas/webapps/postattach", pathroot)).Replace("\\s*|\r|\n|\t", "");
- dic1.Add("path", path);
- dic1.Add("filename", SendDGV.Rows[i].Cells["fp_name"].Value.ToString().Replace(" ", "").Replace("(", "").Replace(")", ""));
- dic1.Add("ps_prodcode", ps_prodcode.Text);
- listr.Add(dic1);
- dh.ExecuteSql("insert into soprelease(SR_ID, SR_LINECODE, SR_PATH, SR_STATUS, SR_MACHINETYPE, SR_FILENAME,sr_ifkeyset)" +
- "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");
- }
- }
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播成功", ps_prodcode.Text, "");
- MessageBox.Show("文档[" + ps_prodcode.Text + "]下放成功");
- }
- else
- {
- MessageBox.Show("产品编号" + ps_prodcode.Text + "未维护SOP文档");
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败,未维护SOP文档", ps_prodcode.Text, "");
- }
- }
- catch (Exception ex)
- {
- LogicHandler.DoCommandLog("SOP", usercode, "", "", sourcecode, "广播SOP", "广播失败", ps_prodcode.Text, "");
- Console.WriteLine(ex.Message + ex.StackTrace);
- }
- }
- public string encryptBASE64(string key)
- {
- Console.WriteLine(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 * from productsop where ps_prodcode='" + ps_prodcode.Text + "'", "select");
- if (dt.Rows.Count > 0)
- {
- string ps_id = dt.Rows[0]["ps_id"].ToString();
- dt = (DataTable)dh.ExecuteSql("select fp_name,fp_path,'' issend,psd_iskey from ProductSOPdetail left join " +
- "filepath on FP_ID=substr(PSD_ATTACH,instr(PSD_ATTACH,';')+1) where psd_psid=" + ps_id, "select");
- if (dt.Rows.Count > 0)
- {
- SendDGV.DataSource = dt;
- }
- }
- }
- private void pr_code_Leave(object sender, EventArgs e)
- {
- //LoadPrCode();
- }
- bool AllChecked = false;
- private void ChooseALL_Click(object sender, EventArgs e)
- {
- if (AllChecked)
- {
- foreach (DataGridViewRow dr in SendDGV.Rows)
- dr.Cells[0].Value = false;
- AllChecked = false;
- }
- else
- {
- foreach (DataGridViewRow dr in SendDGV.Rows)
- dr.Cells[0].Value = true;
- AllChecked = true;
- }
- }
- private void ProcessWorksheet(Worksheet worksheet, string outputFolder)
- {
- // 获取工作表中的所有图片
- List<Picture> pictures = new List<Picture>();
- foreach (Aspose.Cells.Drawing.Picture picture in worksheet.Pictures)
- {
- pictures.Add(picture);
- }
- // 获取使用的行数
- int totalRows = worksheet.Cells.MaxDataRow + 1;
- int imageIndex = 1;
- // 每30行生成一张图片
- for (int startRow = 0; startRow < totalRows; startRow += 30)
- {
- int endRow = Math.Min(startRow + 29, totalRows - 1);
- // 创建图片选项
- ImageOrPrintOptions options = new ImageOrPrintOptions();
- options.ImageFormat = ImageFormat.Png;
- options.OnePagePerSheet = false;
- options.PrintingPage = PrintingPageType.IgnoreBlank;
- worksheet.PageSetup.PrintArea = $"A{startRow + 1}:AC{endRow + 1}";
- // 设置只渲染指定的行范围
- // 创建SheetRender对象
- SheetRender sr = new SheetRender(worksheet, options);
- string imagename = $"{worksheet.Name}_{imageIndex}.png";
- // 获取渲染后的图像
- Bitmap bitmap = sr.ToImage(0);
- string imagePath = "";
- // 如果有图片在当前行范围内,将它们添加到最终图像中
- if (pictures.Count > 0)
- {
- using (Bitmap finalImage = new Bitmap(bitmap.Width, bitmap.Height))
- using (Graphics g = Graphics.FromImage(finalImage))
- {
- // 绘制Excel内容
- g.DrawImage(bitmap, 0, 0);
- // 绘制原始Excel中的图片
- int yOffset = bitmap.Height;
- // 保存图像
- imagePath = Path.Combine(outputFolder, $"{worksheet.Name}_{imageIndex}.png");
- finalImage.Save(imagePath, ImageFormat.Png);
- Console.WriteLine($"Saved: {imagePath}");
- }
- }
- else
- {
- // 如果没有图片,直接保存渲染的图像
- imagePath = Path.Combine(outputFolder, $"{worksheet.Name}_{imageIndex}.png");
- bitmap.Save(imagePath, ImageFormat.Png);
- Console.WriteLine($"Saved: {imagePath}");
- }
- imageIndex++;
- OperatResult.AppendText("解析图片【" + imagePath + ".jpg】" + "\n");
- Dictionary<string, object> dic = new Dictionary<string, object>();
- dic.Add("em_name", "管理员");
- dic.Add("em_code", "ADMIN");
- dic.Add("caller", "ProductSOP");
- OperatResult.AppendText("上传文件【" + imagePath + ".jpg" + "】\n");
- string fp_id = UploadFilesToRemoteUrl("http://192.168.1.92:8088/mes/MEScommon/uploadFiles.action?_noc=1", Application.StartupPath + @"\" + ps_prodcode.Text + @"\" + imagename, dic);
- 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");
- }
- }
- private void ps_prodcode_UserControlTextChanged(object sender, EventArgs e)
- {
- //LoadPrCode();
- }
- private void GetSOP_Click(object sender, EventArgs e)
- {
- LoadPrCode();
- }
- }
- }
|