Beispiel #1
0
        /*public void ConvertToTable(string strTable)
         * {
         *  if (m_pSelection == null)
         *  {
         *      if (m_pDoc == null) m_pDoc = m_pApp.ActiveDocument;
         *      if (m_pApp == null) return;
         *
         *      m_pDoc.Select();
         *      m_pSelection = m_pApp.Selection;
         *      if (m_pSelection == null) return;
         *  }
         *
         *      if (m_pSelection == null) return;
         *      m_pSelection.Collapse(0);
         *
         *  object varInfo = m_pSelection.get_Information(MSWord.WdInformation.wdWithInTable);
         *  if (Convert.ToBoolean(varInfo) == true)
         *  {
         *      m_pDoc.Select();
         *      m_pSelection = m_pApp.Selection;
         *      if (m_pSelection == null) return;
         *      m_pSelection.Collapse(0);
         *  }
         *
         *      m_pSelection.Font.Bold = 0;
         *      m_pSelection.Text = strTable;
         *
         *  m_pSelection.Paragraphs.SpaceAfter = 0;
         *  m_pSelection.Paragraphs.SpaceBefore = 0;
         *
         *  m_pTable = m_pSelection.ConvertToTable(1, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
         *      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
         *      Type.Missing, 0, 0);
         *
         *  if (m_pTable == null) return;
         *
         *      MSWord.Rows pRows = m_pSelection.Rows;
         *      pRows.AllowBreakAcrossPages = 0;
         *  //m_pApp.WordBasic.OpenOrCloseParaBelow;
         *  //m_pApp.WordBasic.OpenOrCloseParaAbove;
         *
         *      m_pSelection.Collapse();
         *
         *      MSWord.Borders pBorders = m_pTable.Borders;
         *      if (pBorders == null) return;
         *      pBorders.Enable = 1;
         * }*/

        public void SetTableFont(FontParams fp, int indTable = -1)
        {
            GetTableReference(indTable);

            m_pTable.Select();
            PutFont(fp, m_pApp.Selection);

            if (fp.styleName != "")
            {
                m_pSelection = m_pApp.Selection;
                m_pSelection.Paragraphs.SpaceAfter      = 0;
                m_pSelection.Paragraphs.SpaceBefore     = 0;
                m_pSelection.Paragraphs.LineSpacingRule = MSWord.WdLineSpacing.wdLineSpaceSingle;
            }
        }
Beispiel #2
0
 /// <summary>
 /// 在指定位置上插入表格
 /// </summary>
 /// <param name="type">插入类型</param>
 /// <param name="value">二维字符串数组</param>
 /// <param name="wordStyle">文字外观</param>
 public void WriteTableToDoc <T>(InsertionPoint type, T[,] value, WordTableStyle wordStyle = WordTableStyle.LightGrid)
 {
     try
     {
         int        rowCount = value.GetLength(0);
         int        colCount = value.GetLength(1);
         Word.Range r        = GetRange(type);
         Word.Table tab      = _wordTables.Add(r, rowCount, colCount);
         tab.set_Style(wordStyle);
         tab.Select();
         for (int i = 0; i < rowCount; i++)
         {
             for (int j = 0; j < colCount; j++)
             {
                 tab.Cell(i + 1, j + 1).Select();
                 _engine.Selection.TypeText(value[i, j].ToString());
             }
         }
     }
     catch (Exception ex)
     {
         ErrorParser(ex);
         return;
     }
 }
        /// <summary>
        /// 断开当前表格的域链接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DiscLink_Click(object sender, RibbonControlEventArgs e)
        {
            WordApp = Globals.ThisAddIn.Application;
            WordDoc = WordApp.ActiveDocument;

            //选中整个表格
            Word.Table TempTable = WordApp.Selection.Tables[1];
            TempTable.Select();

            //获取域
            WordApp.Selection.Next(Word.WdUnits.wdWord, 2).Select();
            WordApp.Selection.PreviousField();
            WordApp.Selection.Fields[1].Unlink();

            TempTable.Select();
        }
Beispiel #4
0
        //public static void createNewWord(Object path, DataTable list_tables)
        //{
        //    msword.Application tableApp = new msword.ApplicationClass();
        //    object nothing = Missing.Value;
        //    msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);
        //    //msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, 3, 2, ref nothing, ref nothing);
        //    msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, list_tables.Rows.Count + 1, list_tables.Columns.Count, ref nothing, ref nothing);
        //    table.Borders.Enable = 1;
        //    table.Borders.OutsideLineStyle = msword.WdLineStyle.wdLineStyleSingle;
        //    for (int l = 0; l < list_tables.Columns.Count; l++)
        //    {
        //        table.Cell(1, l + 1).Range.Text = list_tables.Columns[l].ColumnName;
        //    }

        //    for (int i = 0; i < list_tables.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < list_tables.Columns.Count; j++)
        //        {
        //            table.Cell(i + 2, j + 1).Range.Text = list_tables.Rows[i][j].ToString();
        //        }
        //    }

        //    object moveUnit = msword.WdUnits.wdLine;
        //    object moveCount = list_tables.Rows.Count*2+2;
        //    table.Cell(1, 1).Range.Select(); //获取焦点
        //    tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing);
        //    tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing);
        //    tableApp.Selection.TypeParagraph();

        //    //插入图片
        //    string FileName = Application.StartupPath + @"\Image\2.jpg";//图片所在路径
        //    object LinkToFile = false;
        //    object SaveWithDocument = true;
        //    object Anchor = wordDoc.Paragraphs.Last.Range;
        //    //object Anchor = tableApp.Selection.Range;
        //    wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

        //    msword.Table table2 = wordDoc.Tables.Add(tableApp.Selection.Range, list_tables.Rows.Count + 1, list_tables.Columns.Count, ref nothing, ref nothing);
        //    table2.Borders.Enable = 1;
        //    table2.Borders.OutsideLineStyle = msword.WdLineStyle.wdLineStyleSingle;
        //    for (int l = 0; l < list_tables.Columns.Count; l++)
        //    {
        //        table2.Cell(1, l + 1).Range.Text = list_tables.Columns[l].ColumnName;
        //    }

        //    for (int i = 0; i < list_tables.Rows.Count; i++)
        //    {
        //        for (int j = 0; j < list_tables.Columns.Count; j++)
        //        {
        //            table2.Cell(i + 2, j + 1).Range.Text = list_tables.Rows[i][j].ToString();
        //        }
        //    }

        //    /*3、导入模板
        //    object oMissing = System.Reflection.Missing.Value;
        //    Word._Application oWord;
        //    Word._Document oDoc;
        //    oWord = new Word.Application();
        //    oWord.Visible = true;
        //    object fileName = @"E:XXXCCXTest.doc";
        //    oDoc = oWord.Documents.Add(ref fileName, ref oMissing, ref oMissing, ref oMissing);*/



        //    //wordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
        //    //wordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
        //    //将图片设置为四周环绕型
        //    //Microsoft.Office.Interop.Word.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
        //    // s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare;

        //    object format = msword.WdSaveFormat.wdFormatDocumentDefault;
        //    wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing);
        //    wordDoc.Close(ref nothing, ref nothing, ref nothing);
        //    tableApp.Quit(ref nothing, ref nothing, ref nothing);
        //}

        //public static void createNewWord2(Object path, List<DataTable> list_tables,string image_path)
        //{
        //    msword.Application tableApp = new msword.ApplicationClass();
        //    object nothing = Missing.Value;
        //    msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);

        //    //msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, 3, 2, ref nothing, ref nothing);
        //    for (int k = 0; k < list_tables.Count; k++)
        //    {
        //        msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, list_tables[k].Rows.Count + 1, list_tables[k].Columns.Count, ref nothing, ref nothing);
        //        table.Borders.Enable = 1;

        //        table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
        //        for (int l = 0; l < list_tables[k].Columns.Count; l++)
        //        {
        //            table.Cell(1, l + 1).Range.Text = list_tables[k].Columns[l].ColumnName;
        //        }

        //        for (int i = 0; i < list_tables[k].Rows.Count; i++)
        //        {
        //            for (int j = 0; j < list_tables[k].Columns.Count; j++)
        //            {
        //                table.Cell(i + 2, j + 1).Range.Text = list_tables[k].Rows[i][j].ToString();
        //            }
        //        }
        //        object moveUnit = msword.WdUnits.wdLine;
        //        object moveCount = list_tables[k].Rows.Count * 2 + 2;
        //        table.Cell(1, 1).Range.Select(); //获取焦点

        //        object dummy = System.Reflection.Missing.Value;
        //        object what = msword.WdGoToItem.wdGoToLine;
        //        object which = msword.WdGoToDirection.wdGoToFirst;
        //        object count = list_tables[k].Rows.Count+1;
        //        wordDoc.Application.ActiveDocument.GoTo(ref what, ref which, ref count, ref dummy);

        //        //tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing);
        //        //tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing);
        //        //tableApp.Selection.TypeParagraph();
        //        //OperatePicture.ExportPicture(list_types[k]+"_PLOT");
        //        //插入图片
        //        string FileName = image_path;//图片所在路径
        //        object LinkToFile = false;
        //        object SaveWithDocument = true;
        //        //object Anchor = wordDoc.Paragraphs.Last.Range;
        //        object Anchor = wordDoc.Paragraphs.Last.Range;
        //        wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);

        //    }
        //    object format = msword.WdSaveFormat.wdFormatDocumentDefault;
        //    wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing);
        //    wordDoc.Close(ref nothing, ref nothing, ref nothing);
        //    tableApp.Quit(ref nothing, ref nothing, ref nothing);
        //}
        #endregion
        public static void createNewWord3(Object path, Dictionary <DataTable, string> dicts)
        {
            msword.Application tableApp = new msword.ApplicationClass();
            object             nothing  = Missing.Value;

            msword.Document wordDoc = tableApp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);
            foreach (KeyValuePair <DataTable, string> pair in dicts)
            {
                //wordDoc.Application.Selection.TypeParagraph();
                //wordDoc.Application.Selection.TypeText("表一");
                //wordDoc.Application.Selection.TypeParagraph();

                DataTable    item  = pair.Key;
                msword.Table table = wordDoc.Tables.Add(tableApp.Selection.Range, item.Rows.Count + 1, item.Columns.Count, ref nothing, ref nothing);
                table.Borders.Enable          = 1;
                table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                for (int l = 0; l < item.Columns.Count; l++)
                {
                    table.Cell(1, l + 1).Range.Text = item.Columns[l].ColumnName;
                }

                for (int i = 0; i < item.Rows.Count; i++)
                {
                    for (int j = 0; j < item.Columns.Count; j++)
                    {
                        table.Cell(i + 2, j + 1).Range.Text = item.Rows[i][j].ToString();
                    }
                }
                //wordDoc.Application.Selection.Font.Size = 16;
                //wordDoc.Application.Selection.Font.Size = 10;
                //wordDoc.Application.Selection.Font.Bold = 10;
                object moveUnit  = msword.WdUnits.wdLine;
                object moveCount = 2;
                //table.Cell(1, 1).Range.Select(); //获取焦点
                table.Select();
                tableApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref nothing);
                //tableApp.ActiveWindow.Selection.EndKey(ref moveUnit, ref nothing);
                tableApp.Selection.TypeParagraph();
                //tableApp.Selection.TypeParagraph();

                //OperatePicture.ExportPicture(list_types[k]+"_PLOT");
                //插入图片
                string FileName = pair.Value;//图片所在路径
                if (!string.IsNullOrEmpty(FileName))
                {
                    object LinkToFile       = false;
                    object SaveWithDocument = true;
                    //object Anchor = wordDoc.Paragraphs.Last.Range;
                    object Anchor = wordDoc.Paragraphs.Last.Range;
                    wordDoc.Application.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument);
                    //wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                }
            }
            object format = msword.WdSaveFormat.wdFormatDocumentDefault;

            wordDoc.SaveAs(ref path, ref format, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing);
            wordDoc.Close(ref nothing, ref nothing, ref nothing);
            tableApp.Quit(ref nothing, ref nothing, ref nothing);
        }
Beispiel #5
0
        public void InsertRowsInTable(int indTable, int nCount)
        {
            if (nCount <= 0)
            {
                return;
            }

            if (m_pApp != null)
            {
                if (m_pDoc == null)
                {
                    m_pDoc = m_pApp.ActiveDocument;
                }
                if (m_pDoc == null)
                {
                    return;
                }

                MSWord.Tables tables = m_pDoc.Tables;
                if (tables.Count == 0)
                {
                    return;
                }

                m_pTable = tables[indTable];
                if (m_pTable == null)
                {
                    return;
                }

                m_pTable.Select();

                MSWord.Selection pSel = m_pApp.Selection;
                pSel.InsertRowsBelow(nCount);

                m_pDoc.Select();
                m_pSelection = m_pApp.Selection;
                if (m_pSelection == null)
                {
                    return;
                }
                m_pSelection.Collapse(0);
            }
        }
Beispiel #6
0
        public void InsertTableCell(int insertBeforeColumnIndex, string cellText, string tableName = "")
        {
            if (String.IsNullOrEmpty(tableName))
            {
                object t   = _document.Application.Selection.Information[WordOM.WdInformation.wdWithInTable];
                var    isT = false;
                Boolean.TryParse(t.ToString(), out isT);
                if (isT)
                {
                    WordOM.Table table = _document.Application.Selection.Tables[1];
                    table.Select();
                    _document.Application.Selection.InsertCells(WordOM.WdInsertCells.wdInsertCellsEntireColumn);
                }
            }
            else
            {
                foreach (WordOM.Table table in _document.Tables)
                {
                    if (String.Equals(tableName, table.Title, StringComparison.OrdinalIgnoreCase))
                    {
                        WordOM.Column col = table.Columns[insertBeforeColumnIndex];

                        col.Select();
                        _document.Application.Selection.InsertColumnsRight();
                        table.Columns[table.Columns.Count].Cells[1].Range.Text = cellText;

                        //table.Rows[1].Cells[insertBeforeColumnIndex].Select();
                        //_document.Application.Selection.InsertCells();
                        //table.Cell(1, table.Columns.Count).Range.Text = cellText;

                        // table.Columns.Add(table.Columns[insertBeforeColumnIndex]).Cells[insertBeforeColumnIndex + 1].Range.Text = cellText;
                        //    table.Rows[1].Cells[2].Select();
                        //    _document.Application.Selection.InsertColumnsRight();
                        ////    _document.Application.Selection.InsertCells();
                        //    table.Cell(1, table.Columns.Count).Range.Text = cellText;
                    }
                }
            }
        }
Beispiel #7
0
		/// <summary>
		/// Word operation
		/// </summary>
		/// <param name="command"></param>
		/// <param name="sArg"></param>
		/// <param name="nArg1"></param>
		/// <param name="nArg2"></param>
		/// <param name="nArg3"></param>
		/// <param name="nArg4"></param>
		/// <returns></returns>
		public static string Call(
			string command,
			string sArg,
			int nArg1,
			int nArg2,
			int nArg3,
			int nArg4,
			bool bArg)
		{

			object missingObj = System.Reflection.Missing.Value; // missing object parameter 

			if (SS.I.DebugFlags[5] != null) // dump out command for debug
			{
				ClientLog.Message("Call " + command + " " + sArg);
			}

			try // catch any Word exception
			{

				//******************************************************************************  
				if (Lex.Eq(command, "CreateObject"))  // create the word object
				//******************************************************************************  
				{
					try
					{
						WdApp = new Microsoft.Office.Interop.Word.Application();
					}
					catch (Exception ex)
					{
						return "Word failed to start";
					}

				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Quit"))
				{ // quit application
					//******************************************************************************  

					//Microsoft.Office.Interop.Word.Application.
					WdApp.Quit(ref missingObj, ref missingObj, ref missingObj);

					//	AutoWrap(DISPATCH_METHOD, NULL, WdApp, L"Quit", 0);
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Cells.SetWidth"))
				{
					//******************************************************************************  
					WdSel.Cells.SetWidth(nArg1, WdRulerStyle.wdAdjustNone);
#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg1,nArg1);  // width in points
	SETLONG(Arg2,wdAdjustNone); // ruler style, required sArg
	AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Setwidth", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "DeleteObject"))
				{
					//******************************************************************************  
					WdSel = null;
					WdTable = null;
					WdTables = null;
					WdDoc = null;
					WdDocs = null;
					WdApp = null;
#if false
	// Release references, must do lower to higher level...
	release_obj(WdTemp);
	release_obj(WdSel);
	release_obj(WdTable);
	release_obj(WdTables);
	release_obj(WdDoc);
	release_obj(WdDocs);
	release_obj(WdApp);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Close"))
				{
					//******************************************************************************  
					//      excelobj.ActiveWorkbook.Close False ' no prompt for save
					((_Document)WdDoc).Close(ref missingObj, ref missingObj, ref missingObj);

					//	SETLONG(SaveChanges,wdSaveChanges); // don't prompt
					//	AutoWrap(DISPATCH_METHOD, NULL, WdDoc, L"Close", 1, SaveChanges);
					//	VariantClear(&SaveChanges);
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Documents.Add"))
				{ // Add a new document
					//******************************************************************************  

					WdDocs = WdApp.Documents;
					WdDoc = WdDocs.Add(ref missingObj, ref missingObj, ref missingObj, ref missingObj);

#if false
	release_obj(WdDocs); // Get active documents
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdApp, L"Documents", 0);   // Get Documents collection
	WdDocs = result.pdispVal;

	release_obj(WdDoc); // Add new document
	AutoWrap(DISPATCH_METHOD, &result, WdDocs, L"Add", 0);
	WdDoc = result.pdispVal;
#endif

					if (WdDoc == null) return ("Error adding document");
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "EndKey"))
				{
					//******************************************************************************  
					Object unit = nArg1;
					WdSel.HomeKey(ref unit, ref missingObj);

					//	SETLONG(Arg,nArg1); 
					//	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg);
					//	VariantClear(&Arg);

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Name"))
				{
					//******************************************************************************  
					//      WordObj.Selection.Font.Name = sArg
					WdSel.Font.Name = sArg;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETSTR(Arg,sArg);  // set font name
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Name", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Size"))
				{
					//******************************************************************************  
					//      WordObj.Selection.Font.Size = sArg

					WdSel.Font.Size = nArg1;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1);  // set font size
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Size", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Bold"))
				//******************************************************************************  
				{
					if (bArg) WdSel.Font.Bold = -1;
					else WdSel.Font.Bold = 0;
				}

	//******************************************************************************  
				else if (Lex.Eq(command, "Font.Italic"))
				//******************************************************************************  
				{
					if (bArg) WdSel.Font.Italic = -1;
					else WdSel.Font.Italic = 0;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Font.Subscript"))
				//******************************************************************************  
				{
					WdSel.Font.Subscript = nArg1;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1);  // set font size
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Subscript", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Superscript"))
				{
					//******************************************************************************  
					WdSel.Font.Superscript = nArg1;

#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Font", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1);  // set font size
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Superscript", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "SetDefaultCellStyle"))
				//******************************************************************************  
				{ // Cell style (e.g. backcolor) automatically carries down do successive
					// rows and must be explicitly reset

					//			int rgbBlack = 0;
					//			if (WdSel.Font.Color != (Microsoft.Office.Interop.Word.WdColor)rgbBlack)
					//				WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgbBlack;

					//			int rgbWhite = 255 + 255 * 256 + 255 * 65536;
					//			if (WdSel.Cells.Shading.BackgroundPatternColor != (Microsoft.Office.Interop.Word.WdColor)rgbWhite)
					//				WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgbWhite;

					if (WdSel.Font.Color != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic)
						WdSel.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;

					if (WdSel.Cells.Shading.BackgroundPatternColor != Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic)
						WdSel.Cells.Shading.BackgroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Font.Color"))
				//******************************************************************************  
				{
					Color c = Color.FromArgb(nArg1);
					int rgb = c.R + c.G * 256 + c.B * 65536;
					WdSel.Font.Color = (Microsoft.Office.Interop.Word.WdColor)rgb;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "BackColor"))
				//******************************************************************************  
				{
					Color c = Color.FromArgb(nArg1);
					int rgb = c.R + c.G * 256 + c.B * 65536;
					WdSel.Cells.Shading.BackgroundPatternColor = (Microsoft.Office.Interop.Word.WdColor)rgb;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "HomeKey"))
				{
					//******************************************************************************  
					Object unit = nArg1;
					WdSel.HomeKey(ref unit, ref missingObj);
#if false
	SETLONG(Arg,nArg1); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"HomeKey", 1, Arg);
	VariantClear(&Arg);
#endif
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InlineShapes.AddPicture"))
				{ // insert image from file
					//******************************************************************************  
					InlineShape ils = WdSel.InlineShapes.AddPicture(sArg, ref missingObj, ref missingObj, ref missingObj);
					ils.Width = nArg1;
					ils.Height = nArg2;
#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"InlineShapes", 0);
	WdTemp = result.pdispVal;

	SETSTR(Filename,sArg);  // filename
	SETLONG(Width,nArg1); // in points
	SETLONG(Height,nArg2);

	AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"AddPicture", 1, Filename);
	release_obj(WdTemp);
	WdTemp = result.pdispVal; // new shape object

	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Width", 1, Width);

	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdTemp, L"Height", 1, Height);

	VariantClear(&Filename);
	VariantClear(&Width);
	VariantClear(&Height);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InsertBreak"))
				{
					//******************************************************************************  
					object type = nArg1;
					WdSel.InsertBreak(ref type);

					//	SETLONG(Arg,nArg1); 
					//	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertBreak", 1, Arg);
					//	VariantClear(&Arg);

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InsertSymbol"))
				{
					//******************************************************************************  
					// InsertSymbol(CharacterNumber as Long, Font as String)
					int characterNumber = nArg1;
					object font = sArg;
					WdSel.InsertSymbol(characterNumber, ref font, ref missingObj, ref missingObj);
#if false
	SETLONG(Arg,nArg1); // get char number
	SETSTR(Arg2,sArg); // get font
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"InsertSymbol", 2, Arg2, Arg);
	VariantClear(&Arg);
	VariantClear(&Arg2);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Cells.Merge"))
				{ // merge cells together
					//******************************************************************************  
					WdSel.Cells.Merge();
#if false
	release_obj(WdTemp); // get current font object
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"Cells", 0);
	WdTemp = result.pdispVal;

	AutoWrap(DISPATCH_METHOD, &result, WdTemp, L"Merge", 0);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveLeft"))
				{ // units, count
					//******************************************************************************  
					if (nArg2 <= 0) nArg2 = 1;

					object unit = nArg1;
					object count = nArg2;
					WdSel.MoveLeft(ref unit, ref count, ref missingObj);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveLeft", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveRight"))
				{ // units, count, extend
					//******************************************************************************  
					object extend;
					if (nArg2 <= 0) nArg2 = 1;

					object unit = nArg1;
					object count = nArg2;
					if (nArg3 <= 0) extend = missingObj;
					else extend = nArg3;

					WdSel.MoveRight(ref unit, ref count, ref extend);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	SETLONG(Arg3,nArg3); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveRight", 3, Arg3, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
	VariantClear(&Arg3);
#endif

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveDown"))
				{ // units, count
					//******************************************************************************  
					if (nArg2 <= 0) nArg2 = 1;
					object unit = nArg1;
					object count = nArg2;
					WdSel.MoveDown(ref unit, ref count, ref missingObj);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveDown", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif
					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "MoveUp"))
				{ // units, count
					//******************************************************************************  
					if (nArg2 <= 0) nArg2 = 1;
					object unit = nArg1;
					object count = nArg2;
					WdSel.MoveUp(ref unit, ref count, ref missingObj);
#if false
	SETLONG(Arg1,nArg1); 
	SETLONG(Arg2,nArg2); 
	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"MoveUp", 2, Arg2, Arg1);
	VariantClear(&Arg1);
	VariantClear(&Arg2);
#endif

					UpdateSelection(); // update selection
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PageSetup.Orientation"))
				{
					//******************************************************************************  

					if (nArg1 == 0)
						WdSel.PageSetup.Orientation = WdOrientation.wdOrientPortrait;
					WdSel.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
#if false
	release_obj(WdTemp);
	AutoWrap(DISPATCH_PROPERTYGET, &result, WdSel, L"PageSetup", 0);
	WdTemp = result.pdispVal;

	SETLONG(Arg,nArg1); 
	AutoWrap(DISPATCH_PROPERTYPUT, &result, WdTemp, L"Orientation", 1, Arg);
	VariantClear(&Arg);
#endif
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PageSetup.Margins"))
				{
					//******************************************************************************  
					WdSel.PageSetup.TopMargin = nArg1;
					WdSel.PageSetup.BottomMargin = nArg2;
					WdSel.PageSetup.LeftMargin = nArg3;
					WdSel.PageSetup.RightMargin = nArg4;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PageSetup.PageSize"))
				{
					//******************************************************************************  
					WdSel.PageSetup.PageWidth = nArg1;
					WdSel.PageSetup.PageHeight = nArg2;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "ParagraphFormat.Alignment"))
				{
					//******************************************************************************  
					WdSel.ParagraphFormat.Alignment = (WdParagraphAlignment)nArg1;
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Cells.VerticalAlignment"))
				//******************************************************************************  
				{
					WdSel.Cells.VerticalAlignment = (WdCellVerticalAlignment)nArg1;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Paste"))
				//******************************************************************************  
				{
					WdSel.Paste();
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "PasteSpecial"))
				{
					//******************************************************************************  
					//	PasteSpecial(IconIndex, Link, Placement, DisplayAsIcon, DataType)

					object iconIndex = 0;
					object link = false;
					object placement = InLine;
					object displayAsIcon = false;
					object dataType = nArg1; // set type of data to paste

					//	ClientLog.Message("Before PasteSpecial"); // TST & PRD 
					WdSel.PasteSpecial(ref iconIndex, ref link, ref placement, ref displayAsIcon,
						ref dataType, ref missingObj, ref missingObj);
					//	ClientLog.Message("After PasteSpecial");
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "InsertStructure"))
				//******************************************************************************  
				// Selection.InlineShapes.AddOLEObject ClassType:="ISISServer", FileName:= _
				//  "C:\Isis\sketch1-small.skc", LinkToFile:=False, DisplayAsIcon:=False
				// This is significantly slower than a paste
				{
					object classType = "ISISServer";
					object fileName = sArg;

					WdSel.InlineShapes.AddOLEObject(
						ref classType,
						ref fileName,
						ref missingObj,
						ref missingObj,
						ref missingObj,
						ref missingObj,
						ref missingObj,
						ref missingObj);
				}

			//******************************************************************************  
				else if (Lex.Eq(command, "Rows.AllowBreakAcrossPages"))
				{ // keep all contents of row on same page
					//******************************************************************************  

					WdSel.Rows.AllowBreakAcrossPages = nArg1;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "Rows.HeadingFormat"))
				{ // mark rows as headings
					//******************************************************************************  

					WdSel.Rows.HeadingFormat = nArg1;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "SaveAs"))
				{ // save file in .doc format
					//******************************************************************************  
					try { File.Delete(sArg); } // delete any existing file
					catch (Exception ex) { };
					object fileName = sArg;
					object fileFormat = WdSaveFormat.wdFormatDocument;

					WdDoc.SaveAs(
						ref fileName, // FileName 
						ref fileFormat, // FileFormat 
						ref missingObj, // LockComments 
						ref missingObj, // Password 
						ref missingObj, // AddToRecentFiles 
						ref missingObj, // WritePassword 
						ref missingObj, // ReadOnlyRecommended 
						ref missingObj, // EmbedTrueTypeFonts 
						ref missingObj, // SaveNativePictureFormat
						ref missingObj,	// SaveFormsData 
						ref missingObj,	// SaveAsAOCELetter
						ref missingObj,	// Encoding
						ref missingObj,	// InsertLineBreaks 
						ref missingObj, // AllowSubstitutions 
						ref missingObj, // LineEnding 
						ref missingObj); // AddBiDiMarks
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "ScreenUpdating"))
				{
					//******************************************************************************  
					WdApp.ScreenUpdating = bArg;
				}

		//******************************************************************************  
				else if (Lex.Eq(command, "SelectColumn"))
				{ // select current column of table
					//******************************************************************************  
					WdSel.SelectColumn();
					//	AutoWrap(DISPATCH_METHOD, NULL, WdSel, L"SelectColumn", 0); 
					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "SelectRow"))
				{ // select current row of table
					//******************************************************************************  
					WdSel.SelectRow();

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "Tables.Add"))
				{ // number of rows & cols supplied
					//******************************************************************************  

					WdTables = WdDoc.Tables;
					Microsoft.Office.Interop.Word.Range range = WdSel.Range;
					int numRows = nArg1;
					int numCols = nArg2;
					WdTable = WdTables.Add(range, numRows, numCols, ref missingObj, ref missingObj);
					WdTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
					WdTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "TableSelect"))
				{
					//******************************************************************************  

					WdTable.Select();

					UpdateSelection(); // update selection
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "TypeParagraph"))
				{
					//******************************************************************************  
					WdSel.TypeParagraph();

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "TypeText"))
				{
					//******************************************************************************  
					WdSel.TypeText(sArg);
					//	SETSTR(Arg,sArg); 
					//	AutoWrap(DISPATCH_METHOD, &result, WdSel, L"TypeText", 1, Arg);
					//	VariantClear(&Arg);

					UpdateSelection();
				}

				//******************************************************************************  
				else if (Lex.Eq(command, "Visible"))
				{
					//******************************************************************************  
					WdApp.Visible = bArg;
#if false
	SETBOOL(True,1);
	SETBOOL(False,0);
	if (strcmpi((CCP)sArg,"true)) 
	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, True);

	else 	AutoWrap(DISPATCH_PROPERTYPUT, NULL, WdApp, L"Visible", 1, False);
#endif
				}

		//******************************************************************************  
				else throw new Exception("WordOp - Invalid operation " + command);
				//******************************************************************************  

				return ""; // everything must be ok

			} // end of try
Beispiel #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            //新建文档
            // Word.Application newapp = new Word.Application();//用这句也能初始化
            Word.Application newapp = new Word.ApplicationClass();
            Word.Document    newdoc;
            object           nothing = System.Reflection.Missing.Value;                                //用于作为函数的默认参数

            newdoc         = newapp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing); //生成一个word文档
            newapp.Visible = true;                                                                     //是否显示word程序界面

            //页面设置
            //newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape ;
            //newdoc.PageSetup.PageWidth = newapp.CentimetersToPoints(21.0f);
            //newdoc.PageSetup.PageHeight = newapp.CentimetersToPoints(29.7f);
            newdoc.PageSetup.PaperSize      = Word.WdPaperSize.wdPaperA4;
            newdoc.PageSetup.Orientation    = Word.WdOrientation.wdOrientPortrait;
            newdoc.PageSetup.TopMargin      = 57.0f;
            newdoc.PageSetup.BottomMargin   = 57.0f;
            newdoc.PageSetup.LeftMargin     = 57.0f;
            newdoc.PageSetup.RightMargin    = 57.0f;
            newdoc.PageSetup.HeaderDistance = 30.0f;//页眉位置

            //设置页眉
            newapp.ActiveWindow.View.Type              = Word.WdViewType.wdOutlineView;       //视图样式。
            newapp.ActiveWindow.View.SeekView          = Word.WdSeekView.wdSeekPrimaryHeader; //进入页眉设置,其中页眉边距在页面设置中已完成
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            //插入页眉图片
            string headerfile = "d:\\header.jpg";

            // this.outpicture(headerfile, Properties.Resources.header);
            Word.InlineShape shape1 = newapp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref nothing, ref nothing, ref nothing);
            shape1.Height = 30;
            shape1.Width  = 80;
            newapp.ActiveWindow.ActivePane.Selection.InsertAfter("中建东北院");
            //去掉页眉的那条横线
            newapp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone;
            newapp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false;
            newapp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;//退出页眉设置

            //添加页码
            Word.PageNumbers pns = newapp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;
            pns.NumberStyle               = Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash;
            pns.HeadingLevelForChapter    = 0;
            pns.IncludeChapterNumber      = false;
            pns.ChapterPageSeparator      = Word.WdSeparatorType.wdSeparatorHyphen;
            pns.RestartNumberingAtSection = false;
            pns.StartingNumber            = 0;
            object pagenmbetal = Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
            object first       = true;

            newapp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);

            //文字设置(Selection表示当前选择集,如果当前没有选择对像,则指对光标所在处进行设置)
            newapp.Selection.Font.Size  = 14;
            newapp.Selection.Font.Bold  = 0;
            newapp.Selection.Font.Color = Word.WdColor.wdColorBlack;
            newapp.Selection.Font.Name  = "宋体";

            //段落设置
            newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
            newapp.Selection.ParagraphFormat.LineSpacing     = 20;
            newapp.Selection.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            newapp.Selection.ParagraphFormat.FirstLineIndent = 30;
            //  newdoc.Content.InsertAfter(WindowsFormsApplication1.Properties.Resources.PreViewWords);



            //插入公式
            object oEndOfDoc = "\\endofdoc";

            Word.Range rang1             = newdoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            object     fieldType         = Word.WdFieldType.wdFieldEmpty;
            object     formula           = @"eq \i(a,b,ξxdx)";
            object     presrveFormatting = false;

            rang1.Text           = formula.ToString();
            rang1.Font.Size      = 14;
            rang1.Font.Bold      = 0;
            rang1.Font.Subscript = 0;
            rang1.Font.Color     = Word.WdColor.wdColorBlue;
            rang1.Font.Name      = "宋体";
            rang1.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            rang1.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphRight;
            newdoc.Fields.Add(rang1, ref fieldType, ref formula, ref presrveFormatting);

            //将文档的前三个字替换成"asdfasdf",并将其颜色设为蓝色
            object start = 0;
            object end   = 3;

            Word.Range rang2 = newdoc.Range(ref start, ref end);
            rang2.Font.Color = Word.WdColor.wdColorBlue;
            rang2.Text       = "as签";

            //将文档开头的"as"替换成"袁波"
            rang1.Start = 0;
            rang1.End   = 2;
            rang1.Text  = "这是一个";
            rang1.InsertAfter("书");
            //rang1.Select();
            object codirection = Word.WdCollapseDirection.wdCollapseStart;

            rang1.Collapse(ref codirection);//将rang1的起点和终点都定于起点或终点

            //对前三个字符进行加粗
            newdoc.Range(ref start, ref end).Bold = 1;
            object rang = rang2;

            newdoc.Bookmarks.Add("yb", ref rang);


            object unite = Word.WdUnits.wdStory;

            newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
            newapp.Selection.Font.Size = 10;
            newapp.Selection.TypeText("...............................(式1)\n");


            //插入图片
            newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
            //newapp.Selection.HomeKey(ref unite, ref nothing);//将光标移至文开头
            newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            newapp.Selection.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            object LinkToFile       = false;
            object SaveWithDocument = true;
            object Anchor           = newapp.Selection.Range;
            string picname          = "d:\\kk.jpg";

            //     this.outpicture(picname, Properties.Resources.IMG_2169);
            newdoc.InlineShapes.AddPicture(picname, ref LinkToFile, ref SaveWithDocument, ref Anchor);
            newdoc.InlineShapes[1].Height = 200;
            newdoc.InlineShapes[1].Width  = 200;
            newdoc.Content.InsertAfter("\n");
            newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.Font.Size = 10;
            newapp.Selection.TypeText("图1 袁冶\n");
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            newdoc.Content.InsertAfter("\n");
            newdoc.Content.InsertAfter("\n");

            //用这种方式也可以插入公式,并且这种方法更简单
            newapp.Selection.Font.Size = 14;
            newapp.Selection.InsertFormula(ref formula, ref nothing);
            newapp.Selection.Font.Size = 10;
            newapp.Selection.TypeText("..............................(式2)\n");
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.TypeText("表1 电子产品\n");

            //插入表格
            Word.Table table1 = newdoc.Tables.Add(newapp.Selection.Range, 4, 3, ref nothing, ref nothing);
            newdoc.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";
            newdoc.Tables[1].Cell(1, 2).Range.Text = "电脑";
            newdoc.Tables[1].Cell(1, 3).Range.Text = "手机";
            newdoc.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
            newdoc.Tables[1].Cell(3, 1).Range.Text = "价格(元)";
            newdoc.Tables[1].Cell(4, 1).Range.Text = "共同信息";
            newdoc.Tables[1].Cell(4, 2).Range.Text = "信息A";
            newdoc.Tables[1].Cell(4, 3).Range.Text = "信息B";


            table1.Select();
            table1.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中
            newapp.Selection.Cells.VerticalAlignment   = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.Cells.HeightRule          = Word.WdRowHeightRule.wdRowHeightExactly;
            newapp.Selection.Cells.Height                          = 40;
            table1.Rows[2].Height                                  = 20;
            table1.Rows[3].Height                                  = 20;
            table1.Rows[4].Height                                  = 20;
            table1.Range.ParagraphFormat.Alignment                 = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            newapp.Selection.Cells.Width                           = 150;
            table1.Columns[1].Width                                = 75;
            table1.Cell(1, 1).Range.ParagraphFormat.Alignment      = Word.WdParagraphAlignment.wdAlignParagraphRight;
            table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;



            //表头斜线
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible   = true;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color     = Word.WdColor.wdColorGreen;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

            //表格边框
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color     = Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleDouble;

            //合并单元格
            newdoc.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));

            //删除图片
            this.delpictfile(headerfile);
            this.delpictfile(picname);


            //保存文档
            object name = "c:\\yb3.doc";

            newdoc.SaveAs(ref name, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                          ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,
                          ref nothing, ref nothing);

            //关闭文档
            object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;

            newdoc.Close(ref nothing, ref nothing, ref nothing);
            newapp.Application.Quit(ref saveOption, ref nothing, ref nothing);
            newdoc = null;
            newapp = null;
            ShellExecute(IntPtr.Zero, "open", "c:\\yb3.doc", "", "", 3);
        }
        /// <summary>
        /// 写飞行时序
        /// </summary>
        /// <param name="TableName">表头</param>
        /// <param name="Table">特征表</param>
        /// <param name="TName">总时间列名称</param>
        /// <param name="TjName">级时间列名称</param>
        /// <param name="NoteName">注释列名称</param>
        public void WriteFlightSquence2Document(string TableName, DataTable Table, string TName, string TjName, string NoteName)
        {
            try
            {
                if (Table == null)
                {
                    throw new Exception("DataTable为Null!");
                }
                if (Table.Rows.Count < 1)
                {
                    throw new Exception("DataTable中无数据!");
                }

                //水平居中
                oWord.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                //写表头
                oWord.Selection.TypeText(TableName);

                //  创建表格
                WORD.Table newTable = oDoc.Tables.Add(oWord.Selection.Range, Table.Rows.Count + 1, 3);

                //表格加边框
                newTable.Borders.Enable = 1;
                //newTable.Borders.OutsideLineStyle = WORD.WdLineStyle.wdLineStyleThickThinLargeGap;

                newTable.Cell(1, 1).Range.Text = "飞行时序";
                newTable.Cell(1, 2).Range.Text = "t(s)";
                newTable.Cell(1, 3).Range.Text = "t*(s)";

                //写数据
                double tlast    = 1e10;
                int    TableRow = 1;
                foreach (DataRow dr in Table.Rows)
                {
                    //  此行数据的时刻
                    double tt = (double)dr[TName];

                    //  若与上段时间不同,则认为新数据,写入列数位置增加,否则下次覆盖
                    if (Math.Abs(tt - tlast) > 1e-5)
                    {
                        TableRow++;
                    }
                    tlast = tt;

                    //  将输入DataTable中的行部分数据写入Word文档的表格列中
                    for (int i = 0; i < Table.Rows.Count; i++)
                    {
                        //  写入第一列名称
                        newTable.Cell(TableRow, 1).Range.Text = (string)dr[NoteName];

                        //  写入第二列总时间
                        StringBuilder line = new StringBuilder(100);
                        line.AppendFormat("{0,12:F3}", (double)dr[TName]);
                        newTable.Cell(TableRow, 2).Range.Text = line.ToString();

                        //  写入第三列分时间
                        StringBuilder line2 = new StringBuilder(100);
                        line2.AppendFormat("{0,12:F3}", (double)dr[TjName]);
                        newTable.Cell(TableRow, 3).Range.Text = line2.ToString();
                    }
                }

                //  删除剩余的行
                for (int i = TableRow + 1; i < Table.Rows.Count + 2; i++)
                {
                    newTable.Rows[TableRow + 1].Select();
                    oWord.Selection.Cells.Delete();
                }

                //自动适应文字宽度
                newTable.Select();
                oWord.Selection.Cells.AutoFit();

                //  将光标移至表格下方
                newTable.Rows[TableRow].Select();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToLine);
                oWord.Selection.InsertBreak();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToPage);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + "\n" + "将DataTable写入Word文档出错!");
            }
        }
Beispiel #10
0
        /// <summary>
        /// 添加抗剪强度综合取值表
        /// </summary>
        /// <param name="_ssStatistic">抗剪强度综合取值数据</param>
        /// <returns></returns>
        public MSWord.Table AddShearingStrengthTable(List <ShearingStrengthCalculation.ShearingStrength> _ssStatistic)
        {
            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表7 抗剪强度综合取值表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _ssStatistic.Count + 2, 11, ref Nothing, ref Nothing);

            // 填充列标题
            table.Cell(1, 1).Range.Text  = "分层编号及名称";
            table.Cell(1, 2).Range.Text  = "土工试验";
            table.Cell(1, 4).Range.Text  = "静力触探试验";
            table.Cell(1, 7).Range.Text  = "标贯/动探";
            table.Cell(1, 10).Range.Text = "综合取值";
            string[] rowheader = new string[]
            {
                "φ\n(kPa)",
                "C\n(MPa)",
                "Ps\n(MPa)",
                "φ\n(kPa)",
                "C\n(MPa)",
                "N\n(击)",
                "φ\n(kPa)",
                "C\n(MPa)",
                "φ\n(kPa)",
                "C\n(MPa)"
            };
            for (int i = 1; i < table.Columns.Count; i++)
            {
                table.Cell(2, i + 1).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

            foreach (Row row in table.Rows)
            {
                row.Range.Bold           = 0;
                row.Cells[10].Range.Bold = 1;
                row.Cells[11].Range.Bold = 1;
            }
            table.Rows[1].Range.Bold = 1;

            table.Range.Font.Size = 10.0F;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;

            float[] columnWidth = new float[] { 100, 40, 40, 40, 40, 40, 40, 40, 40, 40, 40 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充试验数据
            for (int i = 0; i < _ssStatistic.Count; i++)
            {
                table.Cell(i + 3, 1).Range.Text  = _ssStatistic[i].layerInfo;
                table.Cell(i + 3, 2).Range.Text  = _ssStatistic[i].FrictionByRst == "-0.19880205" || _ssStatistic[i].FrictionByRst == "-0.2" ? "/" : _ssStatistic[i].FrictionByRst;
                table.Cell(i + 3, 3).Range.Text  = _ssStatistic[i].CohesionByRst == "-0.19880205" || _ssStatistic[i].CohesionByRst == "-0.2" ? "/" : _ssStatistic[i].CohesionByRst;
                table.Cell(i + 3, 4).Range.Text  = _ssStatistic[i].CptParameter == "-0.19880205" || _ssStatistic[i].CptParameter == "-0.2" ? "/" : _ssStatistic[i].CptParameter;
                table.Cell(i + 3, 5).Range.Text  = _ssStatistic[i].FrictionByCpt == "-0.19880205" || _ssStatistic[i].FrictionByCpt == "-0.2" ? "/" : _ssStatistic[i].FrictionByCpt;
                table.Cell(i + 3, 6).Range.Text  = _ssStatistic[i].CohesionByRst == "-0.19880205" || _ssStatistic[i].CohesionByRst == "-0.2" ? "/" : _ssStatistic[i].CohesionByRst;
                table.Cell(i + 3, 7).Range.Text  = _ssStatistic[i].NTestParameter == "-0.19880205" || _ssStatistic[i].NTestParameter == "-0.2" ? "/" : _ssStatistic[i].NTestParameter;
                table.Cell(i + 3, 8).Range.Text  = _ssStatistic[i].FrictionByNTest == "-0.19880205" || _ssStatistic[i].FrictionByNTest == "-0.2" ? "/" : _ssStatistic[i].FrictionByNTest;
                table.Cell(i + 3, 9).Range.Text  = _ssStatistic[i].CohesionByNTest == "-0.19880205" || _ssStatistic[i].CohesionByNTest == "-0.2" ? "/" : _ssStatistic[i].CohesionByNTest;
                table.Cell(i + 3, 10).Range.Text = _ssStatistic[i].FrictionFinal == "-0.19880205" || _ssStatistic[i].FrictionFinal == "-0.2" ? "/" : _ssStatistic[i].FrictionFinal;
                table.Cell(i + 3, 11).Range.Text = _ssStatistic[i].CohesionFinal == "-0.19880205" || _ssStatistic[i].CohesionFinal == "-0.2" ? "/" : _ssStatistic[i].CohesionFinal;
            }

            // 合并层号及名称单元格
            table.Cell(1, 10).Merge(table.Cell(1, 11));
            table.Cell(1, 7).Merge(table.Cell(1, 9));
            table.Cell(1, 4).Merge(table.Cell(1, 6));
            table.Cell(1, 2).Merge(table.Cell(1, 3));
            table.Cell(1, 1).Merge(table.Cell(2, 1));

            // 返回
            return(table);
        }
Beispiel #11
0
        /// <summary>
        /// 添加颗粒分析试验统计表格
        /// </summary>
        /// <param name="_gatStatistic">颗粒分析试验数据</param>
        /// <returns></returns>
        public MSWord.Table AddGATStatisticTable(List <StatisticGAT> _gatStatistic)
        {
            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表5 颗粒分析试验成果统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _gatStatistic.Count + 2, 7, ref Nothing, ref Nothing);

            // 填充列标题
            table.Cell(1, 1).Range.Text = "分层编号及名称";
            table.Cell(1, 2).Range.Text = "粒组分布百分含量(%)";
            string[] rowheader = new string[]
            {
                ">20mm",
                "20~2mm",
                "2~0.5mm",
                "0.5~0.25mm",
                "0.25~0.075mm",
                "<0.075mm"
            };
            for (int i = 1; i < table.Columns.Count; i++)
            {
                table.Cell(2, i + 1).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

            foreach (Row row in table.Rows)
            {
                row.Range.Bold = 0;
            }
            table.Rows[1].Range.Bold = 1;
            table.Rows[2].Range.Bold = 1;

            table.Range.Font.Size = 10.0F;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;

            float[] columnWidth = new float[] { 100, 50, 60, 60, 80, 80, 70 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充试验数据
            for (int i = 0; i < _gatStatistic.Count; i++)
            {
                table.Cell(i + 3, 1).Range.Text = _gatStatistic[i].Layer + _gatStatistic[i].Name;
                table.Cell(i + 3, 2).Range.Text = _gatStatistic[i].Group100To20.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group100To20.ToString("0.0");
                table.Cell(i + 3, 3).Range.Text = _gatStatistic[i].Group20To2.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group20To2.ToString("0.0");
                table.Cell(i + 3, 4).Range.Text = _gatStatistic[i].Group2To0_5.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group2To0_5.ToString("0.0");
                table.Cell(i + 3, 5).Range.Text = _gatStatistic[i].Group0_5To0_25.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group0_5To0_25.ToString("0.0");
                table.Cell(i + 3, 6).Range.Text = _gatStatistic[i].Group0_25To0_075.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group0_25To0_075.ToString("0.0");
                table.Cell(i + 3, 7).Range.Text = _gatStatistic[i].Group0_075To0.ToString() == "-0.19880205" ? "/" : _gatStatistic[i].Group0_075To0.ToString("0.0");
            }

            // 合并层号及名称单元格
            table.Cell(1, 1).Merge(table.Cell(2, 1));
            table.Cell(1, 2).Merge(table.Cell(1, 7));

            // 返回
            return(table);
        }
Beispiel #12
0
        /// <summary>
        /// 添加土工常规试验统计表格
        /// </summary>
        /// <param name="_rstStatistic">土工常规试验统计数据</param>
        /// <returns></returns>
        public MSWord.Table AddRSTStatisticTable(List <StatisticRST> _rstStatistic)
        {
            // 去除统计数为0的分层的统计数据
            for (int i = _rstStatistic.Count / 14 - 1; i > -1; i--)
            {
                bool isZero = true;

                for (int j = 13; j > -1; j--)
                {
                    if (_rstStatistic[j + i * 14].Count != 0)
                    {
                        isZero = false;
                    }
                }

                if (isZero)
                {
                    for (int j = 13; j > -1; j--)
                    {
                        _rstStatistic.RemoveAt(j + i * 14);
                    }
                }
            }

            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表4 土工常规试验成果统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _rstStatistic.Count / 14 * 8 + 1, 16, ref Nothing, ref Nothing);

            // 填充列标题
            string[] rowheader = new string[]
            {
                "层号及名称",
                "统\n计\n名\n称",
                "含\n水\n量",
                "天\n然\n密\n度",
                "比\n重",
                "孔\n隙\n比",
                "饱\n和\n度",
                "液\n限",
                "塑\n限",
                "塑\n性\n指\n数",
                "液\n性\n指\n数",
                "压\n缩\n系\n数",
                "压\n缩\n模\n量",
                "内\n摩\n擦\n角",
                "粘\n聚\n力",
                "渗\n透\n系\n数"
            };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Cell(1, i).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;

            foreach (Row row in table.Rows)
            {
                row.Range.Bold = 0;
            }
            table.Rows[1].Range.Bold = 1;
            for (int i = 0; i < _rstStatistic.Count / 14; i++)
            {
                table.Rows[5 + i * 8].Range.Bold = 1;
                table.Rows[9 + i * 8].Range.Bold = 1;
            }

            table.Rows[1].Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
            for (int i = 1; i <= table.Rows.Count; i++)
            {
                table.Cell(i, 1).Range.ParagraphFormat.LineSpacingRule = WdLineSpacing.wdLineSpaceExactly;
            }

            table.Range.Font.Size = 9.0F;

            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

            table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle  = MSWord.WdLineStyle.wdLineStyleSingle;

            float[] columnWidth = new float[] { 20, 50, 30, 30, 30, 30, 35, 30, 30, 30, 30, 30, 30, 30, 30, 40 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充试验数据
            for (int i = 0; i < _rstStatistic.Count / 14; i++)
            {
                int startRow = 2 + i * 8;

                table.Cell(startRow, 1).Range.Text = _rstStatistic[i * 14].Layer + " " + _rstStatistic[i * 14].Name;

                string[] type = new string[] { "统计数", "最大值", "最小值", "平均值", "标准差", "变异系数", "修正系数", "标准值" };
                for (int j = 0; j < 8; j++)
                {
                    table.Cell(startRow + j, 2).Range.Text = type[j];
                }

                for (int j = 0; j < 14; j++)
                {
                    if (j == 0 || j == 4 || j == 5 || j == 6 || j == 7 || j == 10 || j == 11 || j == 12)
                    {
                        table.Cell(startRow, 3 + j).Range.Text     = _rstStatistic[j + i * 14].Count.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Count.ToString("0");
                        table.Cell(startRow + 1, 3 + j).Range.Text = _rstStatistic[j + i * 14].Max.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Max.ToString("0.0");
                        table.Cell(startRow + 2, 3 + j).Range.Text = _rstStatistic[j + i * 14].Min.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Min.ToString("0.0");
                        table.Cell(startRow + 3, 3 + j).Range.Text = _rstStatistic[j + i * 14].Average.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Average.ToString("0.0");
                        table.Cell(startRow + 4, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardDeviation.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardDeviation.ToString("0.0");
                        table.Cell(startRow + 5, 3 + j).Range.Text = _rstStatistic[j + i * 14].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].VariableCoefficient.ToString("0.00");
                        table.Cell(startRow + 6, 3 + j).Range.Text = _rstStatistic[j + i * 14].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].CorrectionCoefficient.ToString("0.00");
                        table.Cell(startRow + 7, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardValue.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardValue.ToString("0.0");
                    }
                    else if (j == 1 || j == 2 || j == 3 || j == 8 || j == 9)
                    {
                        table.Cell(startRow, 3 + j).Range.Text     = _rstStatistic[j + i * 14].Count.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Count.ToString("0");
                        table.Cell(startRow + 1, 3 + j).Range.Text = _rstStatistic[j + i * 14].Max.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Max.ToString("0.00");
                        table.Cell(startRow + 2, 3 + j).Range.Text = _rstStatistic[j + i * 14].Min.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Min.ToString("0.00");
                        table.Cell(startRow + 3, 3 + j).Range.Text = _rstStatistic[j + i * 14].Average.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Average.ToString("0.00");
                        table.Cell(startRow + 4, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardDeviation.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardDeviation.ToString("0.00");
                        table.Cell(startRow + 5, 3 + j).Range.Text = _rstStatistic[j + i * 14].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].VariableCoefficient.ToString("0.00");
                        table.Cell(startRow + 6, 3 + j).Range.Text = _rstStatistic[j + i * 14].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].CorrectionCoefficient.ToString("0.00");
                        table.Cell(startRow + 7, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardValue.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardValue.ToString("0.00");
                    }
                    else
                    {
                        table.Cell(startRow, 3 + j).Range.Text     = _rstStatistic[j + i * 14].Count.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Count.ToString("0");
                        table.Cell(startRow + 1, 3 + j).Range.Text = _rstStatistic[j + i * 14].Max.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Max.ToString("0.0E0");
                        table.Cell(startRow + 2, 3 + j).Range.Text = _rstStatistic[j + i * 14].Min.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Min.ToString("0.0E0");
                        table.Cell(startRow + 3, 3 + j).Range.Text = _rstStatistic[j + i * 14].Average.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].Average.ToString("0.0E0");
                        table.Cell(startRow + 4, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardDeviation.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardDeviation.ToString("0.0E0");
                        table.Cell(startRow + 5, 3 + j).Range.Text = _rstStatistic[j + i * 14].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].VariableCoefficient.ToString("0.00");
                        table.Cell(startRow + 6, 3 + j).Range.Text = _rstStatistic[j + i * 14].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].CorrectionCoefficient.ToString("0.00");
                        table.Cell(startRow + 7, 3 + j).Range.Text = _rstStatistic[j + i * 14].StandardValue.ToString() == "-0.19880205" ? "/" : _rstStatistic[j + i * 14].StandardValue.ToString("0.0E0");
                    }
                }
            }

            // 合并层号及名称单元格
            for (int i = 0; i < _rstStatistic.Count / 14; i++)
            {
                table.Cell(2 + i * 8, 1).Merge(table.Cell(9 + i * 8, 1));
            }

            // 返回
            return(table);
        }
Beispiel #13
0
        /// <summary>
        /// 添加静力触探摩阻力统计表格
        /// </summary>
        /// <param name="_cptStatistic">静力触探摩阻力统计数据</param>
        /// <returns></returns>
        public MSWord.Table AddPsStatisticTable(List <StatisticCPT> _cptStatistic)
        {
            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表3 静力触探摩阻力统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, _cptStatistic.Count + 1, 10, ref Nothing, ref Nothing);

            // 填充行标题
            string[] rowheader = new string[] { "层号", "岩土名称", "统计数", "最大值", "最小值", "平均值", "标准差", "变异系数", "统计修正系数", "标准值" };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Cell(1, i).Range.Text = rowheader[i - 1];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
            table.Rows[1].Range.Bold = 1;
            for (int i = 2; i <= table.Rows.Count; i++)
            {
                table.Rows[i].Range.Bold              = 0;
                table.Columns[6].Cells[i].Range.Bold  = 1;
                table.Columns[10].Cells[i].Range.Bold = 1;
            }
            table.Range.Font.Size = 10.5F;
            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            table.Borders.OutsideLineStyle        = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle         = MSWord.WdLineStyle.wdLineStyleSingle;
            float[] columnWidth = new float[] { 35, 80, 45, 45, 45, 45, 45, 35, 45, 45 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充摩阻力数据
            for (int i = 2; i <= table.Rows.Count; i++)
            {
                table.Cell(i, 1).Range.Text  = _cptStatistic[i - 2].Layer;
                table.Cell(i, 2).Range.Text  = _cptStatistic[i - 2].Name;
                table.Cell(i, 3).Range.Text  = _cptStatistic[i - 2].Count.ToString("0");
                table.Cell(i, 4).Range.Text  = _cptStatistic[i - 2].Max.ToString("0.00");
                table.Cell(i, 5).Range.Text  = _cptStatistic[i - 2].Min.ToString("0.00");
                table.Cell(i, 6).Range.Text  = _cptStatistic[i - 2].Average.ToString("0.00");
                table.Cell(i, 7).Range.Text  = _cptStatistic[i - 2].StandardDeviation.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].StandardDeviation.ToString("0.00");
                table.Cell(i, 8).Range.Text  = _cptStatistic[i - 2].VariableCoefficient.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].VariableCoefficient.ToString("0.00");
                table.Cell(i, 9).Range.Text  = _cptStatistic[i - 2].CorrectionCoefficient.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].CorrectionCoefficient.ToString("0.00");
                table.Cell(i, 10).Range.Text = _cptStatistic[i - 2].StandardValue.ToString() == "-0.19880205" ? "/" : _cptStatistic[i - 2].StandardValue.ToString("0.00");
            }

            //返回
            return(table);
        }
Beispiel #14
0
        /// <summary>
        /// 添加勘察工作量统计表格
        /// </summary>
        /// <param name="_wordLoadStatistic">勘察工作量数据</param>
        /// <returns></returns>
        public MSWord.Table AddWorkLoadStatisticTable(StatisticWordLoad _wordLoadStatistic)
        {
            // 赋值工作量数组
            WorkLoadStatistic.amountList[0]  = "";
            WorkLoadStatistic.amountList[1]  = "";
            WorkLoadStatistic.amountList[2]  = _wordLoadStatistic.Borehole + "/" + _wordLoadStatistic.CountBorehole;
            WorkLoadStatistic.amountList[3]  = _wordLoadStatistic.Borehole + "/" + _wordLoadStatistic.CountBorehole;
            WorkLoadStatistic.amountList[4]  = _wordLoadStatistic.UndisturbedSample.ToString();
            WorkLoadStatistic.amountList[5]  = _wordLoadStatistic.DisturbedSample.ToString();
            WorkLoadStatistic.amountList[6]  = _wordLoadStatistic.NTestStandard.ToString();
            WorkLoadStatistic.amountList[7]  = _wordLoadStatistic.NTestN10.ToString();
            WorkLoadStatistic.amountList[8]  = _wordLoadStatistic.NTestN635.ToString();
            WorkLoadStatistic.amountList[9]  = _wordLoadStatistic.NTestN120.ToString();
            WorkLoadStatistic.amountList[10] = _wordLoadStatistic.CPT + "/" + _wordLoadStatistic.CountCPT;
            WorkLoadStatistic.amountList[11] = _wordLoadStatistic.RST.ToString();
            WorkLoadStatistic.amountList[12] = _wordLoadStatistic.Permeability.ToString();
            WorkLoadStatistic.amountList[13] = _wordLoadStatistic.GAT.ToString();
            WorkLoadStatistic.amountList[14] = "";

            // 填写表格标题
            Doc.Paragraphs.Last.Range.Text                = "表1 勘察工作量统计表";
            Doc.Paragraphs.Last.Range.Font.Bold           = 1;
            Doc.Paragraphs.Last.Range.Font.Size           = 12;
            App.Selection.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            object unite = MSWord.WdUnits.wdStory;

            App.Selection.EndKey(ref unite, ref Nothing);

            // 定义表格对象
            MSWord.Table table = Tables.Add(App.Selection.Range, 16, 5, ref Nothing, ref Nothing);

            // 填充行标题
            string[] rowheader = new string[] { "工 作 项 目", "单 位", "工作量", "备注" };
            for (int i = 2; i <= table.Columns.Count; i++)
            {
                table.Cell(1, i).Range.Text = rowheader[i - 2];
            }

            // 设置文档格式
            Doc.PageSetup.LeftMargin  = 50F;
            Doc.PageSetup.RightMargin = 50F;

            // 设置表格格式
            table.Select();
            App.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;
            for (int i = 1; i <= table.Rows.Count; i++)
            {
                table.Rows[i].Range.Bold = 0;
            }
            table.Rows[1].Range.Bold = 1;
            table.Range.Font.Size    = 10.5F;
            table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
            table.Range.Cells.VerticalAlignment   = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            table.Borders.OutsideLineStyle        = MSWord.WdLineStyle.wdLineStyleDouble;
            table.Borders.InsideLineStyle         = MSWord.WdLineStyle.wdLineStyleSingle;
            float[] columnWidth = new float[] { 80, 120, 60, 60, 60 };
            for (int i = 1; i <= table.Columns.Count; i++)
            {
                table.Columns[i].Width = columnWidth[i - 1];
            }

            // 填充工作量数据
            for (int i = 0; i < WorkLoadStatistic.amountList.Length; i++)
            {
                table.Cell(i + 2, 2).Range.Text = WorkLoadStatistic.typeList[i];
                table.Cell(i + 2, 3).Range.Text = WorkLoadStatistic.uniteList[i];
                table.Cell(i + 2, 4).Range.Text = WorkLoadStatistic.amountList[i];
                table.Cell(i + 2, 5).Range.Text = WorkLoadStatistic.remarkList[i];
            }

            // 填充第一列
            table.Cell(2, 1).Range.Text  = "测绘";
            table.Cell(4, 1).Range.Text  = "勘探";
            table.Cell(6, 1).Range.Text  = "取样";
            table.Cell(8, 1).Range.Text  = "原位测试";
            table.Cell(13, 1).Range.Text = "室内试验";

            // 删除空行
            int d = 0;

            for (int i = 0; i < 15; i++)
            {
                if (WorkLoadStatistic.amountList[i].ToString() == "0")
                {
                    table.Rows[i + 2 - d].Delete();
                    d++;
                }
            }


            // 合并单元格
            table.Cell(1, 1).Merge(table.Cell(1, 2));
            table.Cell(2, 1).Merge(table.Cell(3, 1));
            table.Cell(4, 1).Merge(table.Cell(5, 1));
            table.Cell(table.Rows.Count, 1).Merge(table.Cell(table.Rows.Count, 2));
            int[] mergeIndex = new int[3] {
                0, 0, 0
            };
            for (int i = 6; i <= table.Rows.Count - 1; i++)
            {
                if ((mergeIndex[0] == 0) && (table.Cell(i, 2).Range.Text.Contains("原状样") || table.Cell(i, 2).Range.Text.Contains("扰动样")))
                {
                    mergeIndex[0] = i;
                }
                if ((mergeIndex[1] == 0) && (table.Cell(i, 2).Range.Text.Contains("标准贯入试验") || table.Cell(i, 2).Range.Text.Contains("触探试验")))
                {
                    mergeIndex[1] = i;
                }
                if ((mergeIndex[2] == 0) && (table.Cell(i, 2).Range.Text.Contains("土工常规") || table.Cell(i, 2).Range.Text.Contains("室内渗透") || table.Cell(i, 2).Range.Text.Contains("颗粒分析") || table.Cell(i, 2).Range.Text.Contains("水质") || table.Cell(i, 2).Range.Text.Contains("击实")))
                {
                    mergeIndex[2] = i;
                }
            }
            for (int i = 0; i < 3; i++)
            {
                int startIndex = mergeIndex[i];
                int endIndex;
                if (i < 2)
                {
                    endIndex = mergeIndex[i + 1] - 1;
                }
                else
                {
                    endIndex = table.Rows.Count - 1;
                }
                if (startIndex == 0)
                {
                    continue;
                }
                if (startIndex != endIndex)
                {
                    table.Cell(startIndex, 1).Merge(table.Cell(endIndex, 1));
                }
            }

            // 返回
            return(table);
        }
        //#####################################################################
        /// <summary>
        ///  将DataTable中部分数据写入到Word文档表格中(若有时间相同点,则由后点覆盖前点)
        /// </summary>
        /// <param name="TableName">表头名称</param>
        /// <param name="Table"></param>
        /// <param name="TName">时间列名称、判断重复时间点</param>
        /// <param name="NoteName">注释列名称</param>
        /// <param name="Name">选择写入文档的列名称</param>
        /// <param name="Label">列说明</param>
        /// <param name="Symbol">符号</param>
        /// <param name="Unit">单位</param>
        /// <param name="Quotiety">系数</param>
        /// <param name="Precision">数据精度、小数点位数</param>
        public void WriteTable2Document(string TableName, DataTable Table, string TName, string NoteName, string[] Name, string[] Label, string[] Symbol, string[] Unit, string[] Quotiety, string[] Precision)
        {
            try
            {
                if (Table == null)
                {
                    throw new Exception("DataTable为Null!");
                }
                if (Table.Rows.Count < 1)
                {
                    throw new Exception("DataTable中无数据!名称:" + Table.TableName);
                }
                if (Name.Length < 1)
                {
                    throw new Exception("输入数组为0");
                }

                //水平居中
                oWord.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;

                //写表头
                oWord.Selection.TypeText(TableName);

                //  创建表格
                WORD.Table newTable = oDoc.Tables.Add(oWord.Selection.Range, Name.Length + 1, Table.Rows.Count + 3);

                //表格加边框
                newTable.Borders.Enable = 1;
                //newTable.Borders.OutsideLineStyle = WORD.WdLineStyle.wdLineStyleThickThinLargeGap;

                newTable.Cell(1, 1).Range.Text = "名称";
                newTable.Cell(1, 2).Range.Text = "符号";
                newTable.Cell(1, 3).Range.Text = "单位";

                //向表格前三列中写入:说明,符号,单位
                for (int i = 0; i < Name.Length; i++)
                {
                    newTable.Cell(i + 2, 1).Range.Text = Label[i];
                    newTable.Cell(i + 2, 2).Range.Text = Symbol[i];
                    newTable.Cell(i + 2, 3).Range.Text = Unit[i];
                }

                //写数据
                double tlast    = 1e10;
                int    TableCol = 3;
                foreach (DataRow dr in Table.Rows)
                {
                    //  此行数据的时刻
                    double tt = (double)dr[TName];

                    //  若与上段时间不同,则认为新数据,写入列数位置增加,否则下次覆盖
                    if (Math.Abs(tt - tlast) > 1e-5)
                    {
                        TableCol++;
                    }
                    tlast = tt;

                    //  将输入DataTable中的行部分数据写入Word文档的表格列中
                    for (int i = 0; i < Name.Length; i++)
                    {
                        //  写入第一行段名称
                        newTable.Cell(1, TableCol).Range.Text = (string)dr[NoteName];

                        //  写入各行数据
                        StringBuilder line = new StringBuilder(100);
                        line.AppendFormat("{0,12:F" + Precision[i] + "}", (double)dr[Name[i]] * Convert.ToDouble(Quotiety[i]));
                        newTable.Cell(i + 2, TableCol).Range.Text = line.ToString();
                    }
                }

                //  删除剩余的列
                for (int i = TableCol + 1; i < Table.Rows.Count + 4; i++)
                {
                    newTable.Columns[TableCol + 1].Select();
                    oWord.Selection.Cells.Delete();
                }

                //自动适应文字宽度
                newTable.Select();
                oWord.Selection.Cells.AutoFit();

                //  将光标移至表格下方
                newTable.Rows[Name.Length + 1].Select();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToLine);
                oWord.Selection.InsertBreak();
                oWord.Selection.GoToNext(WORD.WdGoToItem.wdGoToPage);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + "\n" + "将DataTable写入Word文档出错!");
            }
        }
Beispiel #16
0
        // запускаем поток


        //public void sleeping1()
        //{

        //}

        //public void sleeping()
        //{

        //}

        //public void Count(object obj)
        //{
        //    sleep.Visibility = Visibility.Visible;


        //}

        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            // устанавливаем метод обратного вызова
            //TimerCallback tm = new TimerCallback(Count);
            //// создаем таймер
            //Timer timer = new Timer(tm, num, 0, 200);


            //System.Windows.Media.Brush br = ((Button)sender).Background;
            //((Button)sender).Background = System.Windows.Media.Brushes.Red;

            //Mouse.OverrideCursor = Cursors.Wait;
            //MainWindow form = new MainWindow();
            //form.Owner = this;
            //// Run function in a new thread.
            //System.Threading.Tasks.Task.Factory.StartNew(() =>
            //{
            //    sleeping(form); // Long running function.
            //})
            //.ContinueWith((result) =>
            //{
            //    // Runs when Function is complete...
            //    Mouse.OverrideCursor = Cursors.Arrow;
            //    ((Button)sender).Background = br;
            //});



            // Усыпляем ненадолго поток

            // new Thread(sleeping(this));
            //  myThread.Start();
            //new Thread(sleeping(sleep));

            try
            {
                Word.Application _wordapp = new Word.Application();
                zak = textBox1.Text;
                try { date = date1.SelectedDate.Value.ToShortDateString(); } catch { }
                exp  = textBox12.Text;
                nexp = textBox13.Text;
                try
                {
                    d = date2.SelectedDate.Value.Day.ToString();
                    m = date2.SelectedDate.Value.Month.ToString();
                    y = date2.SelectedDate.Value.Year.ToString();
                }
                catch { }
                auto   = textBox2.Text;
                godM   = textBox3.Text;
                gosN   = textBox4.Text;
                nomK   = textBox5.Text;
                vin    = textBox6.Text;
                color  = textBox7.Text;
                probeg = textBox8.Text;
                TP     = textBox9.Text;
                FIO    = textBox10.Text;
                dFIO   = textBox11.Text;

                Range  cellRange;
                Object newTemplate  = false;
                Object documentType = Word.WdNewDocumentType.wdNewBlankDocument;
                Object template     = _startPathFolder + "\\Шаблон.docx";
                Object template2    = _startPathFolder + "\\Шаблан_акт.docx";
                Object template3    = _startPathFolder + "\\Шаблон_фото.docx";
                if (FIO != "" && auto != "" && gosN != "" && p3 != null)
                {
                    string        path    = _startPathFolder + "\\" + FIO;
                    DirectoryInfo dirInfo = new DirectoryInfo(path);
                    dirInfo.Create();

                    _worddocument = _wordapp.Documents.Add(ref template, ref newTemplate, ref documentType);
                    _worddocument.SaveAs(path + "\\" + auto + " " + gosN + " " + FIO + ".doc");
                    _worddocument.Close();

                    _wordapp.Documents.Open(path + "\\" + auto + " " + gosN + " " + FIO + ".doc");
                    _worddocument = _wordapp.ActiveDocument;
                    Object    missing = Type.Missing;
                    Word.Find find    = _wordapp.Selection.Find;

                    //    _wordapp.Selection.InsertFile(_pathFolder + "\\" + var + ".doc", Type.Missing, false);

                    int col_v_doc3 = 1;
                    wordTable = _worddocument.Tables[7];
                    for (int i = 0; i < l3.Items.Count; i++)
                    {
                        var format = l3.Items[i].ToString().Remove(0, l3.Items[i].ToString().Length - 3);

                        if (format != "pdf")
                        {
                            cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                            var   shape = cellRange.InlineShapes.AddPicture(l3.Items[i].ToString(), Type.Missing, Type.Missing, Type.Missing);
                            float w     = shape.Width;
                            float h     = shape.Height;
                            float c     = w / 930;
                            h = h / c;
                            if (h < 520)
                            {
                                shape.Width  = 930;
                                shape.Height = h;
                            }
                            else
                            {
                                h            = shape.Height;
                                c            = h / 520;
                                w            = w / c;
                                shape.Width  = w;
                                shape.Height = 520;
                            }
                            wordTable.Rows.Add();
                            col_v_doc3++;
                        }
                        else
                        {
                            var names = ConvertPDFtoHojas(l3.Items[i].ToString(), path);
                            foreach (var name in names)
                            {
                                cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                                var   shape = cellRange.InlineShapes.AddPicture(path + @"\" + name, Type.Missing, Type.Missing, Type.Missing);
                                float w     = shape.Width;
                                float h     = shape.Height;
                                //float c = w / 930;
                                //h = h / c;
                                //if (h < 520)
                                //{
                                //    shape.Width = 930;
                                //    shape.Height = h;
                                //}
                                //else
                                //{
                                //    h = shape.Height;
                                //    c = h / 520;
                                //    w = w / c;
                                //    shape.Width = w;
                                //    shape.Height = 520;
                                //}

                                wordTable.Rows.Add();
                                col_v_doc3++;
                                System.IO.File.Delete(path + @"\" + name);
                            }
                        }
                    }


                    int col_v_doc4 = 1;
                    wordTable = _worddocument.Tables[8];
                    for (int i = 0; i < l4.Items.Count; i++)
                    {
                        var format = l4.Items[i].ToString().Remove(0, l4.Items[i].ToString().Length - 3);

                        if (format != "pdf")
                        {
                            cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                            var   shape = cellRange.InlineShapes.AddPicture(l4.Items[i].ToString(), Type.Missing, Type.Missing, Type.Missing);
                            float w     = shape.Width;
                            float h     = shape.Height;
                            float c     = w / 930;
                            h = h / c;
                            if (h < 520)
                            {
                                shape.Width  = 930;
                                shape.Height = h;
                            }
                            else
                            {
                                h            = shape.Height;
                                c            = h / 520;
                                w            = w / c;
                                shape.Width  = w;
                                shape.Height = 520;
                            }
                            wordTable.Rows.Add();
                            col_v_doc4++;
                        }
                        else
                        {
                            var names = ConvertPDFtoHojas(l4.Items[i].ToString(), path);
                            foreach (var name in names)
                            {
                                cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                                var   shape = cellRange.InlineShapes.AddPicture(path + @"\" + name, Type.Missing, Type.Missing, Type.Missing);
                                float w     = shape.Width;
                                float h     = shape.Height;
                                //float c = w / 930;
                                //h = h / c;
                                //if (h < 520)
                                //{
                                //    shape.Width = 930;
                                //    shape.Height = h;
                                //}
                                //else
                                //{
                                //    h = shape.Height;
                                //    c = h / 520;
                                //    w = w / c;
                                //    shape.Width = w;
                                //    shape.Height = 520;
                                //}

                                wordTable.Rows.Add();
                                col_v_doc4++;
                                System.IO.File.Delete(path + @"\" + name);
                            }
                        }
                    }



                    //    worddocument.Activate();
                    find.Text             = "<zak>"; // текст поиска
                    find.Replacement.Text = zak;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<date>"; // текст поиска
                    find.Replacement.Text = date;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<exp>"; // текст поиска
                    find.Replacement.Text = exp;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<nexp>"; // текст поиска
                    find.Replacement.Text = nexp;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<d>"; // текст поиска
                    find.Replacement.Text = d;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<m>"; // текст поиска
                    find.Replacement.Text = m;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<y>"; // текст поиска
                    find.Replacement.Text = y;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<auto>"; // текст поиска
                    find.Replacement.Text = auto;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<godM>"; // текст поиска
                    find.Replacement.Text = godM;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<gosN>"; // текст поиска
                    find.Replacement.Text = gosN;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<nomK>"; // текст поиска
                    find.Replacement.Text = nomK;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<vin>"; // текст поиска
                    find.Replacement.Text = vin;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<color>"; // текст поиска
                    find.Replacement.Text = color;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<probeg>"; // текст поиска
                    find.Replacement.Text = probeg;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<TP>"; // текст поиска
                    find.Replacement.Text = TP;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<FIO>"; // текст поиска
                    find.Replacement.Text = FIO;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);
                    find.Text             = "<dFIO>"; // текст поиска
                    find.Replacement.Text = dFIO;     // текст замены
                    find.Execute(FindText: Type.Missing, MatchCase: false, MatchWholeWord: false,
                                 MatchWildcards: false,
                                 MatchSoundsLike: missing, MatchAllWordForms: false, Forward: true,
                                 Wrap: Word.WdFindWrap.wdFindContinue,
                                 Format: false, ReplaceWith: missing, Replace: Word.WdReplace.wdReplaceAll);



                    string filename = p3;
                    objWorkBook = objWorkExcel.Workbooks.Open(filename);
                    Excel.Worksheet objWorkSheet = (Excel.Worksheet)objWorkBook.Sheets[1];
                    string          poisk        = "";
                    Excel.Range     excelcells;
                    int             stolb;
                    int             strok;
                    try
                    {
                        excelcells = objWorkSheet.Cells.Find("<М.П.>", Type.Missing, Type.Missing, Excel.XlLookAt.xlPart, Type.Missing,
                                                             Excel.XlSearchDirection.xlNext,
                                                             Type.Missing, Type.Missing, Type.Missing);
                        stolb = Convert.ToInt16(excelcells.Column);
                        strok = Convert.ToInt16(excelcells.Rows.Row);
                    }
                    catch
                    {
                        excelcells = objWorkSheet.Cells.Find("Техник - эксперт", Type.Missing, Type.Missing, Excel.XlLookAt.xlPart, Type.Missing,
                                                             Excel.XlSearchDirection.xlNext,
                                                             Type.Missing, Type.Missing, Type.Missing);
                        stolb = Convert.ToInt16((excelcells.Column + 1));
                        strok = Convert.ToInt16(excelcells.Rows.Row);
                    }



                    var x  = objWorkSheet.Cells[(strok), stolb].Top;
                    var yy = objWorkSheet.Cells[(strok), stolb].Left;

                    objWorkSheet.Shapes.AddPicture(_startPathFolder + "\\Печать.jpg", MsoTriState.msoFalse, MsoTriState.msoCTrue, yy, x, 100, 100);
                    objWorkBook.Save();


                    // string ext = xlSheetPath.Substring(xlSheetPath.LastIndexOf("."),
                    //     xlSheetPath.Length - xlSheetPath.LastIndexOf("."));
                    // int xlVersion = (xlSheetPath.Substring(xlSheetPath.LastIndexOf("."),
                    //     xlSheetPath.Length - xlSheetPath.LastIndexOf(".")) == ".xls") ? 8 : 12;


                    //wdapp.Selection.Fields.Add(wdapp.Selection.Range, Word.WdFieldType.wdFieldLink,
                    //    "Excel.Sheet." + xlVersion.ToString() + " " + xlSheetPath + " Лист1!A1G1:A290G290 \\a \\f 5 \\h", true);
                    //wdapp.Visible = true;

                    // Microsoft.Office.Interop.Excel._Application xlApp = new Excel.Application();
                    //  xlApp.Visible = true;
                    // Excel.Workbook workbook = xlApp.Workbooks.Open(xlSheetPath);
                    //  Excel.Worksheet worksheet = workbook.Sheets[1];

                    //Word._Application wdApp = new Word.Application();
                    //wdApp.Visible = true;
                    // Word.Document document = wdApp.Documents.Add();
                    // document.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;

                    objWorkSheet.Range["A1", "G" + (strok + 4)].Copy();
                    wordTable = _worddocument.Tables[6];
                    cellRange = wordTable.Cell(1, 1).Range;
                    cellRange.PasteSpecial();

                    wordTable.Select();
                    _wordapp.Selection.Paragraphs.Space1();
                    _wordapp.Selection.ParagraphFormat.LineUnitAfter  = 0;
                    _wordapp.Selection.ParagraphFormat.LineUnitBefore = 0;
                    //       Range range = _wordapp.ActiveDocument.Content;

                    //       find.Text = "<М.П.>"; // текст поиска
                    //       if (find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                    //ref missing, ref missing, ref missing, ref missing, ref missing,
                    // ref missing, ref missing, ref missing, ref missing, ref missing))
                    //       {

                    //           range.InlineShapes.AddPicture(_startPathFolder + "\\Печать.jpg", ref missing, ref missing, ref missing);
                    //           find.Replacement.ClearFormatting();
                    //           find.Replacement.Text = "";
                    //           object replaceOne = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
                    //           find.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
                    //              ref missing, ref missing, ref missing, ref missing, ref missing,
                    //               ref replaceOne, ref missing, ref missing, ref missing, ref missing);
                    //       }

                    //objWorkBook.Save();
                    objWorkBook.Close(false);



                    if (chec.IsChecked == false)
                    {
                        _worddocument.SaveAs2(path + "\\" + auto + " " + gosN + " " + FIO + ".pdf", WdSaveFormat.wdFormatPDF);
                        _worddocument.Save();
                        _worddocument.Close();

                        _worddocument = _wordapp.Documents.Add(ref template2, ref newTemplate, ref documentType);
                        _worddocument.SaveAs(path + "\\Акт осмотра" + auto + " " + gosN + " " + FIO + ".doc");
                        _worddocument.Close();
                        _worddocument = _wordapp.Documents.Add(ref template3, ref newTemplate, ref documentType);
                        _worddocument.SaveAs(path + "\\Фото" + auto + " " + gosN + " " + FIO + ".doc");
                        _worddocument.Close();

                        _wordapp.Documents.Open(path + "\\Фото" + auto + " " + gosN + " " + FIO + ".doc");
                        _worddocument = _wordapp.ActiveDocument;
                        wordTable     = _worddocument.Tables[1];
                        int col_v_doc2 = 1;
                        for (int i = 1; i <= l2.Items.Count;)
                        {
                            try
                            {
                                for (int j = 1; j < 3; j++)
                                {
                                    cellRange = wordTable.Cell(i, j).Range;
                                    var   shape = cellRange.InlineShapes.AddPicture(l2.Items[(i - 1)].ToString(), Type.Missing, Type.Missing, Type.Missing);
                                    float w     = shape.Width;
                                    float h     = shape.Height;
                                    float c     = w / 480;
                                    h = h / c;
                                    if (h < 250)
                                    {
                                        shape.Width  = 480;
                                        shape.Height = h;
                                    }
                                    else
                                    {
                                        h            = shape.Height;
                                        c            = h / 250;
                                        w            = w / c;
                                        shape.Width  = w;
                                        shape.Height = 250;
                                    }
                                    i++;
                                }
                                wordTable.Rows.Add();
                            }
                            catch { }
                        }
                        _worddocument.SaveAs2(path + "\\Фото" + auto + " " + gosN + " " + FIO + ".pdf", WdSaveFormat.wdFormatPDF);
                        _worddocument.Save();
                        _worddocument.Close();

                        _wordapp.Documents.Open(path + "\\Акт осмотра" + auto + " " + gosN + " " + FIO + ".doc");
                        _worddocument = _wordapp.ActiveDocument;
                        wordTable     = _worddocument.Tables[1];
                        int col_v_doc1 = 1;

                        for (int i = 0; i < l1.Items.Count; i++)
                        {
                            var format = l1.Items[i].ToString().Remove(0, l1.Items[i].ToString().Length - 3);

                            if (format != "pdf")
                            {
                                cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                                var   shape = cellRange.InlineShapes.AddPicture(l1.Items[i].ToString(), Type.Missing, Type.Missing, Type.Missing);
                                float w     = shape.Width;
                                float h     = shape.Height;
                                float c     = w / 930;
                                h = h / c;
                                if (h < 520)
                                {
                                    shape.Width  = 930;
                                    shape.Height = h;
                                }
                                else
                                {
                                    h            = shape.Height;
                                    c            = h / 520;
                                    w            = w / c;
                                    shape.Width  = w;
                                    shape.Height = 520;
                                }
                                wordTable.Rows.Add();
                                col_v_doc1++;
                            }
                            else
                            {
                                var names = ConvertPDFtoHojas(l1.Items[i].ToString(), path);
                                foreach (var name in names)
                                {
                                    cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                                    var shape = cellRange.InlineShapes.AddPicture(path + @"\" + name, Type.Missing, Type.Missing, Type.Missing);
                                    //float w = shape.Width;
                                    //float h = shape.Height;
                                    //float c = w / 900;
                                    //h = h / c;
                                    //if (h < 520)
                                    //{
                                    //    shape.Width = 900;
                                    //    shape.Height = h;
                                    //}
                                    //else
                                    //{
                                    //    h = shape.Height;
                                    //    c = h / 520;
                                    //    w = w / c;
                                    //    shape.Width = w;
                                    //    shape.Height = 520;
                                    //}

                                    wordTable.Rows.Add();
                                    col_v_doc1++;
                                    System.IO.File.Delete(path + @"\" + name);
                                }
                            }
                        }
                        _worddocument.SaveAs2(path + "\\Акт осмотра" + auto + " " + gosN + " " + FIO + ".pdf", WdSaveFormat.wdFormatPDF);
                        _worddocument.Save();
                        _worddocument.Close();
                    }
                    else
                    {
                        wordTable = _worddocument.Tables[5];
                        int col_v_doc1 = 1;

                        for (int i = 0; i < l1.Items.Count; i++)
                        {
                            var format = l1.Items[i].ToString().Remove(0, l1.Items[i].ToString().Length - 3);

                            if (format != "pdf")
                            {
                                cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                                var   shape = cellRange.InlineShapes.AddPicture(l1.Items[i].ToString(), Type.Missing, Type.Missing, Type.Missing);
                                float w     = shape.Width;
                                float h     = shape.Height;
                                float c     = w / 930;
                                h = h / c;
                                if (h < 520)
                                {
                                    shape.Width  = 930;
                                    shape.Height = h;
                                }
                                else
                                {
                                    h            = shape.Height;
                                    c            = h / 520;
                                    w            = w / c;
                                    shape.Width  = w;
                                    shape.Height = 520;
                                }
                                wordTable.Rows.Add();
                                col_v_doc1++;
                            }
                            else
                            {
                                var names = ConvertPDFtoHojas(l1.Items[i].ToString(), path);
                                foreach (var name in names)
                                {
                                    cellRange = wordTable.Cell(col_v_doc3, 1).Range;
                                    var   shape = cellRange.InlineShapes.AddPicture(path + @"\" + name, Type.Missing, Type.Missing, Type.Missing);
                                    float w     = shape.Width;
                                    float h     = shape.Height;
                                    float c     = w / 1000;
                                    h = h / c;
                                    if (h < 650)
                                    {
                                        shape.Width  = 1000;
                                        shape.Height = h;
                                    }
                                    else
                                    {
                                        h            = shape.Height;
                                        c            = h / 650;
                                        w            = w / c;
                                        shape.Width  = w;
                                        shape.Height = 650;
                                    }

                                    wordTable.Rows.Add();
                                    col_v_doc1++;
                                    System.IO.File.Delete(path + @"\" + name);
                                }
                            }
                        }

                        var _currentRange = _worddocument.Range(wordTable.Range.End + 1, wordTable.Range.End + 2);
                        _currentRange.InsertBreak(Word.WdBreakType.wdSectionBreakNextPage);
                        _currentRange.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape;

                        //_currentRange = _worddocument.Range(_worddocument.Content.End - 1, _worddocument.Content.End);
                        _worddocument.Tables.Add(_currentRange, 1, 2);
                        wordTable               = _worddocument.Tables[6];
                        wordTable.TopPadding    = 2;
                        wordTable.LeftPadding   = 2;
                        wordTable.RightPadding  = 2;
                        wordTable.BottomPadding = 2;
                        wordTable.Columns[1].Select();
                        _wordapp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;

                        int col_v_doc2 = 1;
                        for (int i = 1; i <= l2.Items.Count;)
                        {
                            try
                            {
                                for (int j = 1; j < 3; j++)
                                {
                                    cellRange = wordTable.Cell(i, j).Range;
                                    var   shape = cellRange.InlineShapes.AddPicture(l2.Items[(i - 1)].ToString(), Type.Missing, Type.Missing, Type.Missing);
                                    float w     = shape.Width;
                                    float h     = shape.Height;
                                    float c     = w / 480;
                                    h = h / c;
                                    if (h < 250)
                                    {
                                        shape.Width  = 480;
                                        shape.Height = h;
                                    }
                                    else
                                    {
                                        h            = shape.Height;
                                        c            = h / 250;
                                        w            = w / c;
                                        shape.Width  = w;
                                        shape.Height = 250;
                                    }
                                    i++;
                                }
                                wordTable.Rows.Add();
                            }
                            catch { }
                        }
                        _currentRange = _worddocument.Range(wordTable.Range.End + 1, wordTable.Range.End + 2);
                        _currentRange.InsertBreak(Word.WdBreakType.wdSectionBreakNextPage);
                        _currentRange.PageSetup.Orientation       = Word.WdOrientation.wdOrientPortrait;
                        _wordapp.Selection.PageSetup.TopMargin    = 5;
                        _wordapp.Selection.PageSetup.BottomMargin = 5;
                        _worddocument.SaveAs2(path + "\\" + auto + " " + gosN + " " + FIO + ".pdf", WdSaveFormat.wdFormatPDF);
                        _worddocument.Save();
                        _worddocument.Close();
                    }
                    sleep.Visibility = Visibility.Hidden;
                    MessageBox.Show("Готово");
                }
                else
                {
                    sleep.Visibility = Visibility.Hidden;
                    MessageBox.Show("Не заполнены поля");
                }
            }
            catch (Exception eex)
            {
                if (eex.Message == "Ссылка на объект не указывает на экземпляр объекта.")
                {
                    MessageBox.Show("В документе Excel нет <М.П.>");
                    _worddocument.Close(false);
                    objWorkBook.Close(false);
                    sleep.Visibility = Visibility.Hidden;
                }
                else
                {
                    MessageBox.Show(eex.Message);
                    _worddocument.Close(false);
                    objWorkBook.Close(false);
                    sleep.Visibility = Visibility.Hidden;
                }
            }
        }
Beispiel #17
0
        /// <summary>
        /// 转化表数据集合为Word文档
        /// </summary>
        /// <param name="filewordPath"></param>
        /// <param name="tsc"></param>
        public void ConvertInfoToWord(string filewordPath, TabStruCollection tsc)
        {
            if (tsc.List == null || tsc.List.Count == 0)
            {
                return;
            }
            StringBuilder rtn    = new StringBuilder();
            object        wdtype = WdNewDocumentType.wdNewBlankDocument;

            this.m_wddoc = this.m_wdapp.Documents.Add(ref nouseref, ref nouseref, ref wdtype,
                                                      ref nouseref);

            try
            {
                foreach (Draco.DB.QuickDataBase.Schema.Vendor.Implementation.Table table in tsc.List)
                {
                    Draco.DB.QuickDataBase.Schema.Vendor.Implementation.Table tbl = table;
                    Microsoft.Office.Interop.Word.Range range = this.m_wdapp.Selection.Range;
                    object tblbehavior = WdDefaultTableBehavior.wdWord9TableBehavior;
                    object fitbehavite = WdAutoFitBehavior.wdAutoFitFixed;
                    Microsoft.Office.Interop.Word.Table wdtbl = this.m_wddoc.Tables.Add(range, tbl.Columns.Count + 3, 4,
                                                                                        ref tblbehavior,
                                                                                        ref fitbehavite);

                    MergeTblCell(wdtbl, 1, 2, 4);
                    Microsoft.Office.Interop.Word.Cell cell = wdtbl.Cell(1, 1);
                    SetTblCellShading(cell);
                    SetCellValue(cell, "表名:");

                    SetCellValue(wdtbl.Cell(1, 2), tbl.TableName);
                    MergeTblCell(wdtbl, 2, 2, 4);
                    cell = wdtbl.Cell(2, 1);
                    SetTblCellShading(cell);
                    SetCellValue(cell, "表名含义:");
                    SetCellValue(wdtbl.Cell(2, 2), tbl.TableName);

                    cell = wdtbl.Cell(3, 1);
                    SetTblCellShading(cell);
                    SetCellValue(cell, "字段名称");
                    cell = wdtbl.Cell(3, 2);
                    SetTblCellShading(cell);
                    SetCellValue(cell, "字段类型(长度)");
                    cell = wdtbl.Cell(3, 3);
                    SetTblCellShading(cell);
                    SetCellValue(cell, "字段含义");
                    cell = wdtbl.Cell(3, 4);
                    SetTblCellShading(cell);
                    SetCellValue(cell, "备注");

                    for (int i = 0; i < tbl.Columns.Count; i++)
                    {
                        SetCellValue(wdtbl.Cell(i + 4, 1), tbl.Columns[i].ColumnName);
                        string typeAndLen = tbl.Columns[i].FullType.ToString();
                        if (tbl.Columns[i].Length != null && tbl.Columns[i].Length.ToString().Length > 0)
                        {
                            typeAndLen += "(" + tbl.Columns[i].Length + ")";
                        }
                        SetCellValue(wdtbl.Cell(i + 4, 2), typeAndLen);
                        SetCellValue(wdtbl.Cell(i + 4, 3), tbl.Columns[i].Comment);
                        string fieldAtt = "";
                        if (tbl.Columns[i].PrimaryKey != null && (bool)tbl.Columns[i].PrimaryKey)
                        {
                            fieldAtt += "主键;";
                        }
                        else
                        {
                            if (!tbl.Columns[i].Nullable)
                            {
                                fieldAtt += "非空;";
                            }
                            if (tbl.Columns[i].Generated != null && (bool)tbl.Columns[i].Generated)
                            {
                                fieldAtt += "索引;";
                            }
                        }

                        if (tbl.Columns[i].Generated != null && (bool)tbl.Columns[i].Generated)
                        {
                            fieldAtt += "自增;";
                        }

                        if (tbl.Columns[i].Generated != null && (bool)tbl.Columns[i].Generated)
                        {
                            fieldAtt += "唯一;";
                        }

                        if (tbl.Columns[i].DefaultValue != null && tbl.Columns[i].DefaultValue.Trim().Length > 0)
                        {
                            fieldAtt += "默认=" + tbl.Columns[i].DefaultValue + ";";
                        }

                        SetCellValue(wdtbl.Cell(i + 4, 4), fieldAtt);
                    }
                    object unit  = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
                    object count = 1;
                    wdtbl.Select();
                    this.m_wdapp.Selection.MoveRight(ref unit, ref count, ref nouseref);

                    object br = Microsoft.Office.Interop.Word.WdBreakType.wdLineBreak;
                    this.m_wdapp.Selection.InsertBreak(ref br);
                }
                SaveDoc(filewordPath);
            }
            catch (Exception ex)
            {
                //释放资源
                if (this.m_wdapp != null)
                {
                    m_wdapp.Quit(ref nouseref, ref nouseref, ref nouseref);
                }
                throw ex;
            }
        }
Beispiel #18
0
        /// <summary>
        /// 插入表格
        /// </summary>
        public void InsertTable()
        {
            object myNothing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Table table1 = _wordDocument.Tables.Add(_wordApplication.Selection.Range, 4, 3, ref myNothing, ref myNothing);
            _wordDocument.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";
            _wordDocument.Tables[1].Cell(1, 2).Range.Text = "电脑";
            _wordDocument.Tables[1].Cell(1, 3).Range.Text = "手机";
            _wordDocument.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";
            _wordDocument.Tables[1].Cell(3, 1).Range.Text = "价格(元)";
            _wordDocument.Tables[1].Cell(4, 1).Range.Text = "共同信息";
            _wordDocument.Tables[1].Cell(4, 2).Range.Text = "信息A";
            _wordDocument.Tables[1].Cell(4, 3).Range.Text = "信息B";
            table1.Select();
            table1.Rows.Alignment = Microsoft.Office.Interop.Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中

            _wordApplication.Selection.Cells.VerticalAlignment   = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            _wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.HeightRule          = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
            _wordApplication.Selection.Cells.Height = 40;
            table1.Rows[2].Height = 20;
            table1.Rows[3].Height = 20;
            table1.Rows[4].Height = 20;
            table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.Width = 150;
            table1.Columns[1].Width = 75;
            table1.Cell(1, 1).Range.ParagraphFormat.Alignment      = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;


            _wordApplication.Selection.Cells.VerticalAlignment   = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            _wordApplication.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.HeightRule          = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightExactly;
            _wordApplication.Selection.Cells.Height = 40;
            table1.Rows[2].Height = 20; table1.Rows[3].Height = 20;
            table1.Rows[4].Height = 20;
            table1.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            _wordApplication.Selection.Cells.Width = 150;
            table1.Columns[1].Width = 75;
            table1.Cell(1, 1).Range.ParagraphFormat.Alignment      = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
            table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;

            //表头斜线
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Visible   = true;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;


            //表格边框
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color   = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDoubleWavy;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;

            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Visible   = true;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color     = Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Microsoft.Office.Interop.Word.WdLineWidth.wdLineWidth050pt;
            table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleDouble;


            //合并单元格
            //_wordDocument.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));
        }
Beispiel #19
0
        private void ThisDocument_Startup(object sender, System.EventArgs e)
        {
            SetAppConfigEnvironment();

            _idStruttura = ConfigurationManager.AppSettings["idStruttura"];
            string[] users = new string[1];
            if (ConfigurationManager.AppSettings["utentiVisto"] != null)
            {
                users = ConfigurationManager.AppSettings["utentiVisto"].Split(',');
            }

            int rowNum = (int)Math.Ceiling(users.Length / 5.0);
            int colNum = (int)Math.Ceiling((decimal)users.Length / rowNum);

            Word.Table tb = this.Tables[1];

            tb.Rows[tb.Rows.Count].Cells.Split(rowNum, colNum);
            int i = 0, j = 0;

            foreach (string usr in users)
            {
                tb.Cell((tb.Rows.Count - rowNum) + i + 1, (j % colNum) + 1).Range.Text = usr;

                if ((++j % colNum) == 0)
                {
                    i++;
                }
            }


            _db = new DataBase(ConfigurationManager.AppSettings["DB"], false);
            if (_db.OpenConnection())
            {
                _dtApplicazioni = _db.Select("spGetApplicazioniDisponibili", "@IdStruttura=" + _idStruttura) ?? new DataTable();
                foreach (DataRow r in _dtApplicazioni.Rows)
                {
                    dropDownStrumenti.DropDownListEntries.Add(r["DesApplicazione"].ToString(), r["IdApplicazione"].ToString());
                }

                dropDownStrumenti.DropDownListEntries[1].Select();

                Globals.Ribbons.RiMoSTRibbon.getAvailableID();

                lbDataInvio.LockContents = false;
                lbDataInvio.Text         = DateTime.Now.ToShortDateString();
                lbDataInvio.LockContents = true;

                object what    = Word.WdGoToItem.wdGoToLine;
                object which   = Word.WdGoToDirection.wdGoToLast;
                object missing = Missing.Value;

                _db.CloseConnection();
            }

            //disabilito la modifica per gli elementi strutturali del documento
            tb.Select();
            groupControl1 = this.Controls.AddGroupContentControl("TabellaStruttura");

            dropDownStrumenti.Range.Select();
            this.ThisApplication.Options.PasteFormatWithinDocument = WdPasteOptions.wdKeepTextOnly;
        }