2018年7月22日22点38分

using NetOfficeInterface;
using log4net;
using NetOffice.WordApi.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using Office = NetOffice.OfficeApi;
using Word = NetOffice.WordApi;
using SW = System.Windows;
using System.Reflection;
using NetOfficeDataExplorer.Helper;
using Newtonsoft.Json.Linq;
using System.Data;

namespace NetOfficeDataExplorer
{
    class CommandExplore : InterfaceExecute
    {
        #region 属性
        public string Version { get => Helper.StaticData.Version; set => Helper.StaticData.Version = value; }
        public string UserName { get => Helper.StaticData.UserName; set => Helper.StaticData.UserName = value; }
        public string RabbionXML { get => ReadString("CommandExplore.xml"); }
        public object CurrentApp { get => Helper.StaticData.CurrentApp; set => Helper.StaticData.CurrentApp = value as Word.Application; }
        public object CurrentRabbionUI { get => Helper.StaticData.CurrentRabbionUI; set => Helper.StaticData.CurrentRabbionUI = value as Office.IRibbonUI; }
        public object LogError { get => Helper.StaticData._logError; set => Helper.StaticData._logError = value as ILog; }
        private Dictionary<Word.Document, bool> Docmodel = new Dictionary<Word.Document, bool>();
        #endregion

        public void ExecuteCommand(object control)
        {
            Office.IRibbonControl rbui = control as Office.IRibbonControl;
            if (control == null || rbui == null) return;
            try
            {
                switch (rbui.Id)
                {
                    #region 开始处理
                    case "btnStar"://开始处理
                        //newViews.ViewSimple().ShowDialog():
                        break;
                    case "btnBusinessNew"://新建业务模板
                        Word.Document doc = StaticData.CurrentApp.Documents.Add();
                        doc.Application.Caption = "业务模板";
                        Docmodel.Add(doc, false);
                        break;
                    case "btnBusinessOpen"://打开业务模板
                        OpenDoc(ref Docmodel, false, true);
                        break;
                    case "btnBusinessImport"://导入业务模板
                        OpenDoc(ref Docmodel, true, true);
                        break;
                    case "btnDevelopOpen"://打开开发模板
                        OpenDoc(ref Docmodel, false, false);
                        break;
                    case "btnDeveloplmport"://导入开发模板
                        OpenDoc(ref Docmodel, true, true);
                        break;
                    #endregion
                    case "btnXamlPage":
                        {

                        }
                        break;
                    case "btnExcelJson"://这里将Word中Excel生成JSON
                        {
                            //1.拿到Word中所有的Excel
                            //2.读取Excel数据生成Json

                            //获取Word页面第一个Table中的模板ID
                            var range = StaticData.CurrentApp.Documents.FirstOrDefault().Range();
                            char[] split = { '\r', '\a' };
                            var tt = range.Text.Split(split, StringSplitOptions.RemoveEmptyEntries);
                            string ModelId = tt != null && tt.Count() > 4 ? tt[3] : "";
                            foreach (var item in StaticData.CurrentApp.ActiveDocument.ContentControls)
                            {

                                XmlDocument xml = new XmlDocument();System.Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)
                                xml.LoadXml(item.Range.WordOpenXML);
                                XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
                                manager.AddNamespace("pkg", "http://schemas.microsoft.com/office/2006/xmlPackage");
                                var nodes = xml.SelectNodes("pkg:package/pkg:part[@pkg:contentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"]/pkg:binaryData", manager);
                                if (nodes.Count == 1)
                                {
                                    using (DataTable dt = new DataTable())
                                    {
                                        NPOI.XSSF.UserModel.XSSFWorkbook xssfworkbook =
                                            new NPOI.XSSF.UserModel.XSSFWorkbook(new System.IO.MemoryStream(Convert.FromBase64String(nodes[0].InnerText)));
                                        NPOI.SS.UserModel.ISheet sheet = xssfworkbook.GetSheetAt(0);
                                        NPOI.SS.UserModel.IRow header = sheet.GetRow(sheet.FirstRowNum);
                                        List<int> columns = new List<int>();
                                        for (int i = 0; i < header.LastCellNum; i++)
                                        {
                                            object obj = GetValueTypeForXLSX(header.GetCell(i) as NPOI.XSSF.UserModel.XSSFCell);
                                            if (obj == null || obj.ToString() == string.Empty)
                                            {
                                                dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                                                //continue;
                                            }
                                            else
                                                dt.Columns.Add(new DataColumn(obj.ToString()));
                                            columns.Add(i);
                                        }
                                        //判断标题是否包含标题和编码列
                                        if (dt.Columns.Contains("标题") && dt.Columns.Contains("编码"))
                                        {
                                            JObject root = new JObject{
                                                new JProperty("_id", item.Tag),
                                                new JProperty("modelId", "")
                                            };
                                            JObject c5 = new JObject {
                                                new JProperty("name", "编号"),
                                                new JProperty("type", "string"),
                                                new JProperty("keyPath", "_id"),
                                            };
                                            JObject c4 = new JObject { new JProperty("_id", c5) };
                                            //数据
                                            for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                                            {
                                                DataRow dr = dt.NewRow();
                                                bool hasValue = false;
                                                foreach (int j in columns)
                                                {
                                                    dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as NPOI.XSSF.UserModel.XSSFCell);
                                                    if (dr[j] != null && dr[j].ToString() != string.Empty)
                                                    {
                                                        hasValue = true;
                                                    }
                                                }
                                                if (hasValue)
                                                {
                                                    dt.Rows.Add(dr);
                                                }
                                            }
                                            if(dt.Rows.Count > 2) {
                                                continue;
                                            }
                                            foreach (DataRow row in dt.Rows)
                                            {
                                                if (row["标题"].ToString() == "序号")
                                                    continue;
                                                string[] codes = row["编码"].ToString().Split('/');
                                                JObject r = new JObject {
                                                new JProperty("name", row["标题"].ToString()),
                                                new JProperty("type", "string"),
                                                new JProperty("keyPath", codes[codes.Length-1]),
                                            };
                                                c4.Add(codes[0], r);
                                            }
                                            JObject c3 = new JObject {
                                                new JProperty("type","object"),
                                                new JProperty("properties",c4)
                                            };
                                            JObject c1 = new JObject{
                                                new JProperty("name", item.Title.Split('$')[0]),
                                                new JProperty("type", "array"),
                                                new JProperty("modelId", ModelId),//来源是元素清单Excel中模板ID
                                                new JProperty("keyPath", ""),
                                                new JProperty("searchKeys", new JArray()),
                                                new JProperty("items", c3),
                                            };
                                            root.Add("def", c1);

                                            string json = Newtonsoft.Json.JsonConvert.SerializeObject(root);
                                            item.Title = item.Title.Split('$')[0] + "$返回ID"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                            SW.MessageBox.Show(json,item.Title);
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

        #region Private Helper

        /// <summary>
        /// reads text from ressource
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        private static string ReadString(string fileName)
        {
            Assembly assembly = typeof(CommandExplore).Assembly;
            System.IO.Stream ressourceStream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + fileName);
            if (ressourceStream == null)
                throw (new System.IO.IOException("Error accessing resource Stream."));

            System.IO.StreamReader textStreamReader = new System.IO.StreamReader(ressourceStream);
            if (textStreamReader == null)
                throw (new System.IO.IOException("Error accessing resource File."));

            string text = textStreamReader.ReadToEnd();
            ressourceStream.Close();
            textStreamReader.Close();
            return text;
        }
        private void OpenDoc(ref Dictionary<Word.Document, bool> DocmodeI, bool ImportOrOpen, bool templateType)
        {
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.Filter = (ImportOrOpen ? "导入" : "打开") + (templateType ? "业务" : "开发") + "带宏模板文件|*.docm|模板文件|*.docx|所有文件|*.*";
            bool? IsSure = ofd.ShowDialog();
            if (IsSure.HasValue && IsSure.Value)
            {
                if (ImportOrOpen)
                {
                    Word.Document doc = StaticData.CurrentApp.ActiveDocument;
                    if (doc != null)
                    {
                        doc.Application.Caption = templateType ? "业务模板" : "开发模板";
                        //移动光标到文档末尾
                        doc.Application.Selection.EndKey(WdUnits.wdStory);
                        //导入模板数据
                        doc.Application.Selection.InsertFile(ofd.FileName);
                        Docmodel.Add(doc, templateType);
                    }

                }
                else
                {
                    Word.Document doc = StaticData.CurrentApp.Documents.Open(ofd.FileName);
                    if (doc != null)
                    {
                        doc.Application.Caption = templateType ? "业务模板" : "开发模板";
                        DocmodeI.Add(doc, templateType);
                    }
                }

            }
        }
        private void SetStylesByWord(string btn)
        {
            List<Word.Style> list = new List<Word.Style>();
            foreach (var item in StaticData.CurrentApp.ActiveDocument.Styles)
            {
                list.Add(item);
            }
            if (list.Where(a => a.NameLocal == btn).FirstOrDefault() == null)
            {

                //StaticData.CurrentApp.ActiveDocument.Styles(wdStyleHeading1)
            }
        }

        /// <summary>
        /// 获取单元格类型(xlsx)
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static object GetValueTypeForXLSX(NPOI.XSSF.UserModel.XSSFCell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case NPOI.SS.UserModel.CellType.Blank: //BLANK:
                    return null;
                case NPOI.SS.UserModel.CellType.Boolean: //BOOLEAN:
                    return cell.BooleanCellValue;
                case NPOI.SS.UserModel.CellType.Numeric: //NUMERIC:
                    return cell.NumericCellValue;
                case NPOI.SS.UserModel.CellType.String: //STRING:
                    return cell.StringCellValue;
                case NPOI.SS.UserModel.CellType.Error: //ERROR:
                    return cell.ErrorCellValue;
                case NPOI.SS.UserModel.CellType.Formula: //FORMULA:
                default:
                    return "=" + cell.CellFormula;
            }
        }
        #endregion
    }
}

 

posted @ 2018-07-22 22:40  落霞秋水  阅读(97)  评论(0编辑  收藏  举报