Beispiel #1
1
        public static bool WordToPDF(string sourcePath, string targetPath)
        {
            bool result = false;
            Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
            Microsoft.Office.Interop.Word.Application application = null;

            Microsoft.Office.Interop.Word.Document document = null;
            object unknow = System.Type.Missing;
            application = new Microsoft.Office.Interop.Word.Application();
            application.Visible = false;
            document = application.Documents.Open(sourcePath);
            document.SaveAs();
            document.ExportAsFixedFormat(targetPath, exportFormat, false);
            //document.ExportAsFixedFormat(targetPath, exportFormat);
            result = true;

            //application.Documents.Close(ref unknow, ref unknow, ref unknow);
            document.Close(ref unknow, ref unknow, ref unknow);
            document = null;
            application.Quit();
            //application.Quit(ref unknow, ref unknow, ref unknow);
            application = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return result;
        }
Beispiel #2
0
        public byte[] Convert()
        {
            var objWord = new Application();

            if (File.Exists(FileToSave))
            {
                File.Delete(FileToSave);
            }
            try
            {
                objWord.Documents.Open(FileName: FullFilePath);
                objWord.Visible = false;
                if (objWord.Documents.Count > 0)
                {
                    var oDoc = objWord.ActiveDocument;
                    oDoc.SaveAs(FileName: FileToSave, FileFormat: WdSaveFormat.wdFormatHTML);
                    oDoc.Close(SaveChanges: false);
                }
            }
            finally
            {
                objWord.Application.Quit(SaveChanges: false);
            }
            return base.ReadConvertedFile();
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            try
            {
                FileInfo file = new FileInfo(@args[0]);

                if (file.Extension.ToLower() == ".doc" || file.Extension.ToLower() == ".xml" || file.Extension.ToLower() == ".wml")
                {
                    Word._Application application = new Word.Application();
                    object fileformat = Word.WdSaveFormat.wdFormatXMLDocument;

                    object filename = file.FullName;
                    object newfilename = Path.ChangeExtension(file.FullName, ".docx");
                    Word._Document document = application.Documents.Open(filename);

                    document.Convert();
                    document.SaveAs(newfilename, fileformat);
                    document.Close();
                    document = null;

                    application.Quit();
                    application = null;
                }
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine("Missing parameter: IndexOutOfRangeException {0}", e);
            }
        }
Beispiel #4
0
    static void Main(string[] args)
    {
        var checkAccounts = new List<Account> {
                   new Account {
                                      ID = 345,
                                      Balance = 541.27
                               },
                   new Account {
                                      ID = 123,
                                      Balance = -127.44
                               }
               };

        DisplayInExcel(checkAccounts, (account, cell) =>
        {
            //Multiline lambda
            cell.Value2 = account.ID;
            cell.get_Offset(0, 1).Value2 = account.Balance;

            if (account.Balance < 0)
            {
                cell.Interior.Color = 255;
                cell.get_Offset(0, 1).Interior.Color = 255;
            }
        });

        var word = new Word.Application();
        word.Visible = true;
        word.Documents.Add();
        word.Selection.PasteSpecial(Link: true, DisplayAsIcon: true);
    }
Beispiel #5
0
        private string abstarctRichBoxString(string keyWord, Application testWord)//暂定private testDoc提取richBox内容
        {

            testWord.Selection.Find.Text = keyWord;//查询的文字
            string s = "";
            string previous = "";
            string now = "";
            Selection
            currentSelect = testWord.Selection;
            WdInformation pageNum = WdInformation.wdActiveEndAdjustedPageNumber;
            WdInformation rowNum = WdInformation.wdFirstCharacterLineNumber;
            while (testWord.Selection.Find.Execute())
            {
                object page = currentSelect.get_Information(pageNum);
                object row = currentSelect.get_Information(rowNum);
                previous = now;
                now = currentSelect.Paragraphs[1].Range.Text.Trim();
                list.Add(page);
                list.Add(row);
                if (!now.Equals(previous))
                    s += page + "页" + row + "行  " + now + "\r\r";
            }
            testWord.Selection.HomeKey(WdUnits.wdStory, Type.Missing);
            return s;
        }
Beispiel #6
0
        public MainWin()
        {
            oWord = new Word.Application();
            oWord.Visible = true;

            InitializeComponent();
        }
        public override void Convert(String inputFile, String outputFile)
        {
            Object nothing = System.Reflection.Missing.Value;
            try
            {
                if (!File.Exists(inputFile))
                {
                    throw new ConvertException("File not Exists");
                }

                if (IsPasswordProtected(inputFile))
                {
                    throw new ConvertException("Password Exist");
                }

                app = new Word.Application();
                docs = app.Documents;
                doc = docs.Open(inputFile, false, true, false, nothing, nothing, true, nothing, nothing, nothing, nothing, false, false, nothing, true, nothing);
                doc.ExportAsFixedFormat(outputFile, Word.WdExportFormat.wdExportFormatPDF, false, Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 1, 1, Word.WdExportItem.wdExportDocumentContent, false, false, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, false, false, false, nothing);
            }
            catch (Exception e)
            {
                release();
                throw new ConvertException(e.Message);
            }
            release();
        }
Beispiel #8
0
        public static void SaveWordDoc(string originFile, IEnumerable<KeyValuePair<string, string>> replaceList = null, string targetFile = null, WdSaveFormat format = WdSaveFormat.wdFormatDocumentDefault, MsoEncoding encoding = MsoEncoding.msoEncodingAutoDetect)
        {
            Word.Application ap = null;
            Word.Document doc = null;
            object missing = Type.Missing;
            bool success = true;
            replaceList = replaceList ?? new Dictionary<string, string>();
            targetFile = targetFile ?? originFile;
            if(targetFile.LastIndexOf('.')>targetFile.LastIndexOf('/')||targetFile.LastIndexOf('.')>targetFile.LastIndexOf('\\'))
                targetFile=targetFile.Remove(targetFile.LastIndexOf('.'));

            try
            {
                ap = new Word.Application();
                ap.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                doc = ap.Documents.Open(originFile, ReadOnly: false, Visible: false);
                doc.Activate();

                Selection sel = ap.Selection;

                if (sel == null)
                    throw new Exception("Unable to acquire Selection...no writing to document done..");

                switch (sel.Type)
                {
                    case WdSelectionType.wdSelectionIP:
                        replaceList.ToList().ForEach(p => sel.Find.Execute(FindText: p.Key, ReplaceWith: p.Value, Replace: WdReplace.wdReplaceAll));
                        break;
                    default:
                        throw new Exception("Selection type not handled; no writing done");
                }

                sel.Paragraphs.LineUnitAfter = 0;
                sel.Paragraphs.LineUnitBefore = 0;
                sel.Paragraphs.LineSpacingRule = WdLineSpacing.wdLineSpaceSingle;

                doc.SaveSubsetFonts = false;
                doc.SaveAs(targetFile, format, Encoding: encoding);

            }
            catch (Exception)
            {
                success = false;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close(ref missing, ref missing, ref missing);
                    Marshal.ReleaseComObject(doc);
                }
                if (ap != null)
                {
                    ap.Quit(ref missing, ref missing, ref missing);
                    Marshal.ReleaseComObject(ap);
                }
                if(!success)
                    throw new Exception(); // Could be that the document is already open (/) or Word is in Memory(?)
            }
        }
    public static void Print2(string wordfile, string printer = null)
    {
        oWord.Application wordApp = new oWord.Application();
        wordApp.Visible = false;

        wordApp.Documents.Open(wordfile);
        wordApp.DisplayAlerts = oWord.WdAlertLevel.wdAlertsNone;

        System.Drawing.Printing.PrinterSettings settings = new System.Drawing.Printing.PrinterSettings();

        if (printer == null) // print to all installed printers
        {
            foreach (string p in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                try
                {
                    settings.PrinterName = p;
                    wordApp.ActiveDocument.PrintOut(false);
                }
                catch (Exception ex)
                {
                    Logger.LogException(ex, true);
                }
            }
        }
        else
        {
            settings.PrinterName = printer;
            wordApp.ActiveDocument.PrintOut(false);
        }

        wordApp.Quit(oWord.WdSaveOptions.wdDoNotSaveChanges);
    }
 public void setup()
 {
     wordApp = WordApplicationHelper.GetApplication();
     if (wordApp.Documents.Exists(IOHelpers.FirmAddressTestData))
         wordApp.Documents.First(IOHelpers.FirmAddressTestData).Close(Wd.WdSaveOptions.wdDoNotSaveChanges);
     doc = wordApp.Documents.Open(IOHelpers.FirmAddressTestData.FullName);
 }
Beispiel #11
0
        // Usage:
        // using Word = Microsoft.Office.Interop.Word;
        // Action<Word.Application> f = w =>
        // {
        //      var d = w.Documents.Open(@"C:\Foo.docx");
        // };
        // Word1.With(f);
        internal static void With(Action<Word.Application> f)
        {
            Word.Application app = null;

            try
            {
                app = new Word.Application
                {
                    DisplayAlerts = Word.WdAlertLevel.wdAlertsNone,
                    Visible = true
                };
                f(app);
            }
            finally
            {
                if (app != null)
                {
                    if (0 < app.Documents.Count)
                    {
                        // Unlike Excel, Close(...) makes an error when app.Documents.Count == 0
                        // Unlike Excel, Close(...) without wdDoNotSaveChanges shows a prompt for a dirty document.
                        app.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges);
                    }

                    app.Quit();

                    // Both of the following are needed in some cases
                    // while none of them are needed in other cases.
                    Marshal.FinalReleaseComObject(app);
                    GC.Collect();
                }
            }
        }
Beispiel #12
0
        public A()
        {
            oracon = new OracleConnection("server = 127.0.0.1/orcx; user id = qzdata; password = xie51");
            oracon2 = new OracleConnection("server = 10.5.67.11/pdbqz; user id = qzdata; password = qz9401tw");
            wordapp = new word.Application();
            worddoc = new word.Document();
            worddoc = wordapp.Documents.Add();

            worddoc.SpellingChecked = false;
            worddoc.ShowSpellingErrors = false;

     //       wordapp.Visible = true;
            ta.wordapp = wordapp;
            ta.worddoc = worddoc;
            if (IS_YEAR)
            {
                datestr = dsf.GetDateStr(the_year_begin_int, the_month_begin_int, the_year_end_int, the_month_end_int);
            }
            else
            {
                datestr = dsf.GetDateStr(the_date);
            }
            
       //     datestr_abid = "(" + datestr + "and a.ab_id >=1 and a.ab_id <= 7)";
            datestr_abid = "(" + datestr + "and" + abidstr + ")";
            oracon2.Open();
            orahlper = new OraHelper(oracon2);
            orahlper.feedback = true;

            the_month_begin = new DateTime(the_date.Year, the_date.Month, 1, 0, 0, 0);
            the_month_end = the_month_begin.AddMonths(1).AddSeconds(-1);

        }
Beispiel #13
0
        void PrepareApplication()
        {
            if (_application == null)
            {
                _application = new Microsoft.Office.Interop.Word.Application { Caption = WordApplicationTitle, Visible = true };



                ((ApplicationEvents4_Event)_application).Quit += _application_ApplicationEvents4_Event_Quit;

                var processId = Win32Helper.GetProcessIdByWindowTitle(WordApplicationTitle);
                //var processId = Win32Helper.GetEmtyWordProcess();

                while (processId < 0)
                {
                    Thread.Sleep(5);
                    processId = Win32Helper.GetProcessIdByWindowTitle(WordApplicationTitle);
                    //processId = Win32Helper.GetEmtyWordProcess();
                }

                _application.Visible = false;

                HostedHandle = Win32Helper.FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, WordApplicationTitle).ToInt32();

                _application.Visible = true;
            }
        }
Beispiel #14
0
    public static void CompareInWord(string fullpath, string newFullpath, string saveName, string saveDir, string author, bool save = false) {
      Object missing = Type.Missing;
      try {
        var wordapp = new Microsoft.Office.Interop.Word.Application();
        try {
          var doc = wordapp.Documents.Open(fullpath, ReadOnly: true);
          doc.Compare(newFullpath, author ?? missing);
          doc.Close(WdSaveOptions.wdDoNotSaveChanges); // Close the original document
          var dialog = wordapp.Dialogs[WdWordDialog.wdDialogFileSummaryInfo];
          // Pre-set the save destination by setting the Title in the save dialog.
          // This must be done through reflection, since "dynamic" is only supported in .NET 4
          dialog.GetType().InvokeMember("Title", BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty,
                                        null, dialog, new object[] {saveName});
          dialog.Execute();
          wordapp.ChangeFileOpenDirectory(saveDir);
          if (!save) {
            wordapp.ActiveDocument.Saved = true;
          }

          wordapp.Visible = true;
          wordapp.Activate();

          // Simple hack to bring the window to the front.
          wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMinimize;
          wordapp.ActiveWindow.WindowState = WdWindowState.wdWindowStateMaximize;
        } catch (Exception ex) {
          Logger.LogException(ex);
          ShowMessageBox("Word could not open these documents. Please edit the file manually.", "Error");
          wordapp.Quit();
        }
      } catch (Exception ex) {
        Logger.LogException(ex);
        ShowMessageBox("Could not start Microsoft Word. Office 2003 or higher is required.", "Could not start Word");
      }
    }
Beispiel #15
0
        public void PasteTest()
        {
            var fileName = TestFileNames.SourceFile;
            var word = new Application { Visible = false };
            var doc = word.Documents.Open(fileName);

            try
            {
                // ReSharper disable UseIndexedProperty
                var range = doc.Bookmarks.get_Item("Bibliography").Range;
                // ReSharper restore UseIndexedProperty

                var html = Utils.GetHtmlClipboardText("Hello <i>World!</i>");
                Clipboard.SetText(html, TextDataFormat.Html);
                range.PasteSpecial(DataType: WdPasteDataType.wdPasteHTML);

                var destFileName = Path.Combine(Path.GetDirectoryName(fileName),
                    Path.GetFileNameWithoutExtension(fileName) + "-updated" + Path.GetExtension(fileName));
                word.ActiveDocument.SaveAs(destFileName);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.GetMessage());
            }
            finally
            {
                word.Quit(false);
            }
        }
Beispiel #16
0
        public WordDocument(String templateName, bool visible)
        {
            List<int> startedWords = new List<int>();

            foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
            {
                startedWords.Add(p.Id);
            }

            Object missingValue = Missing.Value;
            Object template = templateName;
            if (wordapp == null)
                wordapp = new Word.Application();

            foreach (Process p in System.Diagnostics.Process.GetProcessesByName("winword"))
            {
                if (!startedWords.Contains(p.Id))
                {
                    IDs.Add(p.Id);
                }
            }
            wordapp.Visible = visible;
            doc = wordapp.Documents.Add(ref template,
            ref missingValue, ref missingValue, ref missingValue);
            doc.ActiveWindow.Selection.MoveEnd(Word.WdUnits.wdStory);

            tempFileName = Path.Combine(Path.GetDirectoryName(templateName), tempFileName);
        }
Beispiel #17
0
 private void button1_Click(object sender, EventArgs e)
 {
     //закриває всі відкриті ворди
     String[] s = textBox1.Text.Split(new[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries);
     int step = (int) 100/s.Length;
     for (int i = 0; i < s.Length; i++)
     {
         try
         {
             Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
             var wordDocument = appWord.Documents.Open(s[i]);
             s[i] = s[i].Replace(".docx", ".pdf");
             s[i] = s[i].Replace(".doc", ".pdf");
             wordDocument.ExportAsFixedFormat(s[i], WdExportFormat.wdExportFormatPDF);
             wordDocument.Close();
             appWord.Quit();
         }
         catch{}
         progressBar1.Value += step;
     }
     progressBar1.Value = 100;
     MessageBox.Show("Готово", "Звіт про виконання", MessageBoxButtons.OK, MessageBoxIcon.Information);
     textBox1.Clear();
     progressBar1.Value = 0;
 }
 public void CloseWordApp()
 {
     document.Close(ref falseObj, ref  missingObj, ref missingObj);
     application.Quit(ref missingObj, ref  missingObj, ref missingObj);
     document = null;
     application = null;
 }
Beispiel #19
0
        static void Main(string[] args)
        {
            FileInfo file = new FileInfo(@args[0]);

            if (file.Extension.ToLower() == ".docx")
            {
                Console.WriteLine("Starting file name extraction...");

                //Set the Word Application Window Title
                string wordAppId = "" + DateTime.Now.Ticks;

                Word.Application word = new Word.Application();
                word.Application.Caption = wordAppId;
                word.Application.Visible = true;
                int processId = GetProcessIdByWindowTitle(wordAppId);
                word.Application.Visible = false;

                try
                {
                    object filename = file.FullName;
                    Word._Document document = word.Documents.OpenNoRepairDialog(filename);
                    Console.WriteLine("Extracting file names from document '{0}'.", file);

                    //Console.WriteLine("Document has {0} shapes.", document.InlineShapes.Count);
                    if (document.InlineShapes.Count > 0)
                    {
                        foreach (Word.InlineShape shape in document.InlineShapes)
                        {
                            if (shape.Type == Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject)
                            {
                                Console.WriteLine("Found file name: {0}", shape.OLEFormat.IconLabel);
                            }
                        }
                    }

                    document.Close();
                    document = null;

                    word.Quit();
                    word = null;
                    Console.WriteLine("Success, quitting Word.");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error ocurred: {0}", e);
                }
                finally
                {
                    // Terminate Winword instance by PID.
                    Console.WriteLine("Terminating Winword process with the Windowtitle '{0}' and the Application ID: '{1}'.", wordAppId, processId);
                    Process process = Process.GetProcessById(processId);
                    process.Kill();
                }
            }
            else
            {
                Console.WriteLine("Only DOCX files possible.");
            }
        }
Beispiel #20
0
 private void btn_OutPut_Click(object sender, EventArgs e)
 {
     List<Fruit> P_Fruit = new List<Fruit>();//创建数据集合
     foreach (DataGridViewRow dgvr in dgv_Message.Rows)
     {
         P_Fruit.Add(new Fruit()//向数据集合添加数据
         {
             Name = dgvr.Cells[0].Value.ToString(),
             Price = Convert.ToSingle(dgvr.Cells[1].Value.ToString())
         });
     }
     SaveFileDialog P_SaveFileDialog =//创建保存文件对话框对象
         new SaveFileDialog();
     P_SaveFileDialog.Filter = "*.doc|*.doc";
     if (DialogResult.OK ==//确认是否保存文件
         P_SaveFileDialog.ShowDialog())
     {
         ThreadPool.QueueUserWorkItem(//开始线程池
         (pp) =>//使用lambda表达式
         {
             G_wa = new Microsoft.Office.Interop.Word.Application();//创建应用程序对象
             object P_obj = "Normal.dot";//定义文档模板
             Word.Document P_wd = G_wa.Documents.Add(//向Word应用程序中添加文档
                 ref P_obj, ref G_missing, ref G_missing, ref G_missing);
             Word.Range P_Range = P_wd.Range(//得到文档范围
                 ref G_missing, ref G_missing);
             object o1 = Word.WdDefaultTableBehavior.//设置文档中表格格式
                 wdWord8TableBehavior;
             object o2 = Word.WdAutoFitBehavior.//设置文档中表格格式
                 wdAutoFitWindow;
             Word.Table P_WordTable = P_Range.Tables.Add(P_Range,//在文档中添加表格
                 P_Fruit.Count ,2, ref o1, ref o2);
             P_WordTable.Cell(1, 1).Range.Text = "水果";//向表格中添加信息
             P_WordTable.Cell(1, 2).Range.Text = "价格";//向表格中添加信息
             for (int i = 2; i < P_Fruit.Count + 1; i++)
             {
                 P_WordTable.Cell(i, 1).Range.Text =//向表格中添加信息
                     P_Fruit[i - 2].Name;
                 P_WordTable.Cell(i, 2).Range.Text =//向表格中添加信息
                     P_Fruit[i - 2].Price.ToString();
             }
             object P_Path = P_SaveFileDialog.FileName;
             P_wd.SaveAs(//保存Word文件
                 ref P_Path,
                 ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                 ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                 ref G_missing, ref G_missing, ref G_missing, ref G_missing,
                 ref G_missing, ref G_missing, ref G_missing);
             ((Word._Application)G_wa.Application).Quit(//退出应用程序
                 ref G_missing, ref G_missing, ref G_missing);
             this.Invoke(//调用窗体线程
                 (MethodInvoker)(() =>//使用lambda表达式
                 {
                     MessageBox.Show(//弹出消息对话框
                         "成功创建Word文档!", "提示!");
                 }));
         });
     }
 }
Beispiel #21
0
 /// <summary>
 /// Creates the XWord menu.
 /// </summary>
 /// <param name="wordApplication">The <code>Word.Application</code>.</param>
 public void CreateXWordMenu(Word.Application wordApplication)
 {
     this.application = wordApplication;
     this.officeMenuBar = wordApplication.CommandBars.ActiveMenuBar;
     BuildMenus();
     EnqueueEventHandlers();
     DisableXWordMenus();
 }
Beispiel #22
0
 /// <summary>
 /// Generates a word instance
 /// </summary>
 /// <param name="settings"></param>
 private WordGenerator(NamedLookup settings, bool silent) : base(settings, silent)
 {
     app = new Word.Application();
     app.Visible = !this.silent;
     document = app.Documents.Add(Type.Missing, Type.Missing,
     Word.WdNewDocumentType.wdNewBlankDocument, !this.silent);
     document.UserControl = !this.silent;
 }
Beispiel #23
0
 private void SendToPrinter(Application wordApp)
 {
     wordApp.ActivePrinter = _printerCapture();
     wordApp.PrintOut(true, false, WdPrintOutRange.wdPrintAllDocument,
         Item: WdPrintOutItem.wdPrintDocumentContent, Copies: "1", Pages: "",
         PageType: WdPrintOutPages.wdPrintAllPages, PrintToFile: false, Collate: true,
         ManualDuplexPrint: false);
 }
        public WordInstance(Word.Application app)
        {
            m_App = app;
            m_App.Activate();

            // Get the window handle.
            m_WindowHandle = WindowsApi.GetForegroundWindow();
        }
Beispiel #25
0
 public CopiesForm(ThisAddIn thisAddIn, Word.Application wordApp, object fileName)
 {
     InitializeComponent();
     myThisAddIn = thisAddIn;
     WordApp = wordApp;
     FileName = fileName;
     copies = 0;
 }
Beispiel #26
0
 public WordDocument()
 {
     Object missingValue = Missing.Value;
     Object template = Type.Missing;
     if (wordapp == null)
         wordapp = new Word.Application();
     doc = wordapp.Documents.Add(ref template,
     ref missingValue, ref missingValue, ref missingValue);
 }
Beispiel #27
0
 static void Main(string[] args)
 {
     object filename = "E:\\file7.docx";
     Word.Application word = new Word.Application();
     word.Documents.Add();
     word.Selection.TypeText("Programowanie pod Windows");
     word.ActiveDocument.SaveAs2(ref filename);
     word.Documents.Close();
 }
        public static IList<Einsatz> getEinsaetze(string path, Playlist playlist)
        {
            Check.Require( new NHibernateDaoFactory().getPlaylistDao().GetUniqueByExample(playlist,
                Playlist.Property.Description.ToString(),
                Playlist.Property.IsClosed.ToString(),
                Playlist.Property.Sendetermin.ToString()) == null, String.Format(
                "A {0} entity '{1}' does already exist.", playlist.GetType().Name, playlist.Name));

            object template = path;
            object isNewTemplate = false;
            object documentType = WdNewDocumentType.wdNewBlankDocument;
            object isVisible = false;

            Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document doc = app.Documents.Add(ref template, ref isNewTemplate, ref documentType, ref isVisible);

            Check.Require(doc.Tables[1].Tables.Count < 2, "Undefined word template.");

            IList<Einsatz> einsaetze = new List<Einsatz>();

            if(doc.Tables[1].Tables.Count == 0 && doc.Tables[1].Rows[1].Cells.Count == 4) {
                einsaetze = FileUpload_Service.readMdrFormat(doc, playlist);
            }
            else if(doc.Tables[1].Tables.Count == 0 && doc.Tables[1].Rows[1].Cells.Count == 7) {
                einsaetze = FileUpload_Service.readOldFormat(doc, playlist);
            }
            else if(doc.Tables[1].Tables.Count == 1) {
                Check.Require(doc.Tables[1].Rows[1].Cells[1].Range.Text.StartsWith("Titel"), String.Format(
                    "New format: row should start with 'Titel' but starts with {0}.",
                    doc.Tables[1].Rows[1].Cells[1].Range.Text.Substring(0, 10)));
                Check.Require(doc.Tables[1].Rows[1].Cells.Count == 1, String.Format(
                    "New format: column number should be 1 but is {0}.",
                    doc.Tables[1].Rows[1].Cells.Count));
                Check.Require(doc.Tables[1].Rows[2].Cells[1].Range.Text.StartsWith("Musiktitel"), String.Format(
                    "New format: row should start with 'Musiktitel' but starts with {0}.",
                    doc.Tables[1].Rows[2].Cells[1].Range.Text.Substring(0, 10)));
                Check.Require(doc.Tables[1].Rows[3].Cells.Count == 7, String.Format(
                    "New format: column number should be 7 but is {0}.",
                    doc.Tables[1].Rows[3].Cells.Count));

                einsaetze = FileUpload_Service.readNewFormat(doc, playlist);
            }
            else if(doc.Tables.Count == 2 && doc.Tables[1].Rows[1].Cells.Count == 3) {
                einsaetze = FileUpload_Service.readShortFormat(doc, playlist);
            }
            else {
                throw new PreconditionException("Unknown playlist format.");
            }

            object SaveChanges = WdSaveOptions.wdDoNotSaveChanges;
            object OriginalFormat = WdOriginalFormat.wdWordDocument;
            object RouteDocument = true;

            ((Microsoft.Office.Interop.Word.Application)app).Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);

            return einsaetze;
        }
Beispiel #29
0
        public void GenerateContractReport(WholesaleEntities db, DateTime fromDate, DateTime toDate)
        {
            object oMissing = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */
            int i = 1;

            //Start Word and create a new document.
            Word._Application oWord;
            Word._Document oDoc;
            oWord = new Word.Application();
            oWord.Visible = true;
            oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
                ref oMissing, ref oMissing);

            //Insert a paragraph at the beginning of the document.
            Word.Paragraph oPara1;
            oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
            oPara1.Range.Text = String.Format("Отчет о продажах за период c {0} по {1}", fromDate.ToShortDateString(), toDate.ToShortDateString());
            oPara1.Range.Font.Bold = 1;
            oPara1.Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter; //alignment center
            oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
            oPara1.Range.InsertParagraphAfter();

            //Insert a 3 x 5 table, fill it with data, and make the first row
            //bold and italic.
            List<Contracts> contracts = db.Contracts.Where(x=> x.date >= fromDate && x.date <= toDate).ToList();
            Word.Table oTable;
            Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oTable = oDoc.Tables.Add(wrdRng, contracts.Count+1, 5, ref oMissing, ref oMissing);
            oTable.Range.ParagraphFormat.SpaceAfter = 6;
            oTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
            oTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
        
            //header
            oTable.Cell(i, 1).Range.Text = "№ накладной";
            oTable.Cell(i, 2).Range.Text = "Дата";
            oTable.Cell(i, 3).Range.Text = "Покупатель";
            oTable.Cell(i, 4).Range.Text = "Контактное лицо";
            oTable.Cell(i, 5).Range.Text = "Общая сумма, грн";

            //content
            foreach(Contracts contract in contracts)
            {
                i++;
                oTable.Cell(i, 1).Range.Text = Convert.ToString(contract.contractID);
                oTable.Cell(i, 2).Range.Text = Convert.ToString(contract.date.ToShortDateString());
                oTable.Cell(i, 3).Range.Text = Convert.ToString(db.Clients.FirstOrDefault(x => x.clientID == contract.clientID).name);
                oTable.Cell(i, 4).Range.Text = Convert.ToString(db.Clients.FirstOrDefault(x => x.clientID == contract.clientID).contactName);
                oTable.Cell(i, 5).Range.Text = Convert.ToString(db.ContractProducts.Where(z => z.contractID == contract.contractID).Sum(x => x.count * x.ProductDeliveries.Products.price + x.ProductDeliveries.Deliveries.price));
            }
          
            oTable.Rows[1].Range.Font.Bold = 1;
            oTable.Rows[1].Range.Font.Italic = 1;
            oTable.Columns.AutoFit();

        }
Beispiel #30
0
        private void button1_Click(object sender, EventArgs e) // generate button
        {
            // Template document
            // This changes between Q4 and Q8
            if (Q4 == true)
            {
                // SRY Need to update docTemplate locations for M: drive
                docTemplate = "\\\\intruder\\userdata\\AnalyticalTestEng\\SUB_Certs\\Templates\\Q4 Cert Single Use Liquid Template.docx";
            }
            else
            {
                docTemplate = "\\\\intruder\\userdata\\AnalyticalTestEng\\SUB_Certs\\Templates\\Q8 Cert Single Use Liquid Template.docx";
            }

            connect();

            string        certString = "SELECT [pH_Slope_at_25C_Measurement], [Offset_at_pH7_Measurement], [pH_Slope_at_25C_PassFail], [Span_Measurement] FROM Calibration_Results WHERE [Serial_Number] = " + "'" + SerialNumber + "'";
            var           checkComm  = new SqlCommand(certString, dbConn);
            SqlDataReader certRead   = checkComm.ExecuteReader();

            while (certRead.Read())
            {
                pHSlope    = certRead["pH_Slope_at_25C_Measurement"].ToString();
                pHOffset   = certRead["Offset_at_pH7_Measurement"].ToString();
                SensorPF   = certRead["pH_Slope_at_25C_PassFail"].ToString();
                SensorSpan = certRead["Span_Measurement"].ToString();

                if (SensorPF.Equals("True"))
                {
                    SensorPF = "PASS";
                }
                else
                {
                    SensorPF = "FAIL";
                }


                Console.WriteLine("pHSlope = " + pHSlope);
                Console.WriteLine("pHOffset = " + pHOffset);
                Console.WriteLine("SensorPF = " + SensorPF);
            }
            Console.ReadLine();

            certRead.Close();
            dbConn.Close();

            // New document with replaced text
            // New doc for each serial number
            if (Q4 == true)
            {
                Q4Q8 = "Q4";
            }
            else
            {
                Q4Q8 = "Q8";
            }
            string saveStr = filepathroot + Q4Q8 + "_CERT_" + SerialNumber + ".docx";

            object saveAsFileName = @saveStr;

            Word.Application ap      = new Word.Application();
            object           missing = System.Type.Missing;

            Word.Document doc1 = ap.Documents.Open(@docTemplate);

            try
            {
                FindAndReplace(ap, "<serialNumber>", SerialNumber);
                FindAndReplace(ap, "<pHslope1>", pHSlope);
                FindAndReplace(ap, "<pHoffset1>", pHOffset);
                FindAndReplace(ap, "<PF1>", SensorPF);
                //<span1>
                FindAndReplace(ap, "<span1>", SensorSpan);
                //<deviceType>
                FindAndReplace(ap, "<deviceType>", "Single Use");
                //<modelNumber>
                FindAndReplace(ap, "<modelNumber>", "550PH-COMMON");
                //<factoryInfo>
                FindAndReplace(ap, "<factoryInfo>", "Mexicali, MX");
                //<stationNameInfo>
                FindAndReplace(ap, "<stationNameInfo>", "SUB Tester 1");
                //<operatorIDInfo>
                FindAndReplace(ap, "<operatorIDInfo>", "72739");
                //<calDateInfo>
                string DateStr = DateTime.Now.ToString("MM/dd/yyyy");
                FindAndReplace(ap, "<calDateInfo>", DateStr);

                doc1.SaveAs(ref saveAsFileName,
                            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);

                //MessageBox.Show("Certificate Word document has been generated in " + saveStr);
                MessageBox.Show(CertFileMsg + saveStr);
            }
            catch
            {
                MessageBox.Show("Error populating cert form");
            }

            object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;

            doc1.Close(ref doNotSaveChanges, ref missing, ref missing);
        }
Beispiel #31
0
        //Creeate the Doc Method
        private void CreateWordDocument(object filename, object SaveAs)
        {
            Word.Application wordApp = new Word.Application();
            object           missing = Missing.Value;

            Word.Document myWordDoc = null;

            if (File.Exists((string)filename))
            {
                object readOnly  = false;
                object isVisible = false;
                wordApp.Visible = false;

                myWordDoc = wordApp.Documents.Open(ref filename, ref missing, ref readOnly,
                                                   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);
                myWordDoc.Activate();

                //find and replace
                String sem = tbsem.Text;
                String ext;
                if (sem == "1")
                {
                    ext = "st";
                }
                else if (sem == "2")
                {
                    ext = "nd";
                }
                else if (sem == "3")
                {
                    ext = "rd";
                }
                else
                {
                    ext = "th";
                }
                this.FindAndReplace(wordApp, "<name>", tbname.Text);
                this.FindAndReplace(wordApp, "<semester>", tbsem.Text + ext + " Semester");
                this.FindAndReplace(wordApp, "<branch>", tbbranch.Text);
                this.FindAndReplace(wordApp, "<event>", tbevent.Text + " tournament");
                this.FindAndReplace(wordApp, "<date>", date.Value.Date);
                this.FindAndReplace(wordApp, "<acadyear>", DateTime.Now.Year + "-" + Convert.ToString(DateTime.Now.Year + 1));
            }
            else
            {
                MessageBox.Show("File not Found!");
            }

            //Save as
            myWordDoc.SaveAs2(ref SaveAs, 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);

            myWordDoc.Close();
            wordApp.Quit();
            MessageBox.Show("File Created!");
        }
Beispiel #32
0
        private void ConvertToHtml(ConvertType convertType, String filePath = "", String para = "")
        {
            Monitor.Enter(this);
            bool   _haveErreo = false;//是否有错误
            object FileName   = m_SAVEFOLDER + @"\myfile" + _index++ + ".htm";
            bool   isExists   = Directory.Exists(m_SAVEFOLDER);

            if (!isExists)
            {
                Directory.CreateDirectory(m_SAVEFOLDER);
            }
            try
            {
                #region 用word转换成html
                //filePath如果为空就用剪切板里的内容
                if (string.IsNullOrEmpty(filePath.Trim()))
                {
                    m_app         = new Microsoft.Office.Interop.Word.Application();
                    m_app.Visible = false;
                    object oMissing = Missing.Value;
                    m_oDoc = m_app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                    m_oDoc.Content.Paste();



                    object FileFormat = WdSaveFormat.wdFormatFilteredHTML;
                    if (convertType == ConvertType.WORD)
                    {
                        FileFormat = WdSaveFormat.wdFormatDocument;
                        FileName   = FileName.ToString().Replace(".htm", ".doc");
                    }
                    m_oDoc.SaveAs(ref FileName, ref FileFormat);
                }
                #endregion
            }
            catch (Exception ex)
            {
                ShowDebugMessage("保存Word失败!错误方法名为ConvertToHtml:详细信息:" + ex.Message);
                _haveErreo = true;
            }
            finally
            {
                if (string.IsNullOrEmpty(filePath.Trim()))
                {
                    m_oDoc.Close(null, null, null);
                    m_app.Quit();
                    m_oDoc = null;
                    m_app  = null;
                    GC.Collect();
                }

                #region
                if (!_haveErreo)
                {
                    if (convertType == ConvertType.WORD)
                    {
                        m_returnHTML = JAVAFieldsMethod(m_SAVEFOLDER, string.Empty, convertType, filePath, para);
                    }
                    else if (convertType == ConvertType.HTML)
                    {
                        //上传文件
                        m_returnHTML = JAVAFieldsMethod(m_SAVEFOLDER + @"\myfile" + --_index + ".files", FileName.ToString(), convertType);
                    }
                    if (!string.IsNullOrEmpty(m_returnHTML.Trim()))
                    {
                        javaScriptEventFire("1");
                    }
                    else
                    {
                        javaScriptEventFire("0", "上传失败");
                    }
                    DeleteFolderrsFiles(m_SAVEFOLDER);//删除文件
                }
                else
                {
                    javaScriptEventFire("0", "转换失败");
                }
                #endregion
                Monitor.Exit(this);
            }
        }
Beispiel #33
0
        private void btn1_Click_1(object sender, RoutedEventArgs e)
        {
            clearComments();
            string doc_file_name = Directory.GetCurrentDirectory() + @"\Files\content.doc";

            MsWord.Application oWordApplic; //a reference to Wordapplication
            MsWord.Document    oDoc;        //a reference to thedocument
            try
            {
                if (File.Exists(doc_file_name))
                {
                    File.Delete(doc_file_name);
                }
                oWordApplic = new MsWord.Application();
                object missing = System.Reflection.Missing.Value;

                MsWord.Range curRange;
                object       curTxt;
                int          curSectionNum = 1;
                oDoc = oWordApplic.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                oDoc.Activate();
                Console.WriteLine(" 正在生成文档小节");
                showComment("正在生成文档小节");

                object section_nextPage = MsWord.WdBreakType.wdSectionBreakNextPage;
                object page_break       = MsWord.WdBreakType.wdPageBreak;
                //添加三个分节符,共四个小节
                for (int si = 0; si < 5; si++)
                {
                    oDoc.Paragraphs[1].Range.InsertParagraphAfter();
                    oDoc.Paragraphs[1].Range.InsertBreak(ref section_nextPage);
                }

                Console.WriteLine(" 正在插入摘要内容");
                showComment("正在插入摘要内容");
                #region 摘要部分
                curSectionNum = 1;
                curRange      = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.Select();
                string one_str, key_word;
                //摘要的文本来自 abstract.txt 文本文件
                StreamReader file_abstract = new StreamReader(Directory.GetCurrentDirectory() + @"\Files\abstract.txt");
                oWordApplic.Options.Overtype = false;//overtype 改写模式
                MsWord.Selection currentSelection = oWordApplic.Selection;
                if (currentSelection.Type == MsWord.WdSelectionType.wdSelectionNormal)
                {
                    one_str = file_abstract.ReadLine();  //读入题目
                    currentSelection.TypeText(one_str);
                    currentSelection.TypeParagraph();    //添加段落标记
                    currentSelection.TypeText(" 摘要");    //写入" 摘要" 二字
                    currentSelection.TypeParagraph();    //添加段落标记
                    key_word = file_abstract.ReadLine(); //读入题目
                    one_str  = file_abstract.ReadLine(); //读入段落文本
                    while (one_str != null)
                    {
                        currentSelection.TypeText(one_str);
                        currentSelection.TypeParagraph(); //添加段落标记
                        one_str = file_abstract.ReadLine();
                    }
                    currentSelection.TypeText(" 关键字:");
                    currentSelection.TypeText(key_word);
                    currentSelection.TypeParagraph(); //添加段落标记
                }
                file_abstract.Close();
                //摘要的标题
                curRange           = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curTxt             = curRange.Paragraphs[1].Range.Text;
                curRange.Font.Name = " 宋体";
                curRange.Font.Size = 22;
                curRange.Paragraphs[1].Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                //" 摘要" 两个字
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[2].Range;
                curRange.Select();
                curRange.Paragraphs[1].Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                curRange.Font.Name = " 黑体";
                curRange.Font.Size = 16;
                //摘要正文
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                for (int i = 3; i < oDoc.Sections[curSectionNum].Range.Paragraphs.Count; i++)
                {
                    curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[i].Range;
                    curTxt   = curRange.Paragraphs[1].Range.Text;
                    curRange.Select();
                    curRange.Font.Name = " 宋体";
                    curRange.Font.Size = 12;
                    oDoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacingRule =
                        //oDoc.Paragraphs[i].LineSpacingRule =
                        MsWord.WdLineSpacing.wdLineSpaceMultiple;
                    //多倍行距,1.25 倍,这里的浮点值是以 point 为单位的,不是行距倍数
                    oDoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacing = 15f;
                    oDoc.Sections[curSectionNum].Range.Paragraphs[i].IndentFirstLineCharWidth(2);
                }
                //设置" 关键字:" 为黑体
                curRange = curRange.Paragraphs[curRange.Paragraphs.Count].Range;
                curTxt   = curRange.Paragraphs[1].Range.Text;
                object range_start, range_end;
                range_start = curRange.Start;
                range_end   = curRange.Start + 4;
                curRange    = oDoc.Range(ref range_start, ref range_end);
                curTxt      = curRange.Text;
                //curRange = curRange.Range(ref range_start, ref range_end);
                curRange.Select();
                curRange.Font.Bold = 1;
                #endregion 摘要部分

                Console.WriteLine(" 正在插入目录");
                showComment("正在插入目录");
                #region 目录
                curSectionNum = 2;
                curRange      = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.Select();
                //插入目录时指定的参数
                object useheading_styles     = true; //使用内置的目录标题样式
                object upperheading_level    = 1;    //最高的标题级别
                object lowerheading_level    = 3;    //最低标题级别
                object usefields             = 1;    //true 表示创建的是目录
                object tableid               = 1;
                object RightAlignPageNumbers = true; //右边距对齐的页码
                object IncludePageNumbers    = true; //目录中包含页码
                currentSelection = oWordApplic.Selection;
                currentSelection.TypeText(" 目录");
                currentSelection.TypeParagraph();
                currentSelection.Select();
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[2].Range;
                //插入的表格会代替当前 range
                //range 为非折叠时,TablesOfContents 会代替 range,引起小节数减少。
                curRange.Collapse();
                oDoc.TablesOfContents.Add(curRange, ref useheading_styles, ref upperheading_level,
                                          ref lowerheading_level, ref usefields, ref tableid, ref RightAlignPageNumbers,
                                          ref IncludePageNumbers, ref missing, ref missing, ref missing, ref missing);
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Font.Bold = 1;
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Font.Name = " 黑体";
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Font.Size = 16;
                #endregion 目录


                #region 第一章
                showComment("正在插入第一章内容");
                curSectionNum = 3;
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Select();
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                Console.WriteLine(" 正在设置标题样式");
                showComment("正在设置标题样式");

                object wdFontSizeIndex;
                wdFontSizeIndex = 14;//此序号在 word 中的编号是格式 > 显示格式 > 样式和格式 > 显示所有样式的序号
                //14 即是标题一一级标题:三号黑体。
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).ParagraphFormat.Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Name = " 黑体";
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Size = 16; //三号
                wdFontSizeIndex = 15;                                                           //15 即是标题二二级标题:小三号黑体。
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Name = " 黑体";
                oWordApplic.ActiveDocument.Styles.get_Item(ref wdFontSizeIndex).Font.Size = 15; //小三
                //用指定的标题来设定文本格式
                object Style1 = MsWord.WdBuiltinStyle.wdStyleHeading1;                          //一级标题:三号黑体。
                object Style2 = MsWord.WdBuiltinStyle.wdStyleHeading2;                          //二级标题:小三号黑体。
                oDoc.Sections[curSectionNum].Range.Select();
                currentSelection = oWordApplic.Selection;
                //读入第一章文本信息
                StreamReader file_content = new StreamReader(Directory.GetCurrentDirectory() + @"\Files\content.txt");
                one_str = file_content.ReadLine(); //一级标题
                currentSelection.TypeText(one_str);
                currentSelection.TypeParagraph();  //添加段落标记
                one_str = file_content.ReadLine(); //二级标题
                currentSelection.TypeText(one_str);
                currentSelection.TypeParagraph();  //添加段落标记
                one_str = file_content.ReadLine(); //正文
                while (one_str != null)
                {
                    currentSelection.TypeText(one_str);
                    currentSelection.TypeParagraph();  //添加段落标记
                    one_str = file_content.ReadLine(); //正文
                }
                file_content.Close();
                //段落的对齐方式
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[2].Range;
                curRange.set_Style(ref Style2);
                //第一章正文文本格式
                for (int i = 3; i < oDoc.Sections[curSectionNum].Range.Paragraphs.Count; i++)
                {
                    curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[i].Range;
                    curRange.Select();
                    curRange.Font.Name = " 宋体";
                    curRange.Font.Size = 12;
                    oDoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacingRule =
                        MsWord.WdLineSpacing.wdLineSpaceMultiple;
                    //多倍行距,1.25 倍,这里的浮点值是以 point 为单位的,不是行距的倍数
                    oDoc.Sections[curSectionNum].Range.Paragraphs[i].LineSpacing = 15f;
                    oDoc.Sections[curSectionNum].Range.Paragraphs[i].IndentFirstLineCharWidth(2);
                }
                #endregion 第一章

                Console.WriteLine(" 正在插入第二章内容");
                showComment("正在插入第二章内容");
                #region 第二章表格
                curSectionNum = 4;
                oDoc.Sections[curSectionNum].Range.Select();
                curRange         = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                currentSelection = oWordApplic.Selection;
                currentSelection.TypeText("2 表格");
                currentSelection.TypeParagraph();
                currentSelection.TypeText(" 表格示例");
                currentSelection.TypeParagraph();
                currentSelection.TypeParagraph();
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[3].Range;

                oDoc.Sections[curSectionNum].Range.Paragraphs[3].Range.Select();
                currentSelection = oWordApplic.Selection;
                MsWord.Table oTable;
                oTable = curRange.Tables.Add(curRange, 5, 3, ref missing, ref missing);
                oTable.Range.ParagraphFormat.Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                oTable.Range.Font.Name = " 宋体";
                oTable.Range.Font.Size = 16;
                oTable.Range.Cells.VerticalAlignment =
                    MsWord.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                oTable.Range.Rows.Alignment     = MsWord.WdRowAlignment.wdAlignRowCenter;
                oTable.Columns[1].Width         = 80;
                oTable.Columns[2].Width         = 180;
                oTable.Columns[3].Width         = 80;
                oTable.Cell(1, 1).Range.Text    = " 字段";
                oTable.Cell(1, 2).Range.Text    = " 描述";
                oTable.Cell(1, 3).Range.Text    = " 数据类型";
                oTable.Cell(2, 1).Range.Text    = "ProductID";
                oTable.Cell(2, 2).Range.Text    = " 产品标识";
                oTable.Cell(2, 3).Range.Text    = " 字符串";
                oTable.Borders.InsideLineStyle  = MsWord.WdLineStyle.wdLineStyleSingle;
                oTable.Borders.OutsideLineStyle = MsWord.WdLineStyle.wdLineStyleSingle;
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                curRange.ParagraphFormat.Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;

                showComment("插入表格,并设置边框格式");

                #endregion 第二章

                Console.WriteLine(" 正在插入第三章内容");
                showComment("正在插入第三章内容");
                #region 第三章图片
                curSectionNum = 5;
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Select();
                curRange         = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                currentSelection = oWordApplic.Selection;
                currentSelection.TypeText("3 图片");
                currentSelection.TypeParagraph();
                currentSelection.TypeText(" 图片示例");
                currentSelection.TypeParagraph();

                currentSelection.InlineShapes.AddPicture(Directory.GetCurrentDirectory() + @"\Files\whu.png",
                                                         ref missing, ref missing, ref missing);
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                curRange.set_Style(ref Style1);
                curRange.ParagraphFormat.Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;

                showComment("完成插入图片,并设置格式");
                #endregion 第三章

                Console.WriteLine("正在插入新的章节");
                showComment("正在插入第四章内容");
                #region 添加新的章节,并添加参考文献部分。
                curSectionNum = 6;
                oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range.Select();
                curRange = oDoc.Sections[curSectionNum].Range.Paragraphs[1].Range;
                currentSelection.TypeText("4 参考文献");
                currentSelection.TypeParagraph();
                currentSelection.TypeText(" 参考文献示例");
                currentSelection.TypeParagraph();


                object note = "参考文献1";
                curRange.InsertCrossReference(MsWord.WdReferenceType.wdRefTypeEndnote, MsWord.WdReferenceKind.wdEndnoteNumber,
                                              note, ref missing, ref missing, ref missing);
                //currentSelection.TypeText("参考文献1");

                showComment("完成添加参考文献");
                #endregion



                Console.WriteLine(" 正在设置第一节摘要页眉内容");
                showComment("正在设置第一节摘要页眉内容");
                //设置页脚 section 1 摘要
                curSectionNum = 1;
                oDoc.Sections[curSectionNum].Range.Select();
                //进入页脚视图
                oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                    MsWord.WdSeekView.wdSeekCurrentPageFooter;
                oDoc.Sections[curSectionNum].
                Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].
                Range.Borders[MsWord.WdBorderType.wdBorderBottom].LineStyle =
                    MsWord.WdLineStyle.wdLineStyleNone;
                oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = true;
                oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle
                    = MsWord.WdPageNumberStyle.wdPageNumberStyleUppercaseRoman;
                oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //切换到文档
                oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                    MsWord.WdSeekView.wdSeekMainDocument;
                Console.WriteLine(" 正在设置第二节目录页眉内容");
                showComment("正在设置第二节目录页眉内容");
                //设置页脚 section 2 目录
                curSectionNum = 2;
                oDoc.Sections[curSectionNum].Range.Select();
                //进入页脚视图
                oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                    MsWord.WdSeekView.wdSeekCurrentPageFooter;
                oDoc.Sections[curSectionNum].
                Headers[MsWord.WdHeaderFooterIndex.wdHeaderFooterPrimary].
                Range.Borders[MsWord.WdBorderType.wdBorderBottom].LineStyle =
                    MsWord.WdLineStyle.wdLineStyleNone;
                oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = false;
                oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle
                    = MsWord.WdPageNumberStyle.wdPageNumberStyleUppercaseRoman;
                //oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //切换到文档
                oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                    MsWord.WdSeekView.wdSeekMainDocument;
                //第一章页眉页码设置
                curSectionNum = 3;
                oDoc.Sections[curSectionNum].Range.Select();
                //切换入页脚视图
                oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                    MsWord.WdSeekView.wdSeekCurrentPageFooter;
                currentSelection = oWordApplic.Selection;
                curRange         = currentSelection.Range;
                //本节页码不续上节
                oWordApplic.Selection.HeaderFooter.PageNumbers.RestartNumberingAtSection = true;
                //页码格式为阿拉伯
                oWordApplic.Selection.HeaderFooter.PageNumbers.NumberStyle
                    = MsWord.WdPageNumberStyle.wdPageNumberStyleArabic;
                //起如页码为 1
                oWordApplic.Selection.HeaderFooter.PageNumbers.StartingNumber = 1;
                //添加页码域
                object fieldpage = MsWord.WdFieldType.wdFieldPage;
                oWordApplic.Selection.Fields.Add(oWordApplic.Selection.Range,
                                                 ref fieldpage, ref missing, ref missing);
                //居中对齐
                oWordApplic.Selection.ParagraphFormat.Alignment =
                    MsWord.WdParagraphAlignment.wdAlignParagraphCenter;
                //本小节不链接到上一节
                oDoc.Sections[curSectionNum].Headers[Microsoft.Office.Interop.
                                                     Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                //切换入正文视图

                oWordApplic.ActiveWindow.ActivePane.View.SeekView =
                    MsWord.WdSeekView.wdSeekMainDocument;
                //在输入全部内容后由于后面章节内容有变动,在此要更新目录,使页码正确
                Console.WriteLine(" 正在更新目录");
                showComment("正在更新目录");
                oDoc.Fields[1].Update();
                #region 保存文档
                //保存文档
                Console.WriteLine(" 正在保存 Word 文档");
                showComment("正在保存word文档");
                object fileName;
                fileName = doc_file_name;
                oDoc.SaveAs2(ref fileName);
                oDoc.Close();
                //Word 文档任务完成后,需要释放 Document 对象和 Application 对象。
                Console.WriteLine("正在释放 COM 资源");
                showComment("正在释放COM资源");

                //oWordApplic.Documents.Open(doc_file_name);

                //释放 COM 资源
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
                oDoc = null;
                oWordApplic.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApplic);
                oWordApplic = null;

                System.GC.Collect();
                #endregion 保存文档
            }//try
            catch (Exception e2)
            {
                MessageBox.Show(e2.Message);
            }
            finally
            {
                Console.WriteLine(" 正在结束 Word 进程");
                showComment("正在结束Word进程");
                //关闭 word 进程
                Process[] AllProces = Process.GetProcesses();
                for (int j = 0; j < AllProces.Length; j++)
                {
                    string theProcName = AllProces[j].ProcessName;
                    if (String.Compare(theProcName, "WINWORD") == 0)
                    {
                        if (AllProces[j].Responding && !AllProces[j].HasExited)
                        {
                            AllProces[j].Kill();
                        }
                    }
                }
                //Close word Process.

                OpenWord(doc_file_name);
            }
        }
Beispiel #34
0
 public WordManipulator(Word.Application wordApplication)
 {
     wordApp = wordApplication;
 }
Beispiel #35
0
        //为图片添加边框
        public void Btn_AddBoarder_Click(object sender, RibbonControlEventArgs e)
        {
            Application wdApp = Globals.ThisAddIn.Application;

            StaticFunction.AddBoadersForInlineshapes(wdApp, pictureParagraphStyle: "图片");
        }
        public static void AutomateWord()
        {
            object missing = Type.Missing;
            object notTrue = false;

            Word.Application oWord    = null;
            Word.Documents   oDocs    = null;
            Word.Document    oDoc     = null;
            Word.Paragraphs  oParas   = null;
            Word.Paragraph   oPara    = null;
            Word.Range       oParaRng = null;
            Word.Font        oFont    = null;

            try
            {
                // Create an instance of Microsoft Word and make it invisible.

                oWord         = new Word.Application();
                oWord.Visible = false;
                Console.WriteLine("Word.Application is started");

                // Create a new Document.

                oDocs = oWord.Documents;
                oDoc  = oDocs.Add(ref missing, ref missing, ref missing, ref missing);
                Console.WriteLine("A new document is created");

                // Insert a paragraph.

                Console.WriteLine("Insert a paragraph");

                oParas        = oDoc.Paragraphs;
                oPara         = oParas.Add(ref missing);
                oParaRng      = oPara.Range;
                oParaRng.Text = "Heading 1";
                oFont         = oParaRng.Font;
                oFont.Bold    = 1;
                oParaRng.InsertParagraphAfter();

                // Save the document as a docx file and close it.

                Console.WriteLine("Save and close the document");

                object fileName = Path.GetDirectoryName(
                    Assembly.GetExecutingAssembly().Location) + "\\Sample1.docx";
                object fileFormat = Word.WdSaveFormat.wdFormatXMLDocument;
                oDoc.SaveAs(ref fileName, ref fileFormat, 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);
                ((Word._Document)oDoc).Close(ref missing, ref missing,
                                             ref missing);

                // Quit the Word application.

                Console.WriteLine("Quit the Word application");
                ((Word._Application)oWord).Quit(ref notTrue, ref missing,
                                                ref missing);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Solution1.AutomateWord throws the error: {0}",
                                  ex.Message);
            }
            finally
            {
                // Clean up the unmanaged Word COM resources by explicitly
                // calling Marshal.FinalReleaseComObject on all accessor objects.
                // See http://support.microsoft.com/kb/317109.

                if (oFont != null)
                {
                    Marshal.FinalReleaseComObject(oFont);
                    oFont = null;
                }
                if (oParaRng != null)
                {
                    Marshal.FinalReleaseComObject(oParaRng);
                    oParaRng = null;
                }
                if (oPara != null)
                {
                    Marshal.FinalReleaseComObject(oPara);
                    oPara = null;
                }
                if (oParas != null)
                {
                    Marshal.FinalReleaseComObject(oParas);
                    oParas = null;
                }
                if (oDoc != null)
                {
                    Marshal.FinalReleaseComObject(oDoc);
                    oDoc = null;
                }
                if (oDocs != null)
                {
                    Marshal.FinalReleaseComObject(oDocs);
                    oDocs = null;
                }
                if (oWord != null)
                {
                    Marshal.FinalReleaseComObject(oWord);
                    oWord = null;
                }
            }
        }
Beispiel #37
0
        public void Document_Create(Document_Type type, Document_format format, string name, DataTable table)
        {
            Configuration_Class configuration_Class = new Configuration_Class();

            configuration_Class.Document_configuration_Get();
            switch (name != "" || name != null)
            {
            case true:
                switch (format)
                {
                case Document_format.Word:
                    word.Application application = new word.Application();
                    word.Document    document    = application.Documents.Add(Visible: true);
                    try
                    {
                        word.Range range = document.Range(0, 0);
                        document.Sections.PageSetup.LeftMargin  = application.CentimetersToPoints((float)Configuration_Class.doc_Left_Merge);
                        document.Sections.PageSetup.TopMargin   = application.CentimetersToPoints((float)Configuration_Class.doc_Top_Merge);
                        document.Sections.PageSetup.RightMargin = application.CentimetersToPoints((float)Configuration_Class.doc_Right_Merge);
                        range.Text = Configuration_Class.Organization_Name;
                        //Выравнивание
                        range.ParagraphFormat.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        //Интревал
                        range.ParagraphFormat.SpaceAfter      = 1;
                        range.ParagraphFormat.SpaceBefore     = 1;
                        range.ParagraphFormat.LineSpacingRule = word.WdLineSpacing.wdLineSpaceSingle;
                        range.Font.Name = "Times New Roman";
                        range.Font.Size = 12;
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        word.Paragraph Document_Name = document.Paragraphs.Add();
                        Document_Name.Format.Alignment = word.WdParagraphAlignment.wdAlignParagraphCenter;
                        Document_Name.Range.Font.Name  = "Times New Roman";
                        Document_Name.Range.Font.Size  = 16;



                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        word.Paragraph statparg = document.Paragraphs.Add();
                        //Создание области таблицы в документе
                        word.Table stat_table
                        //ие таблицы в области документа
                        //указывается  параграф в котором документ создан
                        //Количество строк и столбцов
                            = document.Tables.Add(statparg.Range, table.Rows.Count, table.Columns.Count);
                        //Настройка границ таблицы внутренние
                        stat_table.Borders.InsideLineStyle = word.WdLineStyle.wdLineStyleSingle;
                        //Настройка границ таблицы внешние
                        stat_table.Borders.OutsideLineStyle = word.WdLineStyle.wdLineStyleSingle;
                        //Выравнивание текста внутри ячеек по ширине
                        stat_table.Rows.Alignment = word.WdRowAlignment.wdAlignRowCenter;
                        //Выравнивание текста внутри ячеек по высоте
                        stat_table.Range.Cells.VerticalAlignment = word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                        stat_table.Range.Font.Size = 11;
                        stat_table.Range.Font.Name = "Times New Romman";
                        //Индексикация столбцов и строк в Word начинается с 1,1
                        for (int row = 1; row <= table.Rows.Count; row++)
                        {
                            for (int col = 1; col <= table.Columns.Count; col++)
                            {
                                stat_table.Cell(row, col).Range.Text = table.Rows[row - 1][col - 1].ToString();
                            }
                        }
                        document.Paragraphs.Add();
                        document.Paragraphs.Add();
                        //Параграф с фиксацией даты слздания документа
                        word.Paragraph Footparg = document.Paragraphs.Add();
                        Footparg.Range.Text = string.Format("Дата создания \t\t\t{0}", DateTime.Now.ToString("dd.MM.yyyy"));
                    }
                    catch
                    {
                    }
                    finally
                    {
                        switch (format)
                        {
                        case Document_format.Word:
                            //Сохранение документа с названием из метода и формата doc
                            document.SaveAs2(name, word.WdSaveFormat.wdFormatDocument);
                            break;

                        case Document_format.PDF:
                            //Сохранение документа в формате PDF
                            document.SaveAs2(name, word.WdSaveFormat.wdFormatPDF);
                            break;
                        }
                        //Закрываем документ
                        document.Close();
                        //Выходим из процесса с его закрытием
                        application.Quit();
                    }
                    break;

                case Document_format.Excel:
                    //Создание процесса Excel
                    excel.Application application_ex = new excel.Application();
                    //Создание книги
                    excel.Workbook workbook = application_ex.Workbooks.Add();
                    //Создание страницы
                    excel.Worksheet worksheet = (excel.Worksheet)workbook.ActiveSheet;
                    try
                    {
                        switch (type)
                        {
                        case Document_Type.Report:
                            //Название страницы
                            worksheet.Name = "Отчёт";
                            for (int row = 0; row < table.Rows.Count; row++)
                            {
                                for (int col = 0; col < table.Columns.Count; col++)
                                {
                                    worksheet.Cells[row + 1][col + 1] = table.Rows[row][col].ToString();
                                    //Указание диапазона работы с ячееками листа
                                    excel.Range border
                                    //Начало диапазона
                                        = worksheet.Range[worksheet.Cells[1, 1],
                                                          //Динамический конец диапазона в зависимости от выходимых данных
                                                          worksheet.Cells[table.Rows.Count + 1]
                                                          [table.Columns.Count + 1]];
                                    //Стиль линий границ ячеек
                                    border.Borders.LineStyle = excel.XlLineStyle.xlContinuous;
                                    //Выравнивание во высоте
                                    border.VerticalAlignment = excel.XlHAlign.xlHAlignCenter;
                                    //Выравнивание по ширине
                                    border.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter;
                                    //Внесение даты создания документа
                                    worksheet.Cells[table.Rows.Count + 3][2] = string.Format("Дата создания {0}", DateTime.Now.ToString());
                                    //Объединение ячеек
                                    worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 2]].Merge();
                                }
                            }
                            break;

                        case Document_Type.Statistic:
                            worksheet.Name = "Статический отчёт";
                            for (int row = 0; row < table.Rows.Count; row++)
                            {
                                for (int col = 0; col < table.Columns.Count; col++)
                                {
                                    worksheet.Cells[row + 1][col + 1] = table.Rows[row][col].ToString();
                                }
                            }
                            excel.Range border1 = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1][table.Columns.Count + 1]];
                            border1.Borders.LineStyle   = excel.XlLineStyle.xlContinuous;
                            border1.VerticalAlignment   = excel.XlHAlign.xlHAlignCenter;
                            border1.HorizontalAlignment = excel.XlHAlign.xlHAlignCenter;
                            worksheet.Cells[table.Rows.Count + 3][2] = string.Format("Дата создания {0}", DateTime.Now.ToString());
                            worksheet.Range[worksheet.Cells[table.Rows.Count + 3, 2], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 2]].Merge();
                            //Класс области графики
                            excel.ChartObjects chartObjects = (excel.ChartObjects)worksheet.ChartObjects(Type.Missing);
                            //Область размещения графиков: отступы слева сверху, размер ширина и высота
                            excel.ChartObject chartObject = chartObjects.Add(300, 50, 250, 250);
                            //Объявление области графики
                            excel.Chart chart = chartObject.Chart;
                            //Объявление коллекции построений графиков
                            excel.SeriesCollection seriesCollection = (excel.SeriesCollection)chart.SeriesCollection(Type.Missing);
                            //Объявление построения графиков
                            excel.Series series = seriesCollection.NewSeries();
                            //Тип графика
                            chart.ChartType = excel.XlChartType.xl3DColumn;
                            //Диапазон значений по оси Х
                            series.XValues = worksheet.get_Range("B2", "B" + table.Rows.Count + 1);
                            //Диапазон значений по оси У
                            series.Values = worksheet.get_Range("C2", "C" + table.Rows.Count + 1);
                            break;
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        //Сохранение книги
                        worksheet.SaveAs(name, application_ex.DefaultSaveFormat);
                        //Закрытие книги
                        workbook.Close();
                        //Завершение процесса
                        application_ex.Quit();
                    }
                    break;
                }
                break;

            case false:
                System.Windows.Forms.MessageBox.Show("Введите название документа");
                break;
            }
        }
Beispiel #38
0
        object objEndOfDocFlag        = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

        public ReportWord()
        {
            wordDoc = new Word.Document();
            wordApp = new Word.Application();
        }
Beispiel #39
0
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Application myword = new Word.Application(); //Создаем объект объекта
            myword.Visible = true;
            Word.Document  objdoc = myword.Documents.Add();
            Word.Paragraph str;
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = "МИНИСТЕРСТВО НАУКИ И ВЫСШЕГО ОБРАЗОВАНИЯ" +
                             "   РОССИЙСКОЙ ФЕДЕРАЦИИ";
            str = objdoc.Paragraphs.Add();
            process(str);
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = "ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ" +
                             " «ОРЛОВСКИЙ ГОСУДАРСТВЕННЫЙ УНИВЕРСИТЕТ";
            str = objdoc.Paragraphs.Add();
            process(str);
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = " ИМЕНИ И.С. ТУРГЕНЕВА»";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str = objdoc.Paragraphs.Add();
            string mctext = textBox1.Text;

            str.Range.Text = $"\nКафедра {mctext}";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = "\n\n\nОТЧЕТ";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str.Range.Bold = 2;
            str            = objdoc.Paragraphs.Add();
            mctext         = textBox2.Text;
            str.Range.Text = $"По лабораторной работе №{mctext}";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str            = objdoc.Paragraphs.Add();
            mctext         = textBox3.Text;
            str.Range.Text = $"на тему: «{mctext}»";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str            = objdoc.Paragraphs.Add();
            mctext         = textBox4.Text;
            str.Range.Text = $"по дисциплине: «{mctext}»";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str            = objdoc.Paragraphs.Add();
            mctext         = textBox8.Text;
            str.Range.Text = $"\n\n\n\nВыполнил(а/и): {mctext}";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = "Институт приборостроения, автоматизации и информационных технологий" +
                             " Направление: 09.03.04 «Программная инженерия»";
            str = objdoc.Paragraphs.Add();
            process(str);
            str.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            str            = objdoc.Paragraphs.Add();
            mctext         = textBox7.Text;
            str.Range.Text = $"Группа: {mctext}";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            mctext         = textBox5.Text;
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = $"Проверил: {mctext}";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            str            = objdoc.Paragraphs.Add();
            mctext         = textBox6.Text;
            str.Range.Text = $"\nОтметка о зачете:                                    Дата: «____» __________ {mctext} г.";
            str            = objdoc.Paragraphs.Add();
            process(str);
            str.Alignment  = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            str            = objdoc.Paragraphs.Add();
            str.Range.Text = $"\n\n\n\n\nОрел, {mctext}";
            str            = objdoc.Paragraphs.Add();
            process(str);
        }
Beispiel #40
0
 /// <summary>
 /// The formatter needs an application (or more precisely its active document) to format, and a colorizer, to determine what colors to use for the formatting. These references must be initialized before any real work can be done.
 /// </summary>
 /// <param name="colorizer_"></param>
 /// <param name="application_"></param>
 public void Initialize(Colorizer colorizer_, Word.Application application_)
 {
     colorizer = colorizer_;
     wordApp   = application_;
 }
Beispiel #41
0
        static void Key_Greek(Word.Application app, Keys modifer, Keys key)
        {
            switch (key)
            {
            case Keys k when k >= Keys.A && k <= Keys.Z:
            {
                int  cap = (modifer.HasFlag(Keys.Shift) ? 1 : 0) ^ (Console.CapsLock ? 1 : 0); // 大小写
                int  id  = (int)key - (int)Keys.A;                                             // 字母键
                char ch  = (char)(id + (cap == 1 ? 'A' : 'a'));                                // 字母

                if (modifer.HasFlag((int)Keys.Alt + Keys.Control))
                {
                    app.Selection.TypeText("\\fraktur" + ch);         // 哥特体
                }
                else if (modifer.HasFlag(Keys.Control))
                {
                    app.Selection.TypeText("\\double" + ch);         // 双线体
                }
                else if (modifer.HasFlag(Keys.Alt))
                {
                    app.Selection.TypeText("\\script" + ch);         // 手写体
                }
                else
                {
                    // 希腊字母
                    string[] map  = @"alpha beta chi delta epsilon phi gamma eta iota ? kappa lambda mu nu ? pi theta rho sigma tau upsilon ? omega xi psi zeta".Split();
                    string   type = map[id];
                    switch (key)
                    {
                    case Keys.J: type = cap == 0 ? "varphi" : "vartheta"; break;

                    case Keys.O: type = cap == 0 ? "varrho" : "varsigma"; break;

                    case Keys.V: type = cap == 0 ? "varepsilon" : "varpi"; break;

                    default: if (cap == 1)
                        {
                            type = type.Substring(0, 1).ToUpper() + type.Substring(1);
                        }
                        break;                                                                                           // 转大写
                    }
                    app.Selection.TypeText("\\" + type);
                }
                break;
            }

            case Keys.Left: app.Selection.TypeText(modifer == Keys.None ? "\\leftarrow" : "\\Leftarrow"); break;

            case Keys.Right: app.Selection.TypeText(modifer == Keys.None ? "\\rightarrow" : "\\Rightarrow"); break;

            case Keys.Up: app.Selection.TypeText(modifer == Keys.None ? "\\uparrow" : "\\Uparrow"); break;

            case Keys.Down: app.Selection.TypeText(modifer == Keys.None ? "\\downarrow" : "\\Downarrow"); break;

            case Keys.D1: app.Selection.TypeText("\\nearrow"); break;

            case Keys.D2: app.Selection.TypeText("\\nwarrow"); break;

            case Keys.D3: app.Selection.TypeText("\\searrow"); break;

            case Keys.D4: app.Selection.TypeText("\\swarrow"); break;

            case Keys.OemMinus:
                app.Selection.TypeText(modifer == Keys.None ? "\\leftrightarrow" : "\\Leftrightarrow"); break;

            case Keys.OemPipe:
                app.Selection.TypeText(modifer == Keys.None ? "\\updownarrow" : "\\Updownarrow"); break;
            }
        }
        private void CreateDocument()
        {
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.DefaultExt       = ".docx";
                saveFileDialog1.Filter           = "Documents|*.docx";
                saveFileDialog1.AddExtension     = true;
                saveFileDialog1.InitialDirectory = @"C:\Desktop";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    object filename = saveFileDialog1.FileName;
                    Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();
                    winword.ShowAnimation = false;
                    winword.Visible       = false;
                    object missing = System.Reflection.Missing.Value;
                    Microsoft.Office.Interop.Word.Document document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                    Paragraph para1         = document.Content.Paragraphs.Add(ref missing);
                    object    styleHeading1 = "Heading 1";
                    para1.Range.set_Style(ref styleHeading1);
                    para1.Range.Text = "Students List";
                    para1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                    para1.Range.InsertParagraphAfter();
                    para1.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
                    para1.Range.Text = "\r\n Class: 19110CLA2 \r\n Windows Programming";
                    para1.Range.InsertParagraphAfter();
                    int rows    = printGrid.Rows.Count + 1;
                    int columns = printGrid.Columns.Count;

                    Table T = document.Tables.Add(para1.Range, rows, columns, ref missing, ref missing);
                    T.Borders.Enable = 1;

                    for (int i = 1; i < T.Rows.Count; i++)
                    {
                        for (int j = 1; j < T.Columns.Count + 1; j++)
                        {
                            //Header
                            T.Rows[1].Cells[j].Range.Text      = printGrid.Columns[j - 1].HeaderText.ToString();
                            T.Rows[1].Cells[j].Range.Font.Bold = 1;
                            T.Rows[1].Cells[j].Range.Font.Name = "verdana";
                            T.Rows[1].Cells[j].Range.Font.Size = 10;
                            T.Rows[1].Cells[j].Shading.BackgroundPatternColor = WdColor.wdColorGray25;
                            T.Rows[1].Cells[j].VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
                            T.Rows[1].Cells[j].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
                            //Data
                            T.Rows[i + 1].Cells[j].Range.Text = printGrid.Rows[i - 1].Cells[j - 1].Value.ToString();
                            if (j == 8)
                            {
                                Image sparePicture = ByteArrayToImage((byte[])printGrid.Rows[i - 1].Cells[7].Value);
                                Clipboard.SetDataObject(sparePicture);
                                T.Rows[i + 1].Cells[j].Range.Paste();
                            }
                        }
                    }
                    Clipboard.Clear();
                    document.SaveAs2(ref filename);
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                    winword.Quit(ref missing, ref missing, ref missing);
                    winword = null;
                    MessageBox.Show("Document created successfully !");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Beispiel #43
0
        //设置超链接
        public void Button1_Click(object sender, RibbonControlEventArgs e)
        {
            Application wdApp = Globals.ThisAddIn.Application;

            StaticFunction.SetHyperLink(wdApp);
        }
Beispiel #44
0
        private void send_doc()
        {
            var Lastname       = output_lastname.Text;
            var Patronymic     = output_patronymic.Text;
            var name           = output_name.Text;
            var inn            = output_TIN.Text;
            var PassportNumber = output_passportNumber.Text;
            var PassportSeria  = output_passportSeria.Text;
            var Address        = output_address.Text;


            var wordAPP = new Word.Application();

            wordAPP.Visible = false;
            if (output_isBudged.Checked == true)
            {
                try
                {
                    var wordDocument = wordAPP.Documents.Open(templatefilename2);
                    wordDocument.SaveAs(@"D:\отчеты\D_nayma_zhilogo_pom.docx");
                    //wordAPP.Documents.Close();

                    var wordDocument1 = wordAPP.Documents.Open(templatefilename1);
                    for (int i = 0; i < 5; i++)
                    {
                        ReplaceWordStup("{lastname}", Lastname, wordDocument);
                        ReplaceWordStup("{name}", name, wordDocument);
                        ReplaceWordStup("{Patronymic}", Patronymic, wordDocument);
                        ReplaceWordStup("{PassportNumber}", PassportNumber, wordDocument);
                        ReplaceWordStup("{PassportSeria}", PassportSeria, wordDocument);
                        ReplaceWordStup("{Address}", Address, wordDocument);
                        ReplaceWordStup("{inn}", inn, wordDocument);
                        ReplaceWordStup("{lastname}", Lastname, wordDocument);
                        ReplaceWordStup("{name}", name, wordDocument);
                        ReplaceWordStup("{Patronymic}", Patronymic, wordDocument);


                        ReplaceWordStup("{lastname}", Lastname, wordDocument1);
                        ReplaceWordStup("{name}", name, wordDocument1);
                        ReplaceWordStup("{Patronymic}", Patronymic, wordDocument1);
                        ReplaceWordStup("{PassportNumber}", PassportNumber, wordDocument1);
                        ReplaceWordStup("{PassportSeria}", PassportSeria, wordDocument1);
                        ReplaceWordStup("{Address}", Address, wordDocument1);
                        ReplaceWordStup("{inn}", inn, wordDocument1);
                        ReplaceWordStup("{lastname}", Lastname, wordDocument1);
                        ReplaceWordStup("{name}", name, wordDocument1);
                        ReplaceWordStup("{Patronymic}", Patronymic, wordDocument1);
                    }
                    wordDocument1.SaveAs(@"D:\отчеты\budjet_doc.docx");
                    wordDocument.Close();
                    wordDocument1.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Console.WriteLine("end");
                }
            }
            else
            {
                try
                {
                    var wordDocument = wordAPP.Documents.Open(templatefilename3);
                    ReplaceWordStup("{lastname}", Lastname, wordDocument);
                    ReplaceWordStup("{name}", name, wordDocument);
                    ReplaceWordStup("{Patronymic}", Patronymic, wordDocument);
                    ReplaceWordStup("{PassportNumber}", PassportNumber, wordDocument);
                    ReplaceWordStup("{PassportSeria}", PassportSeria, wordDocument);
                    ReplaceWordStup("{Address}", Address, wordDocument);
                    ReplaceWordStup("{inn}", inn, wordDocument);
                    ReplaceWordStup("{lastname}", Lastname, wordDocument);
                    ReplaceWordStup("{name}", name, wordDocument);
                    ReplaceWordStup("{Patronymic}", Patronymic, wordDocument);

                    wordDocument.SaveAs(@"D:\отчеты\kontract_doc.docx");
                    //wordAPP.Documents.Close();

                    var wordDocument1 = wordAPP.Documents.Open(templatefilename1);
                    for (int i = 0; i < 5; i++)
                    {
                        ReplaceWordStup("{lastname}", Lastname, wordDocument1);
                        ReplaceWordStup("{name}", name, wordDocument1);
                        ReplaceWordStup("{Patronymic}", Patronymic, wordDocument1);
                        ReplaceWordStup("{PassportNumber}", PassportNumber, wordDocument1);
                        ReplaceWordStup("{PassportSeria}", PassportSeria, wordDocument1);
                        ReplaceWordStup("{Address}", Address, wordDocument1);
                        ReplaceWordStup("{inn}", inn, wordDocument1);
                        ReplaceWordStup("{lastname}", Lastname, wordDocument1);
                        ReplaceWordStup("{name}", name, wordDocument1);
                        ReplaceWordStup("{Patronymic}", Patronymic, wordDocument1);
                    }
                    wordDocument1.SaveAs(@"D:\отчеты\D_o_vozmeshtenie_zatrat_za_kom_uslugi.docx");
                    wordDocument.Close();
                    wordDocument1.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    Console.WriteLine("end");
                }
            }
            MessageBox.Show("Документ сформирован");
        }
Beispiel #45
0
        //清理文本格式
        public void Button_ClearTextFormat_Click(object sender, RibbonControlEventArgs e)
        {
            Application wdApp = Globals.ThisAddIn.Application;

            StaticFunction.ClearTextFormat(wdApp, pictureParagraphStyle: "图片");
        }
        private WordTest LoadWordDocument(string openDialogFilePath)
        {
            word = new Microsoft.Office.Interop.Word.Application();
            doc  = new Document();

            object fileName = openDialogFilePath;
            // Пустой объект для ненужных параметров
            object missing = System.Type.Missing;

            try
            {
                // Открытие документа
                doc = word.Documents.Open(ref fileName,
                                          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);
            }
            catch (Exception ex)
            {
                MessageService.ShowError("Ошибка при загрузке документа: " + ex.Message);
                this.Dispatcher.Invoke(() => { spinnerIcon.Visibility = Visibility.Hidden; });
                return(null);
            }
            WordTest wordTest = new WordTest();                                 // Создаем тест

            wordTest.TestName = doc.Paragraphs[1].Range.Text.Replace("\r", ""); // Первый параграф - имя теста

            // Парсим время на прохождение теста из второго параграфа
            Regex timeRegular = new Regex("[0-9]{2}:[0-9]{2}:[0-9]{2}");

            string[] wordTime = timeRegular.Match(doc.Paragraphs[2].Range.Text).Value.Split(':');


            int testTimeInSeconds;

            // Если получилось спарсить то грузим вопрос и варианты ответа
            if (wordTime.Length != 0)
            {
                // Переводим время в секунды
                testTimeInSeconds = CalcService.HoursToSeconds(int.Parse(wordTime[0])) +
                                    CalcService.MinutesToSeconds(int.Parse(wordTime[1])) +
                                    int.Parse(wordTime[2]);
                wordTest.TestPassTime = testTimeInSeconds;

                wordTest.TestQuestions = new ObservableCollection <WordQuestions>();
                for (int i = 1; i <= doc.Lists[1].ListParagraphs.Count; i++)
                {
                    WordQuestions question = new WordQuestions()
                    {
                        QuestionText = doc.Lists[1].ListParagraphs[i].Range.Text.Replace("\r", "")
                    };
                    question.OptionsList = new ObservableCollection <string>(doc.Lists[i + 1].Range.Text.Split('\r').Where(x => !String.IsNullOrWhiteSpace(x)).ToList());
                    wordTest.TestQuestions.Add(question);
                }
            }

            ((_Document)doc).Close();
            ((_Application)word).Quit();
            return(wordTest);
        }
Beispiel #47
0
        /// <summary>
        /// 将多个段落转换为一个段落
        /// </summary>
        /// <remarks>比如将从PDF中粘贴过来的多段文字转换为一个段落。具体操作为:将选择区域的文字中的换行符转换为空格</remarks>
        public void buttonPdfReformat_Click(object sender, RibbonControlEventArgs e)
        {
            Application wdApp = Globals.ThisAddIn.Application;

            StaticFunction.PdfReformat(wdApp);
        }
Beispiel #48
0
        private void createDoc()
        {
            //Create an instance for word app
            Microsoft.Office.Interop.Word.Application winword = new Microsoft.Office.Interop.Word.Application();

            //Set animation status for word application
            winword.ShowAnimation = false;

            //Set status for word application is to be visible or not.
            winword.Visible = false;

            //Create a missing variable for missing value
            object missing = System.Reflection.Missing.Value;

            //Create a new document
            Microsoft.Office.Interop.Word.Document document =
                winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);


            //Add the footers into the document
            foreach (Microsoft.Office.Interop.Word.Section wordSection in document.Sections)
            {
                //Get the footer range and add the footer details.
                Microsoft.Office.Interop.Word.Range footerRange = wordSection
                                                                  .Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex           = Microsoft.Office.Interop.Word.WdColorIndex.wdBlack;
                footerRange.Font.Size                 = 10;
                footerRange.ParagraphFormat.Alignment =
                    Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                footerRange.Text = DateTime.Today.ToLongDateString();
            }

            //adding text to document
            document.Content.SetRange(0, 0);
            document.Content.Text = "This is test document " + Environment.NewLine;

            //Add paragraph with Heading 1 style
            Microsoft.Office.Interop.Word.Paragraph para1 = document.Content.Paragraphs.Add(ref missing);
            object styleHeading1 = "Heading 1";

            para1.Range.set_Style(ref styleHeading1);
            para1.Range.Text = "Executive Summary";
            para1.Range.InsertParagraphAfter();

            //Add 1.1
            Microsoft.Office.Interop.Word.Paragraph para2 = document.Content.Paragraphs.Add(ref missing);
            para2.Range.Text = form1.getText(1) + Environment.NewLine;
            ;
            para2.Range.InsertParagraphAfter();

            //Add Chart 1.1
            Microsoft.Office.Interop.Word.Paragraph para3 = document.Content.Paragraphs.Add(ref missing);
            InlineShape pic =
                para3.Range.InlineShapes.AddPicture(
                    "C:\\Users\\admin\\Source\\Repos\\BusinessPlanWriter\\BPWChartImages\\1.1.png");

            //Add 1.2 Header
            Microsoft.Office.Interop.Word.Paragraph para4 = document.Content.Paragraphs.Add(ref missing);
            para4.Range.set_Style(ref styleHeading1);
            para4.Range.Text = "Objectives";
            para4.Range.InsertParagraphAfter();

            //Add 1.2
            Microsoft.Office.Interop.Word.Paragraph para5 = document.Content.Paragraphs.Add(ref missing);
            para5.Range.Text = form1.getText(2) + Environment.NewLine;
            ;
            para5.Range.InsertParagraphAfter();

            //Add Chart 1.2
            try
            {
                Microsoft.Office.Interop.Word.Paragraph para6 = document.Content.Paragraphs.Add(ref missing);
                pic = para6.Range.InlineShapes.AddPicture(
                    "C:\\Users\\admin\\Source\\Repos\\BusinessPlanWriter\\BPWChartImages\\1.2.png");
            }
            catch
            {
            }

            //Add 1.3 Header
            Microsoft.Office.Interop.Word.Paragraph para7 = document.Content.Paragraphs.Add(ref missing);
            para7.Range.set_Style(ref styleHeading1);
            para7.Range.Text = "Mission";
            para7.Range.InsertParagraphAfter();

            //Add 1.3
            Microsoft.Office.Interop.Word.Paragraph para8 = document.Content.Paragraphs.Add(ref missing);
            para8.Range.Text = form1.getText(3) + Environment.NewLine;
            ;
            para8.Range.InsertParagraphAfter();

            //Add Chart 1.3
            try
            {
                Microsoft.Office.Interop.Word.Paragraph para9 = document.Content.Paragraphs.Add(ref missing);
                pic = para9.Range.InlineShapes.AddPicture(
                    "C:\\Users\\admin\\Source\\Repos\\BusinessPlanWriter\\BPWChartImages\\1.3.png");
            }
            catch
            {
            }

            //Add 1.4 Header
            Microsoft.Office.Interop.Word.Paragraph para10 = document.Content.Paragraphs.Add(ref missing);
            para10.Range.set_Style(ref styleHeading1);
            para10.Range.Text = "Keys to Success";
            para10.Range.InsertParagraphAfter();

            //Add 1.4
            Microsoft.Office.Interop.Word.Paragraph para11 = document.Content.Paragraphs.Add(ref missing);
            para11.Range.Text = form1.getText(4) + Environment.NewLine;
            ;
            para11.Range.InsertParagraphAfter();

            //Add Chart 1.4
            try
            {
                Microsoft.Office.Interop.Word.Paragraph para12 = document.Content.Paragraphs.Add(ref missing);
                pic = para12.Range.InlineShapes.AddPicture(
                    "C:\\Users\\admin\\Source\\Repos\\BusinessPlanWriter\\BPWChartImages\\1.3.png");
            }
            catch
            {
            }

            //Page break
            Microsoft.Office.Interop.Word.Paragraph para13 = document.Content.Paragraphs.Add(ref missing);
            para13.Range.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak);

            copySheetToClipboard();

            try
            {
                Microsoft.Office.Interop.Word.Paragraph para14 = document.Content.Paragraphs.Add(ref missing);
                pic = para14.Range.InlineShapes.AddPicture(
                    "C:\\Users\\admin\\Source\\Repos\\BusinessPlanWriter\\BPWChartImages\\CashFlow.bmp");
            }
            catch
            {
                MessageBox.Show("Could not import Cash Flow to Word");
            }



            //Save the document
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Word|*.doc;*.docx|PDF|*.pdf";
            saveFileDialog.Title  = "Export Business Plan";
            saveFileDialog.ShowDialog();

            object filename = saveFileDialog.FileName;

            document.SaveAs2(ref filename);
            document.Close(ref missing, ref missing, ref missing);
            document = null;
            winword.Quit(ref missing, ref missing, ref missing);
            winword = null;
            MessageBox.Show("Document created successfully !");
        }
Beispiel #49
0
 private void Ribbon_eZwd_Load(Object sender, RibbonUIEventArgs e)
 {
     _app = Globals.ThisAddIn.Application;
     _app.DocumentChange += AppOnDocumentChange;
 }
        /// <summary>
        /// 將可簡單列舉的報表匯出成 MS Word 檔
        /// </summary>
        /// <param name="rpt"></param>
        /// <returns></returns>
        public static bool ExportMSWordReport(IEnumerable <Model.IReport> rpt)
        {
            #region rawversion
            //Word.Application wdApp = null;
            //try
            //{
            //    wdApp = new Word.Application();
            //    wdApp.Visible = true;
            //    Word.Document doc = wdApp.Documents.Add();
            //    Word.Range rng;
            //    foreach (Model.IReport item in rpt)
            //    {
            //        rng = doc.Paragraphs.Add().Range;
            //        rng.InsertAfter(item.Title);
            //        rng.Font.Size = 14;
            //        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //        foreach (Model.IRptOutput output in item.Contents)
            //        {
            //            rng.InsertParagraphAfter();
            //            rng = doc.Paragraphs[doc.Paragraphs.Count].Range;
            //            rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //            rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            //            rng.Font.Size = 10;
            //            if (output.OutputInByteArr == null) { continue; }
            //            switch (output.OType)
            //            {
            //                case Dashboard.Model.MtbOType.GRAPH:
            //                    Image img = Tool.BinaryToImage(output.OutputInByteArr);
            //                    System.Windows.Clipboard.SetDataObject(img);
            //                    rng.Paste();
            //                    var shape = rng.InlineShapes[rng.InlineShapes.Count];
            //                    shape.Width = doc.PageSetup.PageWidth * 0.7f;
            //                    break;
            //                case Dashboard.Model.MtbOType.PARAGRAPH:

            //                    rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            //                    rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
            //                    rng.ParagraphFormat.LineSpacing = 12f;
            //                    rng.InsertAfter(System.Text.Encoding.UTF8.GetString(output.OutputInByteArr));
            //                    break;
            //                case Dashboard.Model.MtbOType.TABLE:
            //                    DataTable dt = Tool.BinaryToDataTable(output.OutputInByteArr);
            //                    Word.Table tbl = CreateWordTableWithDataTable(dt, rng);
            //                    break;
            //                case Dashboard.Model.MtbOType.TITLE:
            //                    break;
            //                default:
            //                    break;
            //            }
            //        }


            //    }
            //}
            //catch (Exception ex)
            //{
            //    System.Windows.MessageBox.Show( ex.HResult.ToString() + "-" +ex.Message,"", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            //    return false;
            //}
            //return true;
            #endregion

            #region revised version
            //Word.Application wdApp = null;
            //try
            //{
            //    wdApp = new Word.Application();
            //    wdApp.Visible = true;
            //    Word.Document doc = wdApp.Documents.Add();
            //    Word.Range rng;
            //    if (rpt.ElementAt(0) is Model.IOxyReport)
            //    {
            //        foreach (Model.IOxyReport item in rpt)
            //        {
            //            rng = doc.Paragraphs.Add().Range;
            //            //rng.InsertAfter(item.Title);
            //            rng.Font.Size = 14;
            //            rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //            foreach (Model.IOxyRptOutput output in item.OxyContents)
            //            {
            //                rng.InsertParagraphAfter();
            //                rng = doc.Paragraphs[doc.Paragraphs.Count].Range;
            //                rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //                rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            //                rng.Font.Size = 10;
            //                if (output.OutputInByteArr == null) { continue; }
            //                switch (output.OxyOType)
            //                {
            //                    case Dashboard.Model.OxyOType.GRAPH:
            //                        Image img = Tool.BinaryToImage(output.OutputInByteArr);
            //                        System.Windows.Clipboard.SetDataObject(img);
            //                        rng.Paste();
            //                        var shape = rng.InlineShapes[rng.InlineShapes.Count];
            //                        shape.Width = doc.PageSetup.PageWidth * 0.7f;
            //                        break;
            //                    case Dashboard.Model.OxyOType.TABLE:
            //                        DataTable dt = Tool.BinaryToDataTable(output.OutputInByteArr);
            //                        Word.Table tbl = CreateWordTableWithDataTable(dt, rng);
            //                        break;
            //                    default:
            //                        break;
            //                }
            //            }
            //        }
            //    }
            //    else //here is the original code for Mtb
            //    {
            //        foreach (Model.IReport item in rpt)
            //        {
            //            rng = doc.Paragraphs.Add().Range;
            //            rng.InsertAfter(item.Title);
            //            rng.Font.Size = 14;
            //            rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //            foreach (Model.IRptOutput output in item.Contents)
            //            {
            //                rng.InsertParagraphAfter();
            //                rng = doc.Paragraphs[doc.Paragraphs.Count].Range;
            //                rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
            //                rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
            //                rng.Font.Size = 10;
            //                if (output.OutputInByteArr == null) { continue; }
            //                switch (output.OType)
            //                {
            //                    case Dashboard.Model.MtbOType.GRAPH:
            //                        Image img = Tool.BinaryToImage(output.OutputInByteArr);
            //                        System.Windows.Clipboard.SetDataObject(img);
            //                        rng.Paste();
            //                        var shape = rng.InlineShapes[rng.InlineShapes.Count];
            //                        shape.Width = doc.PageSetup.PageWidth * 0.7f;
            //                        break;
            //                    case Dashboard.Model.MtbOType.PARAGRAPH:

            //                        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
            //                        rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
            //                        rng.ParagraphFormat.LineSpacing = 12f;
            //                        rng.InsertAfter(System.Text.Encoding.UTF8.GetString(output.OutputInByteArr));
            //                        break;
            //                    case Dashboard.Model.MtbOType.TABLE:
            //                        DataTable dt = Tool.BinaryToDataTable(output.OutputInByteArr);
            //                        Word.Table tbl = CreateWordTableWithDataTable(dt, rng);
            //                        break;
            //                    case Dashboard.Model.MtbOType.TITLE:
            //                        break;
            //                    default:
            //                        break;
            //                }
            //            }
            //        }
            //    }

            //}
            //catch (Exception ex)
            //{
            //    System.Windows.MessageBox.Show(ex.HResult.ToString() + "-" + ex.Message, "", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
            //    return false;
            //}
            //return true;
            #endregion

            #region revised version II
            //write a method which could handle both mtb and oxy reports in ReportItems, not only one kinds
            Word.Application wdApp = null;
            try
            {
                wdApp         = new Word.Application();
                wdApp.Visible = true;
                Word.Document doc = wdApp.Documents.Add();
                Word.Range    rng;
                foreach (var item in rpt)
                {
                    #region if item is Model.IOxyReport
                    if (item is Model.IOxyReport)
                    {
                        Model.IOxyReport itemTrans = item as Model.IOxyReport;
                        rng = doc.Paragraphs.Add().Range;
                        //rng.InsertAfter(item.Title);
                        rng.Font.Size = 14;
                        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        foreach (Model.IOxyRptOutput output in itemTrans.OxyContents)
                        {
                            rng.InsertParagraphAfter();
                            rng = doc.Paragraphs[doc.Paragraphs.Count].Range;
                            rng.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                            rng.Font.Size = 10;
                            if (output.OutputInByteArr == null)
                            {
                                continue;
                            }
                            switch (output.OxyOType)
                            {
                            case Dashboard.Model.OxyOType.GRAPH:
                                Image img = Tool.BinaryToImage(output.OutputInByteArr);
                                System.Windows.Clipboard.SetDataObject(img);
                                rng.Paste();
                                var shape = rng.InlineShapes[rng.InlineShapes.Count];
                                shape.Width = doc.PageSetup.PageWidth * 0.7f;
                                break;

                            case Dashboard.Model.OxyOType.TABLE:
                                DataTable  dt  = Tool.BinaryToDataTable(output.OutputInByteArr);
                                Word.Table tbl = CreateWordTableWithDataTable(dt, rng);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    #endregion
                    #region if item is Model.IReport
                    else
                    {
                        Model.IReport itemTrans = item as Model.IReport;
                        rng = doc.Paragraphs.Add().Range;
                        rng.InsertAfter(item.Title);
                        rng.Font.Size = 14;
                        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        foreach (Model.IRptOutput output in itemTrans.Contents)
                        {
                            rng.InsertParagraphAfter();
                            rng = doc.Paragraphs[doc.Paragraphs.Count].Range;
                            rng.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;
                            rng.Font.Size = 10;
                            if (output.OutputInByteArr == null)
                            {
                                continue;
                            }
                            switch (output.OType)
                            {
                            case Dashboard.Model.MtbOType.GRAPH:
                                Image img = Tool.BinaryToImage(output.OutputInByteArr);
                                System.Windows.Clipboard.SetDataObject(img);
                                rng.Paste();
                                var shape = rng.InlineShapes[rng.InlineShapes.Count];
                                shape.Width = doc.PageSetup.PageWidth * 0.7f;
                                break;

                            case Dashboard.Model.MtbOType.PARAGRAPH:

                                rng.ParagraphFormat.Alignment       = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                                rng.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly;
                                rng.ParagraphFormat.LineSpacing     = 12f;
                                rng.InsertAfter(System.Text.Encoding.UTF8.GetString(output.OutputInByteArr));
                                break;

                            case Dashboard.Model.MtbOType.TABLE:
                                DataTable  dt  = Tool.BinaryToDataTable(output.OutputInByteArr);
                                Word.Table tbl = CreateWordTableWithDataTable(dt, rng);
                                break;

                            case Dashboard.Model.MtbOType.TITLE:
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.HResult.ToString() + "-" + ex.Message, "", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Warning);
                return(false);
            }
            return(true);

            #endregion
        }
Beispiel #51
0
        /// <summary>
        /// 规范表格,而且删除表格中的嵌入式图片
        /// </summary>
        /// <param name="TableStyle">要应用的表格样式</param>
        /// <param name="ParagraphFormat">表格中的段落样式</param>
        /// <param name="blnDeleteShapes">是否要删除表格中的图片,包括嵌入式或非嵌入式图片。</param>
        /// <remarks></remarks>
        public void TableFormat(string TableStyle    = "zengfy表格-上下总分型1", string ParagraphFormat = "表格内容置顶",
                                bool blnDeleteShapes = false)
        {
            var Selection = _app.Selection;

            if (Selection.Tables.Count > 0)
            {
                //定位表格
                Table Tb = default(Table);
                Range rg = default(Range);
                foreach (Table tempLoopVar_Tb in Selection.Range.Tables)
                {
                    Tb   = tempLoopVar_Tb;
                    rg   = Tb.Range;
                    _app = Tb.Application;
                    //
                    _app.ScreenUpdating = false;

                    //调整表格尺寸
                    dynamic with_1 = Tb;
                    with_1.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitContent);
                    with_1.AutoFitBehavior(WdAutoFitBehavior.wdAutoFitWindow);

                    //清除表格中的超链接
                    Hyperlinks hps = default(Hyperlinks);
                    hps = rg.Hyperlinks;

                    int hpCount = 0;
                    hpCount = hps.Count;
                    for (var i = 1; i <= hpCount; i++)
                    {
                        hps[1].Delete();
                    }

                    //将手动换行符删除
                    {
                        Tb.Range.Find.ClearFormatting();
                        Tb.Range.Find.Replacement.ClearFormatting();
                        Tb.Range.Find.Text             = "^l";
                        Tb.Range.Find.Replacement.Text = "";
                        Tb.Range.Find.Execute(WdReplace.wdReplaceAll);
                    }
                    //删除表格中的乱码空格
                    {
                        Tb.Range.Find.ClearFormatting();
                        Tb.Range.Find.Replacement.ClearFormatting();
                        Tb.Range.Find.Text             = " ";
                        Tb.Range.Find.Replacement.Text = " ";
                        Tb.Range.Find.Execute(WdReplace.wdReplaceAll);
                    }

                    //删除表格中的嵌入式图片
                    if (blnDeleteShapes)
                    {
                        InlineShapes inlineshps = default(InlineShapes);
                        int          Count      = 0;
                        InlineShape  inlineShp  = default(InlineShape);
                        inlineshps = Tb.Range.InlineShapes;
                        Count      = inlineshps.Count;
                        for (var i = Count; i >= 1; i--)
                        {
                            inlineShp = inlineshps[Convert.ToInt32(i)];
                            inlineShp.Delete();
                        }
                        //删除表格中的图片
                        ShapeRange shps = default(ShapeRange);
                        Shape      shp  = default(Shape);
                        shps  = Tb.Range.ShapeRange;
                        Count = shps.Count;
                        for (var i = Count; i >= 1; i--)
                        {
                            shp = shps[i];
                            shp.Delete();
                        }
                    }

                    //清除表格中的格式设置
                    rg.Select();
                    Selection.ClearFormatting();

                    // ----- 设置表格样式与表格中的段落样式
                    try //设置表格样式
                    {
                        Tb.set_Style(TableStyle);
                    }
                    catch (Exception)
                    {
                    }
                    try //设置表格中的段落样式
                    {
                        rg.ParagraphFormat.set_Style(ParagraphFormat);
                    }
                    catch (Exception)
                    {
                    }
                }

                //取消选择并刷新界面
                Selection.Collapse();
                _app.ScreenRefresh();
                _app.ScreenUpdating = true;
            }
            else
            {
                MessageBox.Show("请至少选择一个表格。", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
 private void InterlinguaSpellCheck_Load(object sender, RibbonUIEventArgs e)
 {
     //Get the word application object
     wordApp = Globals.ThisAddIn.Application;
 }
Beispiel #53
0
        /// <summary>
        /// ドキュメントのプロパティ取得
        /// </summary>
        /// <param name="strClassNo">文書分類番号</param>
        /// <param name="strSecrecyLevel">機密区分</param>
        /// <param name="bStamp">スタンプ有無</param>off
        public override void GetDocumentProperty(ref string strSecrecyLevel, ref string strOfficeCod, ref string strOfficeCode)
        {
            Type   tBuiltProp;                                      // プロパティ情報タイプ
            Type   tProperty;                                       // プロパティ値タイプ
            object oBuiltProp;                                      // プロパティ情報オブジェクト
            object oPropertyItem;                                   // プロパティアイテムオブジェクト
            object oPropertyValue;                                  // プロパティ値オブジェクト

            // 現在開いているWordの取得
            Word.Application WordApp = (Word.Application)global::WordAddInSAB.Globals.ThisAddIn.Application;

            // プロパティ情報を取得
            oBuiltProp = WordApp.ActiveDocument.BuiltInDocumentProperties;

            try
            {
                /////////////////////////////
                // Category(分類項目)情報取得
                /////////////////////////////

                // プロパティ情報タイプを取得
                tBuiltProp = oBuiltProp.GetType();

                // プロパティCategory(分類項目)のアイテム情報を取得
                oPropertyItem = tBuiltProp.InvokeMember("Item", BindingFlags.GetProperty, null, oBuiltProp, new object[] { "Category" });

                // プロパティCategory(分類項目)の値を取得
                tProperty      = oPropertyItem.GetType();
                oPropertyValue = tProperty.InvokeMember("Value", BindingFlags.GetProperty, null, oPropertyItem, new object[] { });


                /////////////////////////////
                // keywords(タグ)情報取得
                /////////////////////////////

                // プロパティ情報タイプを取得
                tBuiltProp = oBuiltProp.GetType();

                // プロパティkeywords(タグ)のアイテム情報を取得
                oPropertyItem = tBuiltProp.InvokeMember("Item", BindingFlags.GetProperty, null, oBuiltProp, new object[] { "keywords" });

                // プロパティkeywords(タグ)の値を取得
                tProperty      = oPropertyItem.GetType();
                oPropertyValue = tProperty.InvokeMember("Value", BindingFlags.GetProperty, null, oPropertyItem, new object[] { });


                // タグ情報があった場合は機密区分、文書分類番号、スタンプの有無をセットする
                if (oPropertyValue != null)
                {
                    string[] strPropertyData = oPropertyValue.ToString().Split(';');

                    // プロパティの事業所コードを取得
                    if (strPropertyData.Count() > (int)Property.OfficeCode)
                    {
                        strOfficeCode = strPropertyData[(int)Property.OfficeCode].Trim();
                    }
                    else
                    {
                        strOfficeCode = AddInsLibrary.CommonSettings.COMMON_SETDEF_OFFICECODE;
                    }


                    // プロパティの文書番号を取得
                    if (strPropertyData.Count() > (int)Property.ClassNo)
                    {
                        strSecrecyLevel = strPropertyData[(int)Property.ClassNo].Trim();
                    }


                    // プロパティの機密区分を取得
                    if (strPropertyData.Count() > (int)Property.SecrecyLevel)
                    {
                        strSecrecyLevel = strPropertyData[(int)Property.SecrecyLevel].Trim();
                    }
                }
            }
            catch
            {
                MessageBox.Show(AddInsLibrary.Properties.Resources.msg_err_read_common_file, AddInsLibrary.Properties.Resources.msgError, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
Beispiel #54
0
        static void Main(string[] args)
        {
            //get user's desktop path for log file, and add log file name
            string logFilePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\containsLink_log.txt";

            //retrive file names from user's specified directory and sub directories
            Console.WriteLine("Enter directory to search:  ");
            string path = Console.ReadLine();

            string[] myFiles = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);

            //process each file
            foreach (string filename in myFiles)
            {
                //skip file if just temp file
                if (filename.Substring(0, 1) != "~")
                {
                    //write filename to log file
                    System.IO.File.AppendAllText(logFilePath, filename);
                    System.IO.File.AppendAllText(logFilePath, Environment.NewLine);
                    Console.WriteLine(filename);

                    //make list to store file's links
                    List <string> links = new List <string>();

                    //find file's extension (type)
                    int    extLoc  = filename.LastIndexOf(".");
                    int    endLoc  = filename.Length - extLoc - 1;
                    string fileExt = filename.Substring(extLoc + 1, endLoc);

                    //process file according to its type, extracting the file's links
                    if (fileExt == "pdf")
                    {
                        //Setup some variables to be used later
                        PdfReader     reader         = default(PdfReader);
                        int           pageCount      = 0;
                        PdfDictionary pageDictionary = default(PdfDictionary);
                        PdfArray      annots         = default(PdfArray);

                        //Open our reader
                        reader = new PdfReader(filename);
                        //Get the page cont
                        pageCount = reader.NumberOfPages;

                        //Loop through each page
                        for (int i = 1; i <= pageCount; i++)
                        {
                            //Get the current page
                            pageDictionary = reader.GetPageN(i);
                            //Get all of the annotations for the current page
                            annots = pageDictionary.GetAsArray(PdfName.ANNOTS);
                            //Make sure we have something
                            if ((annots == null) || (annots.Length == 0))
                            {
                                Console.WriteLine("nothing");
                            }
                            //Loop through each annotation
                            if (annots != null)
                            {
                                //add page number to list
                                links.Add("Page " + i);

                                foreach (PdfObject A in annots.ArrayList)
                                {
                                    //Convert the itext-specific object as a generic PDF object
                                    PdfDictionary AnnotationDictionary =
                                        (PdfDictionary)PdfReader.GetPdfObject(A);
                                    //Make sure this annotation has a link
                                    if (!AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK))
                                    {
                                        continue;
                                    }
                                    //Make sure this annotation has an ACTION
                                    if (AnnotationDictionary.Get(PdfName.A) == null)
                                    {
                                        continue;
                                    }
                                    //Get the ACTION for the current annotation
                                    PdfDictionary AnnotationAction =
                                        AnnotationDictionary.GetAsDict(PdfName.A);
                                    // Test if it is a URI action
                                    if (AnnotationAction.Get(PdfName.S).Equals(PdfName.URI))
                                    {
                                        PdfString Destination = AnnotationAction.GetAsString(PdfName.URI);
                                        string    url         = Destination.ToString();

                                        //add url to list
                                        links.Add(url);
                                    }
                                }
                            }
                        }
                    }
                    else if ((fileExt == "xls") || (fileExt == "xlsx"))
                    {
                        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                        excelApp.Visible = false;

                        //open excel file
                        Workbook excelWorkbook = excelApp.Workbooks.Open(filename, 0, true, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                        Sheets   excelSheets   = excelWorkbook.Worksheets;

                        //loop through worksheets
                        for (int i = 1; i <= excelSheets.Count; i++)
                        {
                            Worksheet sheet = (Worksheet)excelSheets.Item[i];

                            //extract links
                            if (sheet.Hyperlinks.Count > 0)
                            {
                                links.Add("Page " + i);

                                for (int j = 1; j <= sheet.Hyperlinks.Count; j++)
                                {
                                    string address = sheet.Hyperlinks[i].Address;
                                    links.Add(address);
                                }
                            }
                        }

                        excelWorkbook.Close(false);
                        excelApp.Quit();
                    }
                    else if ((fileExt == "doc") || (fileExt == "docx"))
                    {
                        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
                        Document doc = wordApp.Documents.Open(FileName: filename, ReadOnly: true);
                        Microsoft.Office.Interop.Word.Hyperlinks hyperlinks = doc.Hyperlinks;

                        if (hyperlinks.Count > 0)
                        {
                            //links.Add("Page: ");

                            foreach (var hyperlink in hyperlinks)
                            {
                                string address = ((Microsoft.Office.Interop.Word.Hyperlink)hyperlink).Address;
                                links.Add(address);
                            }
                        }

                        doc.Close(false);
                        wordApp.Quit(false);
                    }
                    else if ((fileExt == "csv") || (fileExt == "txt"))
                    {
                        string[] lines = System.IO.File.ReadAllLines(filename);

                        foreach (string line in lines)
                        {
                            foreach (Match item in Regex.Matches(line, @"(http(s)?://)?([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?"))
                            {
                                string address = item.Value;
                                links.Add(address);
                            }
                        }
                    }
                    else
                    {
                    }

                    //write the file's link count to the log file
                    //have to subtract the page number markers from the links count
                    int fileLinkCount = 0;
                    foreach (string line in links)
                    {
                        if (line.Substring(0, 4) != "Page")
                        {
                            fileLinkCount++;
                        }
                    }
                    System.IO.File.AppendAllText(logFilePath, "Link count: " + fileLinkCount + Environment.NewLine);

                    //write the file's links to the log file
                    if (links.Count > 0)
                    {
                        using (TextWriter tw = new StreamWriter(logFilePath, append: true))
                        {
                            foreach (String s in links)
                            {
                                tw.WriteLine(s);
                            }
                        }
                    }

                    System.IO.File.AppendAllText(logFilePath, "----------" + Environment.NewLine);
                }
            }
        }
Beispiel #55
0
        public void CreateWord()
        {
            object oMissing  = System.Reflection.Missing.Value;
            object oEndOfDoc = "\\endofdoc"; /* \endofdoc is a predefined bookmark */

            Word._Application oWord = new Word.Application();
            Word.Document     oDoc  = oWord.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);


            //Insert a paragraph at the beginning of the document.
            Word.Paragraph oPara1;
            oPara1                   = oDoc.Content.Paragraphs.Add(ref oMissing);
            oPara1.Range.Text        = "AlfaPeople Nordic";
            oPara1.Range.Font.Bold   = 1;
            oPara1.Format.SpaceAfter = 24;    //24 pt spacing after paragraph.
            oPara1.Range.InsertParagraphAfter();

            //Insert a paragraph at the end of the document.
            Word.Paragraph oPara2;
            object         oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;

            oPara2                   = oDoc.Content.Paragraphs.Add(ref oRng);
            oPara2.Range.Text        = "Heading 2";
            oPara2.Format.SpaceAfter = 6;
            oPara2.Range.InsertParagraphAfter();

            //Insert another paragraph.
            Word.Paragraph oPara3;
            oRng                     = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oPara3                   = oDoc.Content.Paragraphs.Add(ref oRng);
            oPara3.Range.Text        = "This is a sentence of normal text. Now here is a table:";
            oPara3.Range.Font.Bold   = 0;
            oPara3.Format.SpaceAfter = 24;
            oPara3.Range.InsertParagraphAfter();

            //Insert a 3 x 5 table, fill it with data, and make the first row
            //bold and italic.
            Word.Table oTable;
            Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
            oTable.Range.ParagraphFormat.SpaceAfter = 6;
            int    r, c;
            string strText;

            for (r = 1; r <= 3; r++)
            {
                for (c = 1; c <= 5; c++)
                {
                    strText = "r" + r + "c" + c;
                    oTable.Cell(r, c).Range.Text = strText;
                }
            }
            oTable.Rows[1].Range.Font.Bold   = 1;
            oTable.Rows[1].Range.Font.Italic = 1;

            //Add some text after the table.
            Word.Paragraph oPara4;
            oRng   = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
            oPara4.Range.InsertParagraphBefore();
            oPara4.Range.Text        = "And here's another table:";
            oPara4.Format.SpaceAfter = 24;
            oPara4.Range.InsertParagraphAfter();

            //Insert a 5 x 2 table, fill it with data, and change the column widths.
            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
            oTable.Range.ParagraphFormat.SpaceAfter = 6;
            for (r = 1; r <= 5; r++)
            {
                for (c = 1; c <= 2; c++)
                {
                    strText = "r" + r + "c" + c;
                    oTable.Cell(r, c).Range.Text = strText;
                }
            }
            oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
            oTable.Columns[2].Width = oWord.InchesToPoints(3);

            //Keep inserting text. When you get to 7 inches from top of the
            //document, insert a hard page break.
            object oPos;
            double dPos = oWord.InchesToPoints(7);

            oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
            do
            {
                wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
                wrdRng.ParagraphFormat.SpaceAfter = 6;
                wrdRng.InsertAfter("A line of text");
                wrdRng.InsertParagraphAfter();
                oPos = wrdRng.get_Information
                           (Word.WdInformation.wdVerticalPositionRelativeToPage);
            }while (dPos >= Convert.ToDouble(oPos));
            object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
            object oPageBreak   = Word.WdBreakType.wdPageBreak;

            wrdRng.Collapse(ref oCollapseEnd);
            wrdRng.InsertBreak(ref oPageBreak);
            wrdRng.Collapse(ref oCollapseEnd);
            wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
            wrdRng.InsertParagraphAfter();

            //Insert a chart.
            Word.InlineShape oShape;
            object           oClassType = "MSGraph.Chart.8";

            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,
                                                      ref oMissing, ref oMissing, ref oMissing,
                                                      ref oMissing, ref oMissing, ref oMissing);

            //Demonstrate use of late bound oChart and oChartApp objects to
            //manipulate the chart object with MSGraph.
            object oChart;
            object oChartApp;

            oChart    = oShape.OLEFormat.Object;
            oChartApp = oChart.GetType().InvokeMember("Application",
                                                      BindingFlags.GetProperty, null, oChart, null);

            //Change the chart type to Line.
            object[] Parameters = new Object[1];
            Parameters[0] = 4; //xlLine = 4
            oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
                                          null, oChart, Parameters);

            //Update the chart image and quit MSGraph.
            oChartApp.GetType().InvokeMember("Update",
                                             BindingFlags.InvokeMethod, null, oChartApp, null);
            oChartApp.GetType().InvokeMember("Quit",
                                             BindingFlags.InvokeMethod, null, oChartApp, null);
            //... If desired, you can proceed from here using the Microsoft Graph
            //Object model on the oChart and oChartApp objects to make additional
            //changes to the chart.

            //Set the width of the chart.
            oShape.Width  = oWord.InchesToPoints(6.25f);
            oShape.Height = oWord.InchesToPoints(3.57f);

            //Add text after the chart.
            wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            wrdRng.InsertParagraphAfter();
            wrdRng.InsertAfter("THE END.");

            oDoc.SaveAs2(@"c:\temp\MyNewWorddoc.docx");
        }
Beispiel #56
0
        private void okButton_Click(object sender, EventArgs e)
        {
            string   name  = tbxName.Text;
            string   label = tbxLabel.Text;
            DateTime date  = dtPicker.Value;

            foreach (string item in chlbxAnalysis.CheckedItems)
            {
                switch (item)
                {
                case "Описательные статистики": { Types.Add(TypeOfAnalysis.Statistics); break; };

                case "T-тест": { Types.Add(TypeOfAnalysis.Ttest); break; };

                case "Тест Манна-Уитни": { Types.Add(TypeOfAnalysis.MannWitney); break; };

                case "Хи-Квадрат": { Types.Add(TypeOfAnalysis.Hi); break; };

                case "ANOVA": { Types.Add(TypeOfAnalysis.ANOVA); break; };

                case "Корреляционный анализ": { Types.Add(TypeOfAnalysis.CorAnalysis); break; };

                case "Корреляционная плеяда": { Types.Add(TypeOfAnalysis.CorPleiade); break; };

                case "Регрессионный анализ": { Types.Add(TypeOfAnalysis.RegAnalysis); break; };

                case "Кластеризация": { Types.Add(TypeOfAnalysis.Clustering); break; };

                default: { MessageBox.Show("Как вы вообще здесь оказались?!"); break; }
                }
            }


            try
            {
                //Создаем объект Word - равносильно запуску Word
                wordApp = new Word.Application();
                //Делаем его видимым
                wordApp.Visible = true;
                // открываем документ, соответствующий шаблону
                String templatePath = Environment.CurrentDirectory + "\\TemplateWord.dotx";
                wordDoc = wordApp.Documents.Add(templatePath);

                // вставка текста по закладке (закладки можно создавать в Word: Вставка - Ссылки - Закладка)
                wordRange      = wordDoc.Bookmarks["label"].Range;
                wordRange.Text = label;

                wordRange = wordDoc.Bookmarks["gender"].Range;
                if (chbxFemale.Checked)
                {
                    wordRange.Text = "а";
                }
                wordRange      = wordDoc.Bookmarks["name"].Range;
                wordRange.Text = name;

                wordRange      = wordDoc.Bookmarks["date"].Range;
                wordRange.Text = date.ToString("D");

                wordDoc.Paragraphs.Add();

                wordDoc.Paragraphs.Add();
                wordRange           = wordDoc.Paragraphs[7].Range;
                wordRange.Text      = "Здесь будет описание данных... ";
                wordRange.Font.Size = 12;
                wordRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;

                wordDoc.Paragraphs.Add();
                indexOfParagraphs = 9;
                Types.Sort();

                foreach (var type in Types)
                {
                    switch (type)
                    {
                    case TypeOfAnalysis.Statistics:
                    {
                        indexOfParagraphs = addSomeInfo("Описательные статистики", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.Ttest:
                    {
                        indexOfParagraphs = addSomeInfo("Т Тест", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.MannWitney:
                    {
                        indexOfParagraphs = addSomeInfo("Тест Манна-Уитни", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.Hi:
                    {
                        indexOfParagraphs = addSomeInfo("Хи-Квадрат", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.ANOVA:
                    {
                        indexOfParagraphs = addSomeInfo("АНОВА", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.CorAnalysis:
                    {
                        indexOfParagraphs = addSomeInfo("Корреляционный анализ", indexOfParagraphs);

                        //вставка таблицы
                        Word.Table wordtable = wordDoc.Tables.Add(wordRange, 3, 3);

                        // прорисовка границ -- по умолчанию границы таблицы не рисуются
                        wordtable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                        wordtable.Borders.InsideLineStyle  = Word.WdLineStyle.wdLineStyleDashSmallGap;

                        for (int i = 1; i < 4; ++i)
                        {
                            for (int j = 1; j < 4; ++j)
                            {
                                if (i == 1 && j == 1)
                                {
                                    continue;
                                }

                                if (i == 1)
                                {
                                    wordRange      = wordtable.Cell(i, j).Range;
                                    wordRange.Text = "X" + (j - 1);
                                    continue;
                                }

                                if (j == 1)
                                {
                                    wordRange      = wordtable.Cell(i, j).Range;
                                    wordRange.Text = "Y" + (i - 1);
                                    continue;
                                }

                                wordRange = wordtable.Cell(i, j).Range;
                            }
                        }

                        wordRange = wordtable.Cell(3, 3).Range;
                        wordDoc.Paragraphs.Add();
                        indexOfParagraphs = wordDoc.Paragraphs.Count;
                        wordRange         = wordDoc.Paragraphs[indexOfParagraphs].Range;
                        break;
                    };

                    case TypeOfAnalysis.CorPleiade:
                    {
                        indexOfParagraphs = addSomeInfo("Корреляционная плеяда", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.RegAnalysis:
                    {
                        indexOfParagraphs = addSomeInfo("Регрессионный анализ", indexOfParagraphs);
                        break;
                    };

                    case TypeOfAnalysis.Clustering:
                    {
                        indexOfParagraphs = addSomeInfo("Кластеризация", indexOfParagraphs);
                        break;
                    };

                    default:
                    {
                        MessageBox.Show("Как вы вообще здесь оказались?!");
                        break;
                    }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Упс.. " + ex.Message);
                wordApp.Quit();
                wordDoc = null;
                wordApp = null;
            }
        }
 private void ThisAddIn_Startup(object sender, System.EventArgs e)
 {
     ThisApplication = this.Application;
 }
Beispiel #58
0
        public static void createDoc(Test test)
        {
            object         missing = System.Reflection.Missing.Value;
            WordSaver      ws      = new WordSaver();
            SaveFileDialog sfd     = new SaveFileDialog();

            sfd.Filter   = "Word Documents (*.docx)|*.docx";
            sfd.FileName = "Тест " + test.TestName + ".docx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                Word.Document doc = null;
                try
                {
                    // Создаём объект приложения
                    Word.Application app = new Word.Application();
                    // Путь до шаблона документа
                    File.Delete(Environment.CurrentDirectory + @"\Word\" + test.TestName + ".docx");
                    File.Copy(Environment.CurrentDirectory + @"\Word\WordTest.docx",
                              Environment.CurrentDirectory + @"\Word\" + test.TestName + ".docx");
                    string source = Environment.CurrentDirectory + @"\Word\" + test.TestName + ".docx";
                    // Открываем
                    doc = app.Documents.Open(source);
                    doc.Activate();

                    // Добавляем информацию
                    // wBookmarks содержит все закладки
                    Word.Bookmarks wBookmarks = doc.Bookmarks;

                    //string[] data = new string[3] { "27", "Alex", "Gulynin" };



                    foreach (Word.Bookmark mark in wBookmarks)
                    {
                        if (mark.Name == "testName")
                        {
                            mark.Range.Text = test.TestName;
                        }

                        if (mark.Name == "markExcellent")
                        {
                            mark.Range.Text = test.ListMarks[0].ToString();
                        }

                        if (mark.Name == "markGood")
                        {
                            mark.Range.Text = test.ListMarks[1].ToString();
                        }

                        if (mark.Name == "markSatisfactory")
                        {
                            mark.Range.Text = test.ListMarks[2].ToString();
                        }

                        if (mark.Name == "tasksStartHere")
                        {
                            string textForInsert = "";
                            int    count         = 0;
                            foreach (KeyValuePair <LinkLabel, PanelWrapper> keyValue in test.ListPanelsTasks)
                            {
                                string         taskUslovie = "";
                                List <TextBox> bufListTB   = new List <TextBox> {
                                };
                                //List<PictureBox> listPB = new List<PictureBox> { };
                                textForInsert += "\n\n\n\nЗадание №" + (count + 1) + "\n";
                                for (int i = 0; i < keyValue.Value.Entity.Controls[0].Controls.Count; i++)
                                {
                                    if (keyValue.Value.Entity.Controls[0].Controls[i] is RichTextBox)
                                    {
                                        taskUslovie = keyValue.Value.Entity.Controls[0].Controls[i].Text;
                                    }
                                }

                                textForInsert += "Условие: " + taskUslovie + "\n";



                                for (int i = 0; i < keyValue.Value.Entity.Controls[0].Controls.Count; i++)
                                {
                                    if (keyValue.Value.Entity.Controls[0].Controls[i] is PictureBox)
                                    {
                                        Clipboard.SetImage(
                                            ((PictureBox)(keyValue.Value.Entity.Controls[0].Controls[i]))
                                            .Image);
                                        mark.Range.Paste();
                                    }
                                }


                                for (int i = keyValue.Value.Entity.Controls[0].Controls.Count; i > 0; i--)
                                {
                                    if (keyValue.Value.Entity.Controls[0].Controls[i - 1] is TextBox)
                                    {
                                        bufListTB.Add((TextBox)keyValue.Value.Entity.Controls[0].Controls[i - 1]);
                                    }
                                }

                                for (int i = 0; i < bufListTB.Count; i++)
                                {
                                    textForInsert += "Ответ №" + (i + 1) + ": ";
                                    textForInsert += bufListTB[i].Text + "\n";
                                }

                                count++;
                            }

                            mark.Range.Text = textForInsert;
                        }
                    }

                    doc.SaveAs2000(sfd.FileName);
                    File.Delete(source);
                    // Закрываем документ
                    doc.Close(/*ref missing, ref missing, ref missing*/);
                }

                catch (IOException e)
                {
                    MessageBox.Show("Не удалось сохранить файл, возможно он уже существует " + e.Message,
                                    "Не удалось сохранить файл",
                                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }
Beispiel #59
0
 // The constructor helps opening word application or makes one activate
 public WordManipulator()
 {
     wordApp = new Word.Application();
 }
Beispiel #60
-1
        private bool ConvertWordDocToXPSDoc(string wordDocName)
        {
            // Create a WordApplication and add Document to it
            Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            wordApplication.Documents.Add(wordDocName);
            Document doc = wordApplication.ActiveDocument;
            // You must make sure you have Microsoft.Office.Interop.Word.Dll version 12.
            // Version 11 or previous versions do not have WdSaveFormat.wdFormatXPS option
            try
            {
                string xpsDocName = @"http://www.jjgjt.com/download/1.xps";
                doc.SaveAs(xpsDocName, WdSaveFormat.wdFormatXPS);
                wordApplication.Quit();
                //XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);
                XpsDocument xpsDoc = new XpsDocument(xpsDocName, System.IO.FileAccess.Read);

                documentViewer1.Document = xpsDoc.GetFixedDocumentSequence();
                return true;
            }
            catch (Exception exp)
            {
                string str = exp.Message;
                return false;
            }
        }