Как читать содержимое документа Visio в C # - PullRequest
2 голосов
/ 15 октября 2011

код моей библиотеки DLL выглядит следующим образом:

using System;
using IVisio=Microsoft.Office.Interop.Visio;

namespace Emix
{
public class Visio
{
    protected String path;

    public Visio(String path)
    {
        this.path = path;
    }

    public void open()
    {
        try
        {
            IVisio.Document doc = new IVisio.Application().Documents.Add(this.path);
            Console.WriteLine("Number of pages: " + doc.Pages.Count);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
}

Однако этот код открывает редактор Visio, а затем отображает количество страниц в документе.Можно ли прочитать содержимое этого файла, не открывая Visio?

Ответы [ 5 ]

1 голос
/ 15 октября 2011

Это программа для чтения свойств фигур в Visio ....

    namespace VisioEventsExample
    {
    using System;
    using Microsoft.Office.Interop.Visio;

    class Program
    {
        public static void Main(string[] args)
        {
            // Open up one of Visio's sample drawings.
            Application app = new Application();
            Document doc = app.Documents.Open(
                @"C:\Program Files\Microsoft Office\Office14\visio content\1033\ASTMGT_U.VST");

            // Get the first page in the sample drawing.
            Page page = doc.Pages[1];

            // Start with the collection of shapes on the page and 
            // print the properties we find,
            printProperties(page.Shapes);
        }

        /* This function will travel recursively through a collection of 
         * shapes and print the custom properties in each shape. 
         * 
         * The reason I don't simply look at the shapes in Page.Shapes is 
         * that when you use the Group command the shapes you group become 
         * child shapes of the group shape and are no longer one of the 
         * items in Page.Shapes.
         * 
         * This function will not recursive into shapes which have a Master. 
         * This means that shapes which were created by dropping from stencils 
         * will have their properties printed but properties of child shapes 
         * inside them will be ignored. I do this because such properties are 
         * not typically shown to the user and are often used to implement 
         * features of the shapes such as data graphics.
         * 
         * An alternative halting condition for the recursion which may be 
         * sensible sense for many drawing types would be to stop when you 
         * find a shape with custom properties.
         */
        public static void printProperties(Shapes shapes)
        {
            // Look at each shape in the collection.
            foreach (Shape shape in shapes)
            {               
                // Use this index to look at each row in the properties 
                // section.
                short iRow = (short) VisRowIndices.visRowFirst;

                // While there are stil rows to look at.
                while (shape.get_CellsSRCExists(
                    (short) VisSectionIndices.visSectionProp, 
                    iRow, 
                    (short) VisCellIndices.visCustPropsValue,
                    (short) 0) != 0)
                {
                    // Get the label and value of the current property.
                    string label = shape.get_CellsSRC(
                            (short) VisSectionIndices.visSectionProp, 
                            iRow,
                            (short) VisCellIndices.visCustPropsLabel
                        ).get_ResultStr(VisUnitCodes.visNoCast);

                    string value = shape.get_CellsSRC(
                            (short) VisSectionIndices.visSectionProp, 
                            iRow,
                            (short) VisCellIndices.visCustPropsValue
                        ).get_ResultStr(VisUnitCodes.visNoCast);

                    // Print the results.
                    Console.WriteLine(string.Format(
                        "Shape={0} Label={1} Value={2}",
                        shape.Name, label, value));

                    // Move to the next row in the properties section.
                    iRow++;
                }

                // Now look at child shapes in the collection.
                if (shape.Master == null && shape.Shapes.Count > 0)
                    printProperties(shape.Shapes);
            }
        }
    }
}

В приведенном выше примере предполагается, что на вашем ПК установлена ​​ Основная сборка взаимодействия Visio и что вы включили в свой проект рефери Microsoft.Office.Interop.Visio.

Надеюсь, это поможет вам ....

0 голосов
/ 08 марта 2017

Как указывает один из других ответов, вы можете использовать свойство Application.Visible, чтобы скрыть работающий экземпляр Visio.

Другой вариант - прочитать файл формата VDX Visio напрямую, чтобы получить числостраниц, пользовательских свойств и т. д. Это позволяет избежать запуска Visio для чтения информации из файла.Но это решение требует, чтобы вы стали XML-схемой файлов VDX.

0 голосов
/ 16 октября 2011

Как указывает один из других ответов, вы можете использовать свойство Application.Visible , чтобы скрыть запущенный экземпляр Visio.

Другой вариант - прочитать VDX-файл Visio.напрямую форматировать для получения количества страниц, пользовательских свойств и т. д. Это позволяет избежать запуска Visio для считывания информации из файла.Но это решение требует, чтобы вы стали XML-схемой файлов VDX.

0 голосов
/ 15 октября 2011

Если вы сделаете приложение невидимым, вы не увидите новый экземпляр открытия Visio (все еще будет запущенный экземпляр Visio, просто не видимый)

Application application = new Application();  
application.Visible = false; 
Document doc = application.Documents.Add(this.path);
Console.WriteLine("Number of pages: " + doc.Pages.Count);
0 голосов
/ 15 октября 2011

Взгляните на Как получить информацию о форме в Visio с помощью C # . Он содержит некоторую полезную информацию о вашем сценарии

В этом посте также объясняется, как получить все фигуры и, кроме того, как соединить все фигуры вместе

...