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 System.Web.Script.Serialization; using Aspose.Cells.Rendering; using Aspose.Cells; using System.Drawing.Imaging; using System.Drawing; using System.Windows.Media; namespace FileWatcher { public partial class SOP : Form { DataHelper dh = new DataHelper(); string usercode; string sourcecode; DataTable Dbfind; public SOP(string iUserCode, string iSource) { usercode = iUserCode; sourcecode = iSource; 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; SystemInf.dh = 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 list = new List(); List filename = new List(); 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++) { 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 { DataHelper dh = new DataHelper(); //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; sheetname = sheetname.Replace("01", "1"); sheetname = sheetname.Replace("02", "2"); sheetname = sheetname.Replace("03", "3"); sheetname = sheetname.Replace("04", "4"); sheetname = sheetname.Replace("05", "5"); sheetname = sheetname.Replace("06", "6"); sheetname = sheetname.Replace("07", "7"); sheetname = sheetname.Replace("08", "8"); sheetname = sheetname.Replace("09", "9"); //if (sheetname.Contains("-")) //{ // sheetname = sheetname.Split('-')[0]; //} int width = 0; int height = 0; //Console.WriteLine(sheet.Name); //for (int i = 0; i < sheet.Cells.Columns.Count; i++) //{ // width +=(int) sheet.Cells.Columns[i].Width; //} //for (int i = 0; i < sheet.Cells.Rows.Count; i++) //{ // height += (int)sheet.Cells.Rows[i].Height; //} //Console.WriteLine("width:"+width); //Console.WriteLine("height:"+height); //sheet.Pictures.Add(0, 18, @"图片\电子受控章.png"); //sheet.Pictures.Add(0, 15, @"图片\签名.png"); //sheet.PageSetup.LeftMargin = 0; //sheet.PageSetup.RightMargin = 0; //sheet.PageSetup.BottomMargin = 0; //sheet.PageSetup.TopMargin = 0; ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); imgOptions.ImageFormat = ImageFormat.Png; imgOptions.OnePagePerSheet = true; imgOptions.PrintingPage = PrintingPageType.IgnoreBlank; imgOptions.SetDesiredSize(1565, 1043); SheetRender sr = new SheetRender((Aspose.Cells.Worksheet)sheet, imgOptions); sr.ToImage(0, Application.StartupPath + @"\" + ps_prodcode.Text + @"\" + sheetname + ".jpg"); //// 创建一个图片 OperatResult.AppendText("解析图片【" + sheetname + ".jpg】" + "\n"); Dictionary dic = new Dictionary(); dic.Add("em_name", "管理员"); dic.Add("em_code", "ADMIN"); dic.Add("caller", "ProductSOP"); OperatResult.AppendText("上传文件【" + sheetname + ".jpg" + "】\n"); string fp_id = UploadFilesToRemoteUrl("http://192.168.0.85:8099/mes/MEScommon/uploadFiles.action?_noc=1", Application.StartupPath + @"\" + ps_prodcode.Text + @"\" + sheetname + ".jpg", dic); string ps_id = dh.getFieldDataByCondition("ProductSOP", "ps_id", "ps_prodcode='" + ps_prodcode.Text + "'").ToString(); dh.ExecuteSql("insert into ProductSOPdetail(psd_id,psd_psid,psd_attach) select ProductSOPdetail_seq.nextval,ps_id,'" + sheetname + ".jpg" + ";" + fp_id + "' from ProductSOP where ps_prodcode='" + ps_prodcode.Text + "'", "insert"); //if (fp_id != "") //{ // dh.ExecuteSql("update ProductSOP set ps_attachsop=ps_attachsop||" + fp_id + "||';' where ps_prodcode='" + pr_code.Text + "'", "update"); //} } catch (Exception ex) { OperatResult.AppendText(ex.Message + ex.StackTrace); } } /// /// 请求上传图片到阿里云 /// /// 上传地址 /// 本地文件路径 /// 上传的数据信息 /// public string UploadFilesToRemoteUrl(string url1, string filepath, Dictionary 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 dic1 = new Dictionary(); List> dic2 = null; dic1 = BaseUtil.ToDictionary(Content); dic2 = dic1["data"] as List>; 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> listr = new List>(); JavaScriptSerializer jss = new JavaScriptSerializer(); Dictionary map1 = new Dictionary(); Dictionary map = new Dictionary(); 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 dic1 = new Dictionary(); 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 ps_prodcode_UserControlTextChanged(object sender, EventArgs e) { LoadPrCode(); } private void GetSOP_Click(object sender, EventArgs e) { LoadPrCode(); } } }