MRBrowserLibrary

Example:


using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
using BrowserHelper;

namespace 国外进口过境货物筛选系统
{
    /// <summary>
    /// 主界面类
    /// </summary>
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class frmMain : Form
    {
        private string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        private PageEvent menuPageEvent;
        private PageEvent mainPangeEvnet;
        private DataTable singleHandleTxtResultDataTable;
        private OpenFileDialog openFileDialog;
        private OpenFileDialog singleOpenFileDialog;
        private List<String> multiSelectFileNameList;

        /// <summary>
        /// 构造方法
        /// </summary>
        public frmMain()
        {
            InitializeComponent();

            //  初始化程序
            menuPageEvent = new PageEvent(browserControl);
            mainPangeEvnet = new PageEvent(browserMain);

            openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = true;
            singleOpenFileDialog = new OpenFileDialog();
            multiSelectFileNameList = new List<string>();

            browserMain.ObjectForScripting = this;

            //  通用菜单
            menuPageEvent.AddEvent("header.html", "mainnav_exit", (sdr, arg) =>
                {
                    Visible = false;
                    Dispose();
                });

            menuPageEvent.AddEvent("header.html", "mainnav_help", (sdr, arg) =>
            {
                if (File.Exists(baseDirectory + "help.chm"))
                {
                    Process proc = new Process();
                    proc.StartInfo.FileName = baseDirectory + "help.chm";
                    proc.StartInfo.Arguments = "";
                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
                    proc.Start();
                }
                else
                {
                    MessageBox.Show("帮助文件缺失,请联系管理员");
                }
            });

            menuPageEvent.AddEvent("header.html", "mainnav_sc_current", (sdr, arg) =>
                {
                    browserMain.Url = new Uri(baseDirectory + "Content/form.html");
                });

            menuPageEvent.AddEvent("header.html", "mainnav_plsc", (sdr, arg) =>
                {
                    multiSelectFileNameList.Clear();
                    browserMain.Url = new Uri(baseDirectory + "Content/multiForm.html");
                });

            //  单文件传输 form.html
            mainPangeEvnet.AddEvent("form.html", "getOpenFileName", (sdr, arg) =>
                {
                    MatchClass m = new MatchClass();
                    string strFilename = browserMain.Document.GetElementById("openfile").GetAttribute("value");
                    string strExtension = System.IO.Path.GetExtension(strFilename);
                    if (strExtension.ToLower() != ".txt")
                    {
                        MessageBox.Show("文件格式不对!");
                        return;
                    }
                    browserMain.Document.InvokeScript("removeCenterClass");
                   
                    ArrayList list = new ArrayList();
                    list = m.readFile(strFilename);
                    if (list != null && list[1] != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        int iTotal = (int)list[0];
                        singleHandleTxtResultDataTable = (DataTable)list[1];
                        sb.Append(@"<div class=""box_1""><input type=""submit"" class=""btn22"" id=""export"" onclick=""exportTable()""  value="""" /></div>");
                        sb.Append("<p>本次总处理数据" + iTotal + "条,成功筛选数据" + singleHandleTxtResultDataTable.Rows.Count.ToString() + "条!</p><hr />");
                        sb.Append("<table class=\"tab\"><tr class=\"tab_title\">\n");
                        sb.Append(@"<td>船名</td><td>航次</td><td>到港日期</td><td>提单号</td><td>上箱号</td></tr>");
                        if (singleHandleTxtResultDataTable != null)
                        {
                            for (int i = 0; i < singleHandleTxtResultDataTable.Rows.Count; i++)
                            {
                                sb.Append(@"<tr class=""tab_trcurrent"">");
                                sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["船名"].ToString()));
                                sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["航次"].ToString()));
                                sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["到港日期"].ToString()));
                                sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["提单号"].ToString()));
                                sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["箱号"].ToString()));
                                sb.Append("</tr>");
                            }
                        }
                        sb.Append("</table>");
                        var elementById = browserMain.Document.GetElementById("uploadResult");
                        if (elementById != null)
                        {
                            elementById.InnerHtml = sb.ToString();
                        }
                    }
                });

            mainPangeEvnet.AddEvent("form.html", "selectFile", (sdr, arg) =>
            {
                if (singleOpenFileDialog.ShowDialog() == DialogResult.OK)
                {
                    browserMain.Document.GetElementById("openfile").SetAttribute("value", singleOpenFileDialog.FileName);
                }
            });

            //  多文件筛选
            mainPangeEvnet.AddEvent("multiForm.html", "openMultiFile", (sdr, arg) =>
                {
                    multiSelectFileNameList.Clear();
                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        string[] fileNames = openFileDialog.FileNames;
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < fileNames.Length; i++)
                        {
                            sb.Append(fileNames[i]);
                            sb.Append(";");
                        }
                        browserMain.Document.GetElementById("fileNames").SetAttribute("value", sb.ToString());
                        multiSelectFileNameList.AddRange(fileNames);
                    }
                });

            mainPangeEvnet.AddEvent("multiForm.html", "getMultiFileNames", (sdr, arg) =>
                {
                    WriteFromMutlifForm();
                });
        }

        //  批量筛选
        public void WriteFromMutlifForm()
        {
            if (multiSelectFileNameList != null && multiSelectFileNameList.Count > 0)
            {
                List<DataTable> list = new List<DataTable>();
                int totalCount = 0;
                int successCount = 0;
                for (int i = 0; i < multiSelectFileNameList.Count; i++)
                {
                    MatchClass m = new MatchClass();
                    ArrayList readFile = m.readFile(multiSelectFileNameList[i]);
                    if (readFile != null)
                    {
                        totalCount += (int)readFile[0];
                        var dataTable = (DataTable)readFile[1];
                        successCount += dataTable.Rows.Count;
                        list.Add(dataTable);
                    }
                }
                browserMain.Document.InvokeScript("removeCenterClass");
                StringBuilder sb = new StringBuilder();
                sb.Append(@" <div class=""box_1""><input type=""button"" onclick=""exportAllTable()"" class=""btn22""  value="""" /></div><p>本次总处理数据" + totalCount + @"条,成功筛选数据" + successCount + @"条!</p><!--表格--><table class=""tab"" ><tr class=""tab_title"" ><td width=""30px""><input type=""checkbox"" checked=""checked"" id=""checkall"" onclick=""checkallmethod()"" /></td><td  width=""45px"">序号</td><td>文档名称</td><td>匹配数</td><td>打开</td></tr>");
                for (int i = 0; i < multiSelectFileNameList.Count; i++)
                {
                    FileInfo fileInfo = new FileInfo(multiSelectFileNameList[i]);
                    DataTable dataTable = list[i];
                    sb.Append(
                        @"<tr ><td><input name=""checkExportOption"" checked=""checked"" type=""checkbox"" /></td><td>" + (i + 1) + "</td><td>" + fileInfo.Name + "</td><td>" + dataTable.Rows.Count + @"</td><td><input type=""button"" class=""btn1"" onclick=""callOpenSingle('" + (i + 1) + @"')"" value=""打 开"" /></td></tr>");

                }
                browserMain.Document.GetElementById("uploadResult").InnerHtml = sb.ToString();
            }
            else
            {
                MessageBox.Show("请选择要筛选的文件");
            }
        }

        /// <summary>
        /// 导出数据至Excel.
        /// </summary>
        public void writeSingle()
        {
            if (!browserMain.Url.ToString().Contains("multiForm.html"))
            {
                multiSelectFileNameList.Clear();
            }
            if (browserMain.Document != null)
            {
                var elementById = browserMain.Document.GetElementById("openfile");
                string content = browserMain.Document.Body.InnerHtml;
                if (elementById != null)
                {
                    string strFilename = elementById.GetAttribute("value");
                    if (!string.IsNullOrEmpty(strFilename))
                    {
                        FileInfo fileInfo = new FileInfo(strFilename);
                        if (fileInfo != null && fileInfo.Name.Length > 0 && fileInfo.Name.Contains("."))
                        {
                            string fileName = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf("."));
                            string directory = fileInfo.Directory.FullName;
                            if (singleHandleTxtResultDataTable != null &&
                                singleHandleTxtResultDataTable.Rows.Count > 0)
                            {
                                WriteXls writeXls = new WriteXls();
                                writeXls.Write(directory + "/" + fileName + ".xls", singleHandleTxtResultDataTable);
//                                browserMain.Url = browserMain.Url;
                                browserMain.Document.Body.InnerHtml = content;
                                mainPangeEvnet.BindPage();
                            }
                            else
                            {
                                MessageBox.Show("没有信息可以导出");
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 导出多个结果集至Excel.
        /// </summary>
        public void writeMulti()
        {
            if (browserMain.Document != null)
            {
                if (multiSelectFileNameList.Count > 0)
                {
                    List<int> indexList = new List<int>();
                    int index = 0;
                    foreach (HtmlElement checkboxControl in browserMain.Document.GetElementsByTagName("input"))
                    {
                        if (checkboxControl.Name.Equals("checkExportOption"))
                        {
                            if (checkboxControl.GetAttribute("checked").Trim().ToLower().Equals("true"))
                            {
                                indexList.Add(index);   
                            }
                            index++;
                        }
                    }

                    if (indexList.Count <= 0)
                    {
                        MessageBox.Show("请先选择要导出的项");
                        return;
                    }

                    List<DataTable> list = new List<DataTable>();
                    string fullFileName = "";
                    string directory = "";
                    for (int i = 0; i < multiSelectFileNameList.Count; i++)
                    {
                        if (indexList.Contains(i))
                        {
                            string strFilename = multiSelectFileNameList[i];
                            if (!string.IsNullOrEmpty(strFilename))
                            {
                                FileInfo fileInfo = new FileInfo(strFilename);
                                if (fileInfo != null && fileInfo.Name.Length > 0 && fileInfo.Name.Contains("."))
                                {
                                    string fileName = fileInfo.Name.Substring(0, fileInfo.Name.IndexOf("."));
                                    directory = fileInfo.Directory.FullName;
                                    fullFileName += fileName;
                                    MatchClass m = new MatchClass();
                                    ArrayList readFile = m.readFile(multiSelectFileNameList[i]);
                                    if (readFile != null)
                                    {
                                        var dataTable = (DataTable)readFile[1];
                                        list.Add(dataTable);
                                    }
                                }
                            }
                        }
                    }
                   
                    if (!string.IsNullOrEmpty(fullFileName) && !string.IsNullOrEmpty(directory) && list.Count > 0)
                    {
                        WriteXls writeXls = new WriteXls();
                        writeXls.Write(directory + "/" + fullFileName + ".xls", list);
                    }
                    else
                    {
                        MessageBox.Show("没有信息可以导出");
                    }
                }
            }
        }

        /// <summary>
        /// 写出信息
        /// </summary>
        /// <param name="id">The id.</param>
        public void writeinfo(string id)
        {
            bool isFromMulti = false;
            MatchClass m = new MatchClass();
            string strFilename = multiSelectFileNameList[Int32.Parse(id) - 1];
            string strExtension = System.IO.Path.GetExtension(strFilename);
            if (strExtension.ToLower() != ".txt")
            {
                MessageBox.Show("文件格式不对!");
                return;
            }
            if (browserMain.Url.ToString().Contains("multiForm.html"))
            {
                browserMain.Document.GetElementById("openfile").SetAttribute("value", strFilename);
                isFromMulti = true;
            }
            ArrayList list = new ArrayList();
            list = m.readFile(strFilename);
            if (list != null && list[1] != null)
            {
                StringBuilder sb = new StringBuilder();
                int iTotal = (int)list[0];
                singleHandleTxtResultDataTable = (DataTable)list[1];
                sb.Append(@"<div class=""box_1"">");
                if (isFromMulti)
                {
                    sb.Append(@"<input type=""button"" class=""btnback"" id=""export"" onclick=""WriteResult()""  value="""" />");
                }
                sb.Append(@"<input type=""button"" class=""btn22"" id=""export"" onclick=""exportTable()""  value="""" /></div>");
                sb.Append("<p>本次总处理数据" + iTotal + "条,成功筛选数据" + singleHandleTxtResultDataTable.Rows.Count.ToString() + "条!</p><hr />");
                sb.Append("<table class=\"tab\"><tr class=\"tab_title\">\n");
                sb.Append(@"<td>船名</td><td>航次</td><td>到港日期</td><td>提单号</td><td>上箱号</td></tr>");
                if (singleHandleTxtResultDataTable != null)
                {
                    for (int i = 0; i < singleHandleTxtResultDataTable.Rows.Count; i++)
                    {
                        sb.Append(@"<tr class=""tab_trcurrent"">");
                        sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["船名"].ToString()));
                        sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["航次"].ToString()));
                        sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["到港日期"].ToString()));
                        sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["提单号"].ToString()));
                        sb.Append(string.Format("<td>{0}</td>", singleHandleTxtResultDataTable.Rows[i]["箱号"].ToString()));
                        sb.Append("</tr>");
                    }
                }
                sb.Append("</table>");
                var elementById = browserMain.Document.GetElementById("uploadResult");
                if (elementById != null)
                {
                    elementById.InnerHtml = sb.ToString();
                }
            }
        }

        /// <summary>
        /// 载入时方法
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void frmMain_Load(object sender, EventArgs e)
        {
            browserControl.Url = new Uri(baseDirectory + "Content/header.html");
            browserMain.Url = new Uri(baseDirectory + "Content/welcome.html");
            browserFooter.Url = new Uri(baseDirectory + "Content/footer.html");
        }

        /// <summary>
        /// 动态绑定响应时间
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="WebBrowserDocumentCompletedEventArgs"/> instance containing the event data.</param>
        private void browserControl_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            menuPageEvent.BindPage();
            if (multiSelectFileNameList != null)
            {
                multiSelectFileNameList.Clear();   
            }
            if (singleHandleTxtResultDataTable != null)
            {
                singleHandleTxtResultDataTable.Rows.Clear();
                singleHandleTxtResultDataTable.Dispose();
                singleHandleTxtResultDataTable = null;
            }
        }

        private void frmMain_ResizeEnd(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 文件内容切换响应
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="WebBrowserDocumentCompletedEventArgs"/> instance containing the event data.</param>
        private void browserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            browserMain.ObjectForScripting = this;
            mainPangeEvnet.BindPage();
            if (browserMain.Url.ToString().Contains("multiForm.html"))
            {
                multiSelectFileNameList.Clear();
            }
            string url = browserMain.Url.ToString();
            if (!(url.Contains("form.html") || url.Contains("welcome.html") || url.Contains("multiForm.html")))
            {
                browserMain.Url = new Uri("Content/welcome.html");
            }
        }

        /// <summary>
        ///改变option的接口.
        /// </summary>
        public void changeCheckOption()
        {
            string checkedStr = browserMain.Document.GetElementById("checkall").GetAttribute("checked");
            string value = checkedStr.Trim().ToLower().Equals("true") ? "checked" : "";
            foreach (HtmlElement checkboxControl in browserMain.Document.GetElementsByTagName("input"))
            {
                if (checkboxControl.Name.Equals("checkExportOption"))
                {
                    checkboxControl.SetAttribute("checked", value);   
                }
            }
        }
    }
}

Last edited May 22, 2014 at 9:45 AM by restmad, version 5