顯示具有 請稍候 標籤的文章。 顯示所有文章
顯示具有 請稍候 標籤的文章。 顯示所有文章

2022年12月26日 星期一

V80201- 請稍候訊息 - 1>Label方式 2>LoadMask方式

目的:  V80201- 顯示 請稍候訊息

處理說明: 1>畫面上,以 label 顯示訊息 - 請稍候  - label.setVisible(true)  ;
                  2>載入完成時, label.setVisible(false)  ;
                  3>Ext.Ajax 的  async 必需為 true, 異步式處理, 即去後端處理時,前端仍需繼續處理
                       ,如此前端才會顯示等待訊息




一.以 Label 方式處理
1>*.js
  //資料處理中..,請稍候
                {
                    xtype: 'label',
                    id: 'waitlbl1',
                    text: '.',
                    hidden: false,
                }, // end of 請稍候
                {
                    xtype: 'label',
                    id: 'waitlbl',

                    text: '資料處理中,請稍候...',
                    hidden: true,
                    style: {color: 'blue',}

                }, // end of 請稍候

{
            xtype: 'button', text: '確定', id: 'sub_ShowPN_OkBtn',
            listeners: {
                click: function () {
                    //mysuccessalert("mysub2_確定 ");
                    Ext.getCmp("waitlbl").setVisible(true);
                    //Ext.getCmp("waitlbl").setX(100);                                        
                    //myMask.show();                    
                    ShowPNGridDetail(par_PN, par_ECNO, par_CNDPROCCODE, par_ASN);
                }
            }
        },        


Ext.getCmp('sub_Grid').store.on("load", function (me, records, successful, eOpts) {        
        if (successful) {
            console.log("successful");
            console.log("Ext.getCmp('sub_Grid').store.data", Ext.getCmp('sub_Grid').store.data);
            win1.show();
            //若已載入完成,則            
            Ext.getCmp('waitlbl').setVisible(false);            
            //myMask.unmask();                    
            //myMask.hide();                                
        }
    }

二.以 LoadMask方式處理

目的:  V80201- 顯示 請稍候訊息  - 以 LoadMask 方式

處理說明: 1>畫面上,以 LoadMask 顯示訊息 - 請稍候  - Ext.getCmp("myMask").show();

                  2>載入完成時, - Ext.getCmp("myMask").hide();





1>*.js
var myMask = new Ext.LoadMask(Ext.getBody(), {
     msg: '資料處理中,請稍候...',
     id: 'myMask',

});

//顯示訊息
Ext.getCmp("myMask").show();

//隱藏訊息
Ext.getCmp('sub_Grid').store.on("load", function (me, records, successful, eOpts) {
        if (successful) {

            console.log("successful");
            console.log("Ext.getCmp('sub_Grid').store.data", Ext.getCmp('sub_Grid').store.data);
            win1.show();
            //若已載入完成,則            
            Ext.getCmp("myMask").hide();
        }
    }
    );






2022年8月29日 星期一

V120103 - Ext.Ajax 1> async=true/false 的不同 2>Ext.Ajax 和 Form.submit 的不同 3>loadMask

 目的:  說明 Ext.Ajax  - async : true/false 的不同


處理說明: 1>async: true, 不等後端執行完,即往下執行
                       async: false, 等後端執行完,才往下執行
   
                  2>Ext.Ajax       : 由 response.responseText 取得傳回值
                      form.submit  : 由 opts.response.responseText 取得傳回值
            
                 3>LoadMask : 適用於 async: true 



1>*.js  async=true/false 的區別

function mySub1_OkBtn_click() {
//取得 [類別][匯入機號][拆移工場]
console.log('0 xlsToV120101 click -  mySub1_OkBtn_click !!');
//1 > 讀取子畫面的過濾條件
var np = {};
var Tmp_sub_CLS = Ext.getCmp("sub_CLS").getValue();
var Tmp_sub_ASN = Ext.getCmp("sub_ASN").getValue();
var Tmp_sub_FACWC = Ext.getCmp("sub_FACWC").getValue();
np["sub_CLS"] = Tmp_sub_CLS;
np["sub_ASN"] = Tmp_sub_ASN;
np["sub_FACWC"] = Tmp_sub_FACWC;

console.log('5  before show mask !!');
var Tmp_upPanel = Ext.getCmp("mySub1_OkBtn").up("panel");
//console.log("Tmp_upPanel:", Tmp_upPanel);
//var mask = new Ext.LoadMask(Ext.getBody(), {
var mask = new Ext.LoadMask(Tmp_upPanel, {
msg: '處理中,請稍待...'
});

mask.show();//使用 mask 需手動呼叫show() 方法下
//顯示結果訊息..
//console.log('5.5  mask.show() !!');
console.log('6  before timer !!');
var timer = setInterval(function () {
clearInterval(timer);
mask.hide();
console.log('6.5  mask.hide() - after 20 sec !!');
timer = null;
//var r = r_cookies('EX_DFile');
//console.log("r_cookies=", r);
//if (!checkisnull(r)) {
// mysuccessalert(r);
//}
}, 30000);  //5000ms = 5sec

        //Ext.getCmp('mySubForm').submit({
Ext.Ajax.request({
url: '../../api/V120103API/xlsToV120101',
method: 'POST',
async: false,
//standardSubmit: true, // 非 Ajax 的方式  //若要傳送檔案至前端, standardSubmit必需設為 true 
params: np,
success: function (response, opts) {
console.log('0 xlsToV120101 sucess!!');
//console.log('0 opts:', opts);
//console.log('0 response:', response);
           console.log("success response.responseText:", response.responseText);
                var obj = Ext.decode(response.responseText);
                //console.log("obj:", obj);
if (obj["success"]) {
console.log(' 1 xlsToV120101 obj[sucess]  true !!');
Tmp_Str = "[匯入]完成 !! <br>"
           + obj["Rtn_Msg"];
mysuccessalert(Tmp_Str);
console.log("success=true , Tmp_Str=", Tmp_Str);
Ext.getCmp('mySub1_OkBtn').up("window").close();
Ext.getCmp('mySub1_OkBtn').up("window").destroy();
Ext.getCmp('btn_Show').fireHandler();
}
else {
console.log(' 2 xlsToV120101 obj[sucess]  false !!');
Tmp_Str = "[匯入]失敗 !! <br>"
            +obj["Rtn_Msg"];
mysuccessalert(Tmp_Str);
}
            },
            failure: function (response, opts) {
                //console.log('uploadFileToDB failure !!');
                //console.log(" failure opts.response.responseText:", opts.response.responseText);
console.log(' 3 xlsToV120101 failure !!');
                var obj = Ext.decode(response.responseText);
                console.log("obj:", obj);
Tmp_Str = "[匯入]失敗!! <br>"
+ obj["Rtn_Msg"];
                mywarnalert(Tmp_Str);                
            } // end of failure 
});  // end of submit
console.log('7  Ext.Ajax finished !!');
};  // end of function mySub1_OkBtn_click()


2>success: function (response, opts) {

     1>>若 Ext.Ajax 則由 response.responseText

             var obj = Ext.decode(response.responseText);

     2>>若 Form.submit 則由 opts.response.responseText

            var obj = Ext.decode(opts.response.responseText);



3>Loadmask的用法:  適用於 async : true



2022年8月18日 星期四

V120402D - xls套表列印 - 請稍候訊息 - Cookie - xls欄位格式設定 - 欄位合併, 插入圖片 - JSON2dt - 開啟檔案

 目的: xls套表列印, 分頁處理- Cookie - xls欄位格式設定 - 欄位合併, 插入圖片

處理說明: 1>由 SS_FILES 讀取套表檔案 , 存至 Server檔案目錄
                  2>xls分頁處理
                  3> xls欄位合併, 插入圖片                  




1>*.js  - V120402D.js

//[列印]鈕  - 列印套表  - Txxxx 技令借用登記表    - Dxxx 文件借用登記簿
    function sub_LookFlds_OkBtn() {
         //1>將子畫面 store 的資料轉成 JSON 字串,當參數傳至後端 Ext.Ajax
        var Tmp_sub_store = Ext.getCmp("sub_Grid").store;
        var Tmp_JSONString = store2JSON(Tmp_sub_store);
        var np = {};
        np["JSONString"] = Tmp_JSONString;
        //子畫面 submit
        Ext.getCmp('mySubForm').submit({
            //Ext.Ajax.request({
            url: '../../api/V120402DAPI/DoPRNLIST',
            method: 'POST',
            async: false,
       standardSubmit: true,// 非 Ajax 的方式  //若要傳送檔案至前端, standardSubmit必需設為 true 
            params: np,  //把目前 store資料轉成JSON, 當成處理參數 np
        });

        //顯示訊息 - 請稍候
        var mask = new Ext.LoadMask(Ext.getBody(), {
            msg: '處理中,請稍待...'
        });

        mask.show();//使用 mask 需手動呼叫show() 方法下
        var timer = setInterval(function () {
            clearInterval(timer);
            mask.hide();
            timer = null;
            //讀取 cookie的訊息 
            var r = r_cookies('EX_DFile');
            console.log("r_cookies=", r);
            if (!checkisnull(r)) {
                mysuccessalert(r);
            }
        }, 5000);  //3000ms = 3sec
    };  // end of function mySub1_OkBtn_click()


2>*.cs  - SS_FILES 轉成 xls 處理, xls欄位格式設定, 加入圖片

//套表列印 - 借閱記錄 - 列印文件借閱登記簿
        [HttpPost]
        public void DoPRNLIST()
        {
            var c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            // 1>將 SS_FILES.FBOLD 存成 Local檔案
            //取得目前子畫面的欄位值            
  string Tmp_JSONString = nvc["JSONString"];//Tmp_DataJSON:  將目前子畫面的資料. JSON字串  
            DataTable Tmp_dt = myfunc.JSON2dt(Tmp_JSONString);
            //DataTable DataTable1 = (DataTable)JsonConvert.DeserializeObject(Tmp_DataString1, (typeof(DataTable)));
            
            OracleConnection conn = new OracleConnection(DBService.ConnectionString(DBLINK));//
            OracleCommand cmd = new OracleCommand();

            conn.Open();
            conn.ClientInfo = User.Identity.Name;
            conn.ModuleName = BaseSYS + "_" + BaseMODID;
            conn.ActionName = ActionName;
            cmd.Connection = conn;
            string Tmp_Sql = "";
            string Tmp_Str = "";
            string Tmp_Str1 = "";
            string Tmp_RtnMsg;
            string Tmp_FName = "V120402_文件借閱登記簿.xlsx";      //套表的檔案名稱 , 
            string documentPath = HttpContext.Current.Server.MapPath("~") + "document\\";  // 取得實實的路徑            
            string pathFName = documentPath + Tmp_FName;
            //需要擷取大量資料時,DataReader 是很好的選擇,因為資料不會快取至記憶體。
            OracleDataReader reader;
            Workbook wk = null;
            MemoryStream mstream = new MemoryStream();
            string FileName = "V120402_文件借閱登記簿" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
            string FileName1 = documentPath + FileName;
            try
            {
                wk = new Workbook();
                //1>將  SS_FILES. FBODY , 存至Local目錄.檔案                 
                if (File.Exists(pathFName))
                {
                    File.Delete(pathFName);
                }
                Tmp_Sql = " SELECT  FNAME,FBODY "
                                + " FROM     SS_FILES   "
                                + "   WHERE   1 = 1  "
                                + "  AND         FNAME = " + myfunc.AA(Tmp_FName);
                cmd.CommandText = Tmp_Sql;
                reader = cmd.ExecuteReader();
                byte[] file = null;
                //FileMode.OpenOrCreate: 開啟檔案若無檔案則新增
                //FileAccess.ReadWrite: 允許檔案讀取/寫入
                FileStream fs = File.Open(pathFName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                BinaryWriter bw = new BinaryWriter(fs);
                if (reader.HasRows)
                {
                    if (reader.Read())
                    {
                        file = (byte[])reader["FBODY"];
                        //fs.Write(file,0,50000);
                        bw.Write(file);
                        wk.LoadFromStream(fs);
                        bw.Close();
                        fs.Close();
                    }
                }

                //2 > 主機.Local檔案 XLS 讀入  FStream
                //FileStream fs = File.Open(pathFName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)                
                Worksheet ws = wk.Worksheets[0];//獲取第一個工作表
                                                //寫入[SAPNO][PN][QTY][EOCND][RMK]

                //int RowCnt = 0;  //每頁 行                    
                int PageRowIndex = 0;  //本頁啟始 rowindex
                int PageSize = 29;            //每頁29行 , 含 頁首 行數                        
                int DataSize = 21;           //資料行數 , 資料row 行數
                int PageTitleRows = 6;  //頁首行數 (含資料標題行)
                string Tmp_DOCNO, Tmp_STLCT, Tmp_BRP_, Tmp_TELNO;
                string Tmp_BRDT, Tmp_RTDT, Tmp_REMARK;
                string Tmp_PicName = "V120402_Pic.jpg";
                string Tmp_pathPicName = documentPath + Tmp_PicName;
                int Pages = 0;
                int PageRow = -1;


                //每筆資料列印後, 分頁印下一筆
                for (var i = 0; i < Tmp_dt.Rows.Count; i++)
                {
                    //每筆資料均分頁 & 複製樣板 rows      
                    //每21筆資料,則分頁
                    if ((i % DataSize) ==0)
                    {
                        Pages = Pages + 1;
                        PageRow = -1;                        
                        if (Pages == 2)
                            Console.WriteLine("Pages", Pages);
                        PageRowIndex = PageRowIndex + PageSize;
                        //分頁
                        ws.HPageBreaks.Add(ws.Range[myfunc.GetExcelPos(0, PageRowIndex)]);
                        string Tmp_Range = "A" + string.Format("{0:D}", PageRowIndex + 1) + ":H" + string.Format("{0:D}", PageRowIndex + 1 + (PageSize - 1));
                        ws.Copy(ws.Range["A1:H29"], ws.Range[Tmp_Range], true);
                        Tmp_Range = "D" + string.Format("{0:D}", PageRowIndex + 2) + ":F" + string.Format("{0:D}", PageRowIndex + 2);
                        //文件借閱登記簿 merge - 欄位合併
                        //ws.Range[D2: F2].Merge();
                        ws.Range[Tmp_Range].Merge();
                        //設定列高度
                        ws.SetRowHeight(PageRowIndex + 2, 30);
                        //(Document On-loan Records)  merge
                        Tmp_Range = "D" + string.Format("{0:D}", PageRowIndex + 3) + ":F" + string.Format("{0:D}", PageRowIndex + 3);
                        //ws.Range[D3: F3].Merge();
                        ws.Range[Tmp_Range].Merge();
                        ws.SetRowHeight(PageRowIndex + 3, 25);
                        //加入圖片
                        int Tmp_row = PageRowIndex + 1;


                        //string Tmp_pathPicName = "C:\\Users\\611292\\Desktop\\demo.jpg";
                       //將 SS_FILES 存成檔案(Tmp_PathFName)
                        Tmp_pathPicName = myfunc.SS_FILES2PathFName(Tmp_PicName, DBLINK);  
                        ws.Pictures.Add(Tmp_row, 1, Tmp_pathPicName);
                    }
                    PageRow = PageRow + 1;
                    Tmp_DOCNO = Tmp_dt.Rows[i]["DOCNO"].ToString();
                    Tmp_STLCT = Tmp_dt.Rows[i]["STLCT"].ToString();
                    Tmp_BRP_ = Tmp_dt.Rows[i]["BRP_"].ToString();
                    Tmp_TELNO = Tmp_dt.Rows[i]["TELNO"].ToString();
                    if (Tmp_dt.Rows[i]["BRDT"].ToString().Length > 0)
        Tmp_BRDT = DateTime.Parse(Tmp_dt.Rows[i]["BRDT"].ToString()).ToString("yyyy/MM/dd");
                    else
                        Tmp_BRDT = "";
                    if (Tmp_dt.Rows[i]["RTDT"].ToString().Length > 0)
        Tmp_RTDT = DateTime.Parse(Tmp_dt.Rows[i]["RTDT"].ToString()).ToString("yyyy/MM/dd");
                    else
                        Tmp_RTDT = "";
                    Tmp_REMARK = Tmp_dt.Rows[i]["REMARK"].ToString();                    
ws.Range[myfunc.GetExcelPos(1, PageRowIndex + PageTitleRows + PageRow)].Text =Tmp_DOCNO;
ws.Range[myfunc.GetExcelPos(2, PageRowIndex + PageTitleRows + PageRow)].Text = Tmp_STLCT;
ws.Range[myfunc.GetExcelPos(3, PageRowIndex + PageTitleRows + PageRow)].Text = Tmp_BRP_;
ws.Range[myfunc.GetExcelPos(4, PageRowIndex + PageTitleRows + PageRow)].Text = Tmp_TELNO;
ws.Range[myfunc.GetExcelPos(5, PageRowIndex + PageTitleRows + PageRow)].Text = Tmp_BRDT;
ws.Range[myfunc.GetExcelPos(6, PageRowIndex + PageTitleRows + PageRow)].Text = Tmp_RTDT;
ws.Range[myfunc.GetExcelPos(7, PageRowIndex + PageTitleRows + PageRow)].Text = Tmp_REMARK;                    
                }
                //刪除樣板  rows                            
                ws.DeleteRow(1, PageSize);
                ws.Activate();
                wk.SaveToStream(mstream, FileFormat.Version2007);
                wk.SaveToFile(FileName1, FileFormat.Version2007);
                
                //開啟 xls file
                System.Diagnostics.Process.Start(FileName1);
                //wk.SaveToFile(FileName, ExcelVersion.Version2007);       
                /* 開啟 Local xls 檔案
                 * using System.Diagnostics;
                    Process process = new Process();
                   process.StartInfo.FileName = "WINWORD.EXE";
                   process.StartInfo.Arguments = @"C:\Users\Shani\Desktop\process.docx";
                   process.Start();
                 */
            }
            catch (Exception e)
            {
                var Tmp_ErrMsg = e.Message;                
                Tmp_Str = "開啟XLS檔案 , 錯誤訊息如下<br>"
                                + "(" + FileName + ")報表<br>"
                                + Tmp_ErrMsg;
                HttpCookie MyCookie1 = new HttpCookie("EX_DFile", HttpUtility.UrlEncode(Tmp_Str));
                HttpContext.Current.Response.Cookies.Add(MyCookie1);
                //HttpContext.Current.Response.End();
                //throw;                
            }
            finally
            {
                //reader.Close();
                //bw.Close();
                //fs.Close();
                wk.Dispose();
                conn.Close();
                //wk.close();

            }

            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode((string)FileName, System.Text.Encoding.UTF8) + "\"");
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //HttpContext.Current.Response.BinaryWrite(file);
            //HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            HttpContext.Current.Response.BinaryWrite(mstream.ToArray());
            //包裝標籤檔產生完成
            Tmp_Str = "請開啟如下XLS檔案<br>"
                            + "(" + FileName + ")列印<br>";                             
            HttpCookie MyCookie = new HttpCookie("EX_DFile", HttpUtility.UrlEncode(Tmp_Str));
            HttpContext.Current.Response.Cookies.Add(MyCookie);
            HttpContext.Current.Response.End();
        }  // end of public void DoPRNLIST()


2022年8月17日 星期三

V120502 - 套表列印, 並自動分頁 , 顯示 Cookie的訊息 , 顯示請稍候訊息

 目的: V120502 - 套表列印, 並自動分頁

處理說明 : 
      1>前端:
                  1>>將子畫面的Grid資料存成 JSON字串, 當np參數傳給 Ext.Ajax 
      2>後端
                  1>>讀取 SS_FILES 套表(using Spire.Xls;)
                  2>>讀取 np 參數中的子畫面資料
                  3>>開啟 *.xlsx 檔案,填入欄位值, 若筆數>每頁筆數,則跳頁  




1>*.js  將子畫面的資料轉成 JSON 字串, 並存成 np參數 , 傳給 Ext.Ajax

//[確定]鈕 - 套表列印
function mySub1_OkBtn_click() {                
        //0 > 將目前畫面的store資料, 存成 np(多筆資料) 當參數, 傳給 處理 url
        console.log("0 mySub1_OkBtn_click - 列印包裝標籤.確定");
        var Tmp_sub_store = Ext.getCmp('sub_Grid').store;
        var cur_rec;
        var Tmp_SAPNO, Tmp_PN, Tmp_QTY, Tmp_EOCND, Tmp_RMK;
        var Tmp_data_JSON = "";  //將store資料轉成 JSON 的字串
        var Tmp_sub_np = {};        
        let Tmp_DataAry1 = [];
        var Tmp_Str="";
        for (i = 0; i < Tmp_sub_store.getCount(); i++) {
            cur_rec = Tmp_sub_store.getAt(i);
            console.log(Tmp_Str + "cur_rec:", cur_rec);
            Tmp_DataAry1.push(cur_rec.data);            
        }
        console.log("Tmp_DataAry1:", Tmp_DataAry1);        
        // 將目前子畫面的資料(Table)轉成 JSON字串
        let Tmp_DataString1 = JSON.stringify(Tmp_DataAry1);
        console.log("Tmp_DataString1:", Tmp_DataString1);

        var Tmp_CHKDT = Ext.getCmp("sub_DT").getValue();
        console.log("Tmp_CHKDT:", Tmp_CHKDT);
        var np = {};
        np = {
            DataString1: Tmp_DataString1,  
            CHKDT: Tmp_CHKDT,
        };        

        Ext.getCmp('mySubForm').submit({
            //Ext.Ajax.request({
            url: '../../api/V120502API/DoPRNLIST',
            method: 'POST',
            async: false,
            standardSubmit: true, //若要傳送檔案至前端, standardSubmit必需設為 true  
            params: np,
        });
        //顯示結果訊息..

        var mask = new Ext.LoadMask(Ext.getBody(), {
            msg: '處理中,請稍待...'
        });

        mask.show();//使用 mask 需手動呼叫show() 方法下
        var timer = setInterval(function () {
            clearInterval(timer);
            mask.hide();
            timer = null;
            var r = r_cookies('EX_DFile');
            console.log("r_cookies=", r);
            if (!checkisnull(r)) {
                mysuccessalert(r);
            }
        }, 5000);  //3000ms = 3sec
    };  // end of function mySub1_OkBtn_click()


2>*.cs 處理
[HttpPost]
        public void DoPRNLIST()
        {
            var c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            // 1>將 SS_FILES.FBOLD 存成 Local檔案
            //取得目前子畫面的欄位值
            string Tmp_DataString1 = nvc["DataString1"];    //Tmp_DataString:  將目前子畫面的資料. JSON字串   
            string Tmp_CHKDT = nvc["CHKDT"];    //[ ]不印日期
//將 table 字串轉成 DataTable
DataTable DataTable1 = (DataTable)JsonConvert.DeserializeObject(Tmp_DataString1, (typeof(DataTable)));

            string Tmp_SAPNO, Tmp_PN, Tmp_EOCND, Tmp_RMK;
            string Tmp_QTY;            
            
                        OracleConnection conn = new OracleConnection(DBService.ConnectionString(DBLINK));//
                        OracleCommand cmd = new OracleCommand();
                        //OracleDataAdapter adp = new OracleDataAdapter();
                        //DataSet ds = new DataSet();
                        //var response = Request.CreateResponse();

                        conn.Open();
                        conn.ClientInfo = User.Identity.Name;
                        conn.ModuleName = BaseSYS + "_" + BaseMODID;
                        conn.ActionName = ActionName;
                        cmd.Connection = conn;
                        string Tmp_Sql = "";
                        string Tmp_Str = "";
                        string Tmp_Str1 = "";
                        string Tmp_RtnMsg;
                        string Tmp_FName = "V120502_包裝標籤_格式檔.xlsx";      //套表的檔案名稱 , 
                        string documentPath = HttpContext.Current.Server.MapPath("~") + "document\\";  // 取得實實的路徑            
                        string pathFName = documentPath + Tmp_FName;
                        //需要擷取大量資料時,DataReader 是很好的選擇,因為資料不會快取至記憶體。
                        OracleDataReader reader;
                        Workbook wk = null;
                        MemoryStream mstream = new MemoryStream();
                        string FileName = "V120502_包裝標籤_格式檔_" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
                        string FileName1 = documentPath + FileName;
                        try
                        {
                            wk = new Workbook();
                            //1>將  SS_FILES. FBODY , 存至Local目錄.檔案                 
                            if (File.Exists(pathFName))
                            {
                                File.Delete(pathFName);
                            }
                            Tmp_Sql = " SELECT  FNAME,FBODY "
                                            + " FROM     SS_FILES   "
                                            + "   WHERE   1 = 1  "
                                            + "  AND         FNAME = " + myfunc.AA(Tmp_FName);
                            cmd.CommandText = Tmp_Sql;
                            reader = cmd.ExecuteReader();
                            byte[] file = null;
                            //FileMode.OpenOrCreate: 開啟檔案若無檔案則新增
                            //FileAccess.ReadWrite: 允許檔案讀取/寫入
                            FileStream fs = File.Open(pathFName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            BinaryWriter bw = new BinaryWriter(fs);
                            if (reader.HasRows)
                            {
                                if (reader.Read())
                                {
                                    file = (byte[])reader["FBODY"];
                                    //fs.Write(file,0,50000);
                                    bw.Write(file);
                                    wk.LoadFromStream(fs);
                                    bw.Close();
                                    fs.Close();
                                }
                            }

                            //2 > 主機.Local檔案 XLS 讀入  FStream
                            Worksheet ws = wk.Worksheets[0];//獲取第一個工作表
                                                            //寫入[SAPNO][PN][QTY][EOCND][RMK]

                int RowCnt = 0;  //每頁 行                    
                int PageRowIndex = 0;  //本頁啟始 rowindex
                int PageSize = 8;            //每頁8行                       
                //每筆資料列印後, 分頁印下一筆
                for (var i = 0; i < DataTable1.Rows.Count; i++)
                            {
                    //每筆資料均分頁 & 複製樣板 rows                    
                        PageRowIndex = PageRowIndex + PageSize;
                        ws.HPageBreaks.Add(ws.Range[myfunc.GetExcelPos(0, PageRowIndex)]);
                        string Tmp_Range = "A" + string.Format("{0:D}", PageRowIndex + 1) + ":B" + string.Format("{0:D}", PageRowIndex + 1 + (PageSize - 1));
                        ws.Copy(ws.Range["A1:B8"], ws.Range[Tmp_Range], true);
                    
                                Tmp_SAPNO = DataTable1.Rows[i]["SAPNO"].ToString();
                                Tmp_PN = DataTable1.Rows[i]["PN"].ToString();
                                Tmp_QTY = DataTable1.Rows[i]["QTY"].ToString();
                                Tmp_EOCND = DataTable1.Rows[i]["EOCND"].ToString();
                                Tmp_RMK = DataTable1.Rows[i]["RMK"].ToString();
                                ws.Range[myfunc.GetExcelPos(1, PageRowIndex)].Text = Tmp_PN;
                                ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 1)].Text = Tmp_EOCND;
                                if (Tmp_CHKDT == "true")  //不印日期
                    {
                        ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 2)].Text = "";
                    }
                                else
                    {
                        ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 2)].Text = myfunc.cnow();                        
                    }
                        
                                 ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 3)].Text = Tmp_QTY;
                                 ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 4)].Text = Tmp_SAPNO;
                                 ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 5)].Text = "";  //品保欄位空白
                                 ws.Range[myfunc.GetExcelPos(1, PageRowIndex + 6)].Text = Tmp_RMK;                                                                  
                }                     
                            //刪除樣板  rows                            
                            ws.DeleteRow(1, PageSize);
                            //ws.AllocatedRange.AutoFitColumns();
                            //wk.SaveToStream(mstream, FileFormat.Version2007);
                            //wk.SaveToFile(FileName1, FileFormat.Version2007);
                wk.SaveToStream(mstream, FileFormat.Version2013);
                wk.SaveToFile(FileName1, FileFormat.Version2013);
                //wk.SaveToFile(FileName, ExcelVersion.Version2007);                
            }
                        catch (Exception e)
                        {
                            var Tmp_ErrMsg = e.Message;
                        }
                        finally
                        {
                            //reader.Close();
                            //bw.Close();
                            //fs.Close();
                            wk.Dispose();
                            conn.Close();
                            //wk.close();

                        }

                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode((string)FileName, System.Text.Encoding.UTF8) + "\"");
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                        HttpContext.Current.Response.BinaryWrite(mstream.ToArray());
            //包裝標籤檔產生完成
                       Tmp_Str = "請開啟如下XLS檔案<br>" 
                                       +"(" + FileName + ")<br>"
                                        +"並挑選[標籤印表機(TSC_ME240)]印表機<br>" 
                                        +"標籤樣式100mm*60mm(寬*高)列印<br>";
                        HttpCookie MyCookie = new HttpCookie("EX_DFile", HttpUtility.UrlEncode(Tmp_Str));
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();                        
        }  // end of public void DoPRNLIST()




2022年8月8日 星期一

Ext.Ajax.request - 傳送檔案至 Browser - mask 資料處理中,請稍候 , Cookie

1>目的: 透過 Form.submit 方式,於後端處理後,將結果檔案傳送至前端
2>處理說明: 


1>*.js  - [確認匯入]鈕, 將匯入結果,存於 xls最後一欄後,傳至前端 , 錯誤訊息以 Cookie 傳回

 //[確認匯入]鈕 , 處理
    function mySubForm_2_btnokClick() {
        //取得 [檔案上傳].檔名
        var btn_FileIn_Obj = Ext.getCmp('sub_FName');
        var Tmp_Str = "";
        var np = {
            FName: Ext.getDom(btn_FileIn_Obj.inputId).value
        };
        console.log("FName: ", np.FName);
        //submit會將fileUploadForm裡面input name送到後端
        //Ext.getCmp('btn_FileIn').getForm().submit({
        Ext.getCmp('mySubForm_2_btnok').up("form").submit({
            //standardSubmit: false,    //default:false
            url: '../api/V120103API/uploadFileToDB',
            method: 'POST',
            async: false,

            headers: { 'Content-type': 'multipart/form-data' },
            params: np,
            standardsubmit=true    //才可將檔案送至前端
        } ) //end of submit;
          //顯示匯入結果
        var mask = new Ext.LoadMask(Ext.getBody(), {
            msg: '資料處理中,請稍候...'
        });
        mask.show();//使用 mask 需手動呼叫show() 方法下
        var timer = setInterval(function () {
            var cookie_token = Ext.util.Cookies.get("Rtn_Msg");
            if (cookie_token != null) {
                clearInterval(timer);
                timer = null;
                mask.hide();
                //console.log(" show result !!");
                var r = r_cookies("Rtn_Msg");
                mysuccessalert(r);

                Ext.getCmp('mySubForm_2_btnok').up("window").close();
                Ext.getCmp('mySubForm_2_btnok').up("window").destroy();
                //mysuccessalert('檔案匯出完成');
            }
        }, 1000);       
        
    };  // end of mySubForm_2_btnokClick() {


2>*.cs  - 透過 Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" +          
                HttpUtility.UrlEncode(Tmp_FName, System.Text.Encoding.UTF8) + "\"");  
             --> 傳送檔案至 Browser   

//[匯入] 鈕 , 匯入 XLS 檔案 void
        [HttpPost]
        public void uploadFileToDB()
        {

            HttpContext c = HttpContext.Current;
            NameValueCollection nvc = c.Request.Form;
            //匯入檔案名稱(含 *.xlsx)
            string FName = nvc["FName"];
            string FName0 =Path.GetFileNameWithoutExtension(FName) ;  //不含 extension
            string Tmp_FName = FName;
            Workbook wk = null;

            HttpRequest Request = HttpContext.Current.Request;
            var response = this.Request.CreateResponse();
            string file_Name = FName;
            string FILEDT = DateTime.Now.ToString("yyyy-MM-dd");
            string Tmp_RtnMsg = "";
            string Tmp_Sql = "", Tmp_Str = "";
            int Tmp_CNT = 0;

            MemoryStream stream = new MemoryStream();
            HttpCookie MyCookie = new HttpCookie("Rtn_Msg");
            foreach (string cur_FName in Request.Files)
            {
                string fileType = Request.Files[cur_FName].ContentType;
                Stream file_Strm = Request.Files[cur_FName].InputStream;
                file_Name = Path.GetFileName(Request.Files[cur_FName].FileName);                
                int fileSize = Request.Files[cur_FName].ContentLength;
                byte[] fileRcrd = new byte[fileSize];
                //更新資料庫欄位值                
                int Tmp_curpos = 0;                
                bool Tmp_isOK = true;
                try
                {

                    wk = new Workbook();
                    wk.LoadFromStream(file_Strm);
                    Worksheet sheet1 = wk.Worksheets[0];//獲取第一個工作表
                                                        //共 10 欄
//string[] outFieldArray = { "計畫代碼", "父件件號", "件號", "件號中文名稱", "每機用量", 
                                             "BOM量", "計量單位", "工廠", "類別","備註" };
                                                        //int RowsCount = sheet1.Rows.Count();
                    int RowsCount = sheet1.LastRow;
                    string Tmp_CLS,Tmp_ITM,  Tmp_DITM, Tmp_NM, Tmp_REPN, Tmp_RESN, Tmp_INPN, Tmp_INSN, Tmp_RMK;
                    string Tmp_PLNC, Tmp_REWK, Tmp_INSC, Tmp_STLCT, Tmp_NOTE, Tmp_FACWC;
                    string Tmp_RESULT;

                    //STEP1 檢核  XLS 欄位名稱資料是否正確                                            
                    //類別 排序項次 名稱 拆移件號 拆移序號 安裝件號 安裝序號 備考
                    // 拆移PlanningCard 修理REWORK 安裝InstallationCard 儲位 備註 拆移工廠
                    Tmp_RtnMsg = "匯入檔案欄位名稱必需如下:<br>";
                    Tmp_CLS = sheet1.Range[myfunc.GetExcelPos(0, 0)].Value;
                    if (Tmp_CLS != "類別")
                        Tmp_RtnMsg = Tmp_RtnMsg + "第1欄位名稱必需為[類別],";
                    Tmp_DITM = sheet1.Range[myfunc.GetExcelPos(1, 0)].Value;
                    if (Tmp_DITM != "排序項次")
                        Tmp_RtnMsg = Tmp_RtnMsg + "第2欄位名稱必需為[排序項次],";
                    //新增[結果說明]欄位
                    Tmp_RESULT = "結果說明";
                    sheet1.Range[myfunc.GetExcelPos(14, 0)].Value=Tmp_RESULT;

                    //xls 欄位名稱有問題                                                    
                    if ((Tmp_CLS != "類別") || (Tmp_DITM != "排序項次") || (Tmp_NM != "名稱") || (Tmp_REPN != "拆移件號") || (Tmp_RESN != "拆移序號") ||
                          (Tmp_INPN != "安裝件號") || (Tmp_INSN != "安裝序號") || (!Tmp_RMK.Contains("備考")) ||
                          (Tmp_PLNC != "拆移PlanningCard") || (Tmp_REWK != "修理REWORK") || (Tmp_INSC != "安裝InstallationCard") || 
                          (Tmp_STLCT != "儲位") || (Tmp_NOTE != "備註") || (Tmp_FACWC != "拆移工廠")
                          )
                    {
                        Tmp_RtnMsg = Tmp_RtnMsg
                                                 +"敬請檢核";
                        //Tmp_Rtn_JSON = "{success: false,FName:" + myfunc.AA(FName) + ",Rtn_Msg:" + myfunc.AA(Tmp_RtnMsg) + "}";
                        MyCookie.Value=  HttpUtility.UrlEncode(Tmp_RtnMsg);
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();
                        return ;
                    };

                    int Tmp_index;
                    Tmp_isOK = true;
                    //STEP2 檢核資料
                    for (int i = 0; i < RowsCount; i++)
                    {
                        Tmp_curpos = i + 1;
                     
                    //若資料不正確,則不寫入資料庫,只傳回檔案
                    if (Tmp_isOK == false)
                    {
                        Tmp_Str = "匯入檔案欄位值需修正!!<br>"
                                    + "請檢核如下檔案名稱(" + Tmp_FName + ")<br>";
                                    
                        MyCookie.Value = HttpUtility.UrlEncode(Tmp_Str);
                        // 若匯入資料有問題, 則不寫入資料庫 , 傳回結果檔案(*_結果.xlsx)
                        Tmp_FName = FName0 + "_結果.xlsx";
                        wk.SaveToStream(stream, FileFormat.Version2007);
                        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(Tmp_FName, System.Text.Encoding.UTF8) + "\"");
                        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        HttpContext.Current.Response.BinaryWrite(stream.ToArray());
                        HttpContext.Current.Response.Cookies.Add(MyCookie);
                        HttpContext.Current.Response.End();
                        return;
                    }