Гость
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Как открыть документ Word из С# / 14 сообщений из 14, страница 1 из 1
16.06.2006, 14:04
    #33795661
Dragon_Oleg
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Как открыть документ Word, который находиться на диске из WinForm (C#) ?
Надо ли подключать Com объект для Word?

Microsoft.Office.Interop.Word.ApplicationClass WordApp =
new Microsoft.Office.Interop.Word.ApplicationClass();
...
Рейтинг: 0 / 0
16.06.2006, 14:28
    #33795757
1024
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
как-то так:

System.Diagnostics.Process myProcess = new Process();
myProcess.StartInfo.FileName = "c:\\MyFile.doc";
myProcess.StartInfo.Verb = "Open";
myProcess.StartInfo.CreateNoWindow = false;
myProcess.Start();


Posted via ActualForum NNTP Server 1.3
...
Рейтинг: 0 / 0
16.06.2006, 14:47
    #33795818
Dragon_Oleg
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Спасибо большое Хорошее решение
а что если понадобиться открыть в Word файл с расширением xml?
По умалчанию он открываеться в IE, а хотелось бы Word

Как тогда решить поставленную задачю?
...
Рейтинг: 0 / 0
16.06.2006, 15:09
    #33795910
1024
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
System.Diagnostics.Process - это использовать средства ОС. Если расширение
..doc зарегистрировано на блокнот то и открываться или печататься будет в
блокноте. Если нужен именно ворд то работать с ним можно через COM используя
VBA


Posted via ActualForum NNTP Server 1.3
...
Рейтинг: 0 / 0
16.06.2006, 15:39
    #33796031
Dragon_Oleg
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Понятно
Спасибо большое
...
Рейтинг: 0 / 0
17.06.2006, 23:50
    #33797753
Ray Adams
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Вот тебе небольшой класс для этого дела. Я его для себя писал. Мне было нужно, открыть определенный файл. Произвести в файле замену текста и сохранить обратно.
Вот пример как его использовать
Код: plaintext
1.
2.
3.
4.
5.
            MyWord wrd=new MyWord(true);
            wrd.OpenFile("c:\\file.doc");
            wrd.FindReplace("что", "на что");
            wrd.ShowWord(true);
            wrd.PrintPreview();

Вот сам класс

Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Reflection;

namespace MyOffice
{
    
    public class MyWord
    {
        private object internalWord;
        private object objCurDoc=null;
        private bool FAutoClose = false;
        private bool IsSuccesLast = false;
        public bool IsSucces
        {
            get { bool old = IsSuccesLast; IsSuccesLast = false; return old; }
        }
        public MyWord (bool AutoClose)
        {
            FAutoClose = AutoClose;
            try
            {
                Type objClassType;
                objClassType = Type.GetTypeFromProgID("Word.Application");
                internalWord = Activator.CreateInstance(objClassType);
                IsSuccesLast = true;
            }
            catch
            {
                IsSuccesLast = false;
            }
                
        }
        ~MyWord()
        {
            if ((FAutoClose) && (objCurDoc!=null))
            {
                this.CloseDoc();
            }
        }
        public bool CloseDoc()
        {
            try
            {
                //Close Active Document
                objCurDoc.GetType().InvokeMember("Close", BindingFlags.InvokeMethod,
                    null, objCurDoc, null);
                objCurDoc = null;
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool Quit()
        {
            try
            {
                object[] Parameters;
                Parameters = new Object[3];
                Parameters[0] = 0;
                Parameters[1] = 0;
                Parameters[2] = false;
                internalWord.GetType().InvokeMember("Quit", BindingFlags.SetProperty,
                    null, internalWord, Parameters);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool ShowWord(bool is_visible)
        {
            try
            {
                object[] Parameters;
                Parameters = new Object[1];
                Parameters[0] = is_visible;
                internalWord.GetType().InvokeMember("Visible", BindingFlags.SetProperty,
                    null, internalWord, Parameters);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool OpenFile(string FileName)
        {
            try
            {
                object objDocs_Late = internalWord.GetType().InvokeMember(
                  "Documents", BindingFlags.GetProperty, null, internalWord, null);

                object[] Parameters;
                Parameters = new Object[1];
                Parameters[0] = FileName;
                objCurDoc = objDocs_Late.GetType().InvokeMember("Open",
                    BindingFlags.InvokeMethod, null, objDocs_Late, Parameters);
                return true;
            }
            catch
            {
                return false;
            }

        }
        public bool SaveDocument()
        {
            if (objCurDoc == null) return false;
            try
            {
                objCurDoc.GetType().InvokeMember("Save",
                BindingFlags.InvokeMethod, null, objCurDoc, null);
                return true;
            }
            catch
            {
                return false;
            }
            
        }
        public bool FindReplace(string findtext, string replacetext)
        {
            try
            {
                object[] Parameters;
                object objSelection = internalWord.GetType().InvokeMember(
                  "Selection", BindingFlags.GetProperty, null, internalWord, null);

                Parameters = new Object[2];
                Parameters[0] = 0;
                Parameters[1] = 0;

                objSelection.GetType().InvokeMember(
                  "SetRange", BindingFlags.InvokeMethod, null, objSelection, Parameters);

                object objFind = objSelection.GetType().InvokeMember(
                  "Find", BindingFlags.GetProperty, null, objSelection, null);

                Parameters = new Object[11];
                Parameters[0] = findtext; //find text
                Parameters[1] = false; //match case
                Parameters[2] = true; //match whole word
                Parameters[3] = false; //match wild card
                Parameters[4] = false; //match sounds like
                Parameters[5] = false; //match all word forms
                Parameters[6] = true; //forward
                Parameters[7] = false; //wrap
                Parameters[8] = false; //format
                Parameters[9] = replacetext; //replace text
                Parameters[10] = 2; //replace?
                objFind.GetType().InvokeMember("Execute",
                    BindingFlags.InvokeMethod, null, objFind, Parameters);
                return true;
            }
            catch
            {
                return false;
            }

        }
        public bool SaveAs(string filename)
        {
            if (objCurDoc == null) return false;
            object[] Parameters = new Object[1];
            Parameters[0] = filename; //find text
            try
            {
                objCurDoc.GetType().InvokeMember("SaveAs",
                    BindingFlags.InvokeMethod, null, objCurDoc, Parameters);
                return true;
            }
            catch 
            {
                return false;
            }
        }
        public bool PrintPreview()
        {
            if (objCurDoc == null) return false;
            try
            {
                objCurDoc.GetType().InvokeMember("PrintPreview",
                    BindingFlags.InvokeMethod, null, objCurDoc, null);
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool Print()
        {
            if (objCurDoc == null) return false;
            try
            {
                object[] Parameters = new Object[14];
                Parameters[0] = false; //in bacground?
                Parameters[0] = Missing.Value; //append
                Parameters[0] = 0; //all document wdPrintAllDocument
                Parameters[0] = Missing.Value; //Output file name
                Parameters[0] = Missing.Value; //From 
                Parameters[0] = Missing.Value; //To page
                Parameters[0] = Missing.Value; //Item?
                Parameters[0] = 1; //Copies
                Parameters[0] = Missing.Value; //Pages
                Parameters[0] = Missing.Value; //Page type?
                Parameters[0] = false; //print to file
                Parameters[0] = false; //collate
                Parameters[0] = Missing.Value; //only for MAC
                Parameters[0] = Missing.Value; //Manual duplex
                Parameters[0] = Missing.Value; //collate


                objCurDoc.GetType().InvokeMember("PrintOut",
                    BindingFlags.InvokeMethod, null, objCurDoc, null);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
asdasd
...
Рейтинг: 0 / 0
19.06.2006, 13:13
    #33799544
Dragon_Oleg
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Благодарю за помощь!
...
Рейтинг: 0 / 0
07.07.2006, 15:26
    #33838720
Dragon_Oleg
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Здраствуйте Ray Adams

А что делать, если процессы Word размножаются как кролики?
Делаю вот так:

MyWord wrd = new MyWord(true);
wrd.OpenFile(path);
wrd.ShowWord(true);
wrd.SaveDocument();
wrd.CloseDoc();
wrd.ShowWord(false);
wrd.Quit();

А процессы все увеличиваються
...
Рейтинг: 0 / 0
08.07.2006, 12:20
    #33840011
timur999
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Тогда попробуй так:
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
98.
99.
100.
101.
102.
103.
104.
105.
106.
107.
108.
109.
110.
111.
112.
113.
114.
115.
116.
117.
118.
119.
120.
121.
122.
123.
124.
125.
126.
127.
128.
129.
130.
131.
132.
133.
134.
135.
136.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
258.
259.
260.
using System;
using System.Runtime.InteropServices;
using System.Reflection;

namespace ClassWord
{
	namespace Word
	{
		public enum WdFindWrap: int
		{
			wdFindAsk = 2,
			wdFindContinue = 1,
			wdFindStop = 0
		}

		public enum WdReplace: int
		{
			wdReplaceAll = 2,
			wdReplaceNone = 0,
			wdReplaceOne = 1
		}

		/// <summary>
		/// Summary description for Application
		/// </summary>
		public class Application
		{
			private object application;

			public bool Visible
			{
				get
				{
					return Convert.ToBoolean(application.GetType().InvokeMember("Visible", BindingFlags.GetProperty, null, application, null));
				}
				set
				{
					application.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, application, new object[] {value});
				}
			}

			public void Quit()
			{
				application.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, application, null);
				Marshal.ReleaseComObject(application);
				GC.GetTotalMemory(true);
			}

			public Documents Documents
			{
				get
				{
					return new Documents(application.GetType().InvokeMember("Documents", BindingFlags.GetProperty, null, application, null));
				}
			}

			public Selection Selection
			{
				get
				{
					return new Selection(application.GetType().InvokeMember("Selection", BindingFlags.GetProperty, null, application, null));
				}
			}

			public Application()
			{
				string sAppProgID = "Word.Application";
				Type tWordObj = Type.GetTypeFromProgID(sAppProgID);
				application = Activator.CreateInstance(tWordObj);
			}
		}

		/// <summary>
		/// Summary description for Documents
		/// </summary>
		public class Documents
		{
			private object documents;

			public Document Add()
			{
				return new Document(documents.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, documents, null));
			}

			public Document Open(string fileName)
			{
				return new Document(documents.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, documents, new object[] {fileName}));
			}

			public void Close()
			{
				documents.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, documents, null);
				Marshal.ReleaseComObject(documents);
				GC.GetTotalMemory(true);
			}

			public Documents(object _documents)
			{
				documents = _documents;
			}
		}

		/// <summary>
		/// Summary description for Document
		/// </summary>
		public class Document
		{
			private object document;

			public void Save()
			{
				document.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, document, null);
			}

			public void SaveAs(string fileName)
			{
				document.GetType().InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, document, new object[]{fileName});
			}

			public void Close()
			{
				document.GetType().InvokeMember("Close", BindingFlags.InvokeMethod, null, document, null);
				Marshal.ReleaseComObject(document);
				GC.GetTotalMemory(true);
			}

			public Document(object _document)
			{
				document = _document;
			}
		}

		/// <summary>
		/// Summary description for Selection
		/// </summary>
		public class Selection
		{
			private object selection;

			public Find Find
			{
				get
				{
					return new Find(selection.GetType().InvokeMember("Find", BindingFlags.GetProperty, null, selection, null));
				}
			}

			public Selection(object _selection)
			{
				selection = _selection;
			}
		}

		/// <summary>
		/// Summary description for Find
		/// </summary>
		public class Find
		{
			private object find;

			public void Execute(object FindText, object MatchCase, object MatchWholeWord, object MatchWildcards, object MatchSoundsLike, object MatchAllWordForms, object Forward, WdFindWrap Wrap, object Format, object ReplaceWith, WdReplace Replace, object MatchKashida, object MatchDiacritics, object MatchAlefHamza, object MatchControl)
			{
				object[] args = new object[15] {FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl};
				find.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, find, args);
			}

			public Font Font
			{
				get
				{
					return new Font(find.GetType().InvokeMember("Font", BindingFlags.GetProperty, null, find, null));
				}
			}

			public Replacement Replacement
			{
				get
				{
					return new Replacement(find.GetType().InvokeMember("Replacement", BindingFlags.GetProperty, null, find, null));
				}
			}

			public Find(object _find)
			{
				find = _find;
			}
		}

		/// <summary>
		/// Summary description for Replacement
		/// </summary>
		public class Replacement
		{
			private object replacement;

			public Font Font
			{
				get
				{
					return new Font(replacement.GetType().InvokeMember("Font", BindingFlags.GetProperty, null, replacement, null));
				}
			}

			public Replacement(object _replacement)
			{
				replacement = _replacement;
			}
		}

		/// <summary>
		/// Summary description for Font
		/// </summary>
		public class Font
		{
			object font;

			public string Name
			{
				get
				{
					return Convert.ToString(font.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, font, null));
				}
				set
				{
					font.GetType().InvokeMember("Name", BindingFlags.SetProperty, null, font, new object[] {value});
				}
			}

			public bool Bold
			{
				get
				{
					return Convert.ToBoolean(font.GetType().InvokeMember("Bold", BindingFlags.GetProperty, null, font, null));
				}
				set
				{
					font.GetType().InvokeMember("Bold", BindingFlags.SetProperty, null, font, new object[] {value});
				}
			}

			public bool Italic
			{
				get
				{
					return Convert.ToBoolean(font.GetType().InvokeMember("Italic", BindingFlags.GetProperty, null, font, null));
				}
				set
				{
					font.GetType().InvokeMember("Italic", BindingFlags.SetProperty, null, font, new object[] {value});
				}
			}

			public Font(object _font)
			{
				font = _font;
			}
		}
	}
}

...
Рейтинг: 0 / 0
Период между сообщениями больше года.
05.03.2008, 18:23
    #35173754
guest1221
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
а как классом myword изменять колонтитулы?
...
Рейтинг: 0 / 0
Период между сообщениями больше года.
05.08.2021, 06:25
    #40088756
Besm1
Гость
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Dragon_Oleg
Здраствуйте Ray Adams

А что делать, если процессы Word размножаются как кролики?
Делаю вот так:

MyWord wrd = new MyWord(true);
wrd.OpenFile(path);
wrd.ShowWord(true);
wrd.SaveDocument();
wrd.CloseDoc();
wrd.ShowWord(false);
wrd.Quit();

А процессы все увеличиваються


Увеличиваются (или размножаются) они ровно потому, что каждый раз ты первой строкой скрипта создаёшь новый процесс, но не убиваешь его после использования. А чтобы убить, надо написать волшебную строку:

wrd = null;
...
Рейтинг: 0 / 0
05.08.2021, 12:09
    #40088840
ЕвгенийВ
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Besm1,
Спасибо от ТС! Он 15 лет ждал ответа.
...
Рейтинг: 0 / 0
05.08.2021, 14:19
    #40088896
Roman Mejtes
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
ЕвгенийВ,

мне вот больше интересно. на сколько этот ответ адекватен и что конкретно дает то, что автор удаляет ссылку на объект? звучит крайне сомнительно
...
Рейтинг: 0 / 0
05.08.2021, 20:14
    #40089009
Сон Веры Павловны
Участник
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Как открыть документ Word из С#
Roman Mejtes
звучит крайне сомнительно

Да, для out-proc COM-сервера это как мертвому припарка. Обычно вызывают последовательность Marshal.ReleaseComObject/GC.Collect/GC.WaitForPendingFinalizers/GC.Collect. И Marshal.ReleaseComObject желательно вызывать не только для экземпляра аппликации (ворда в данном случае), но и для всех COM-объектов библиотеки, с которыми ведется работа. Иначе как минимум будет течь память. Как максимум - останется висеть процесс. Как вспомню, так вздрогну.
...
Рейтинг: 0 / 0
Форумы / WinForms, .Net Framework [игнор отключен] [закрыт для гостей] / Как открыть документ Word из С# / 14 сообщений из 14, страница 1 из 1
Целевая тема:
Создать новую тему:
Автор:
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]