Форум программистов, компьютерный форум, киберфорум
C#: WPF, UWP и Silverlight
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.86/111: Рейтинг темы: голосов - 111, средняя оценка - 4.86
71 / 69 / 19
Регистрация: 13.12.2011
Сообщений: 274

Создание word-отчета (*.doc) в WPF

24.02.2012, 00:52. Показов 22184. Ответов 11
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Какие методики создания файлов формата *.doc есть в VS2010? Попытки поиска адекватного рабочего примера не увенчались успехом. :-(
Сторонние компоненты использовать не хотелось бы.

Добавлено через 1 час 9 минут
Отвечу сам на свой вопрос!
Нашел хороший пример!
Для этого нам надо:
1) Зайти в "Проект" - "Добавить ссылку"
2) На вкладке COM выбрать "Microsoft Word хх.х Object Library"
C#
1
2
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
Если нам не надо закрывать созданный документ - комментируем строки:
C#
1
2
//wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
//wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
...

Далее (пример по клику на кнопку):

C#
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
/// <summary>
        /// TO WORD
        /// </summary>
 
        Word.Application wrdApp;
        Word._Document wrdDoc;
        Object oMissing = System.Reflection.Missing.Value;
        Object oFalse = false;
 
        private void InsertLines(int LineNum)
        {
            int iCount;
 
            // Insert "LineNum" blank lines. 
            for (iCount = 1; iCount <= LineNum; iCount++)
            {
                wrdApp.Selection.TypeParagraph();
            }
        }
 
        private void FillRow(Word._Document oDoc, int Row, string Text1, string Text2, string Text3, string Text4)
        {
            // Insert the data into the specific cell.
            oDoc.Tables[1].Cell(Row, 1).Range.InsertAfter(Text1);
            oDoc.Tables[1].Cell(Row, 2).Range.InsertAfter(Text2);
            oDoc.Tables[1].Cell(Row, 3).Range.InsertAfter(Text3);
            oDoc.Tables[1].Cell(Row, 4).Range.InsertAfter(Text4);
        }
 
        private void button21_Click(object sender, RoutedEventArgs e)
        {
            Word.Selection wrdSelection;
            Word.MailMerge wrdMailMerge;
            Word.MailMergeFields wrdMergeFields;
            Word.Table wrdTable;
            string StrToAdd;
 
            // Create an instance of Word  and make it visible.
            wrdApp = new Word.Application();
            wrdApp.Visible = true;
 
            // Add a new document.
            wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing,
                ref oMissing, ref oMissing);
            wrdDoc.Select();
 
            wrdSelection = wrdApp.Selection;
            wrdMailMerge = wrdDoc.MailMerge;
 
            // Create a MailMerge Data file.
            
            //CreateMailMergeDataFile();
 
            // Create a string and insert it into the document.
            StrToAdd = "State University\r\nElectrical Engineering Department";
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wrdSelection.TypeText(StrToAdd);
 
            InsertLines(4);
 
            // Insert merge data.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wrdMergeFields = wrdMailMerge.Fields;
            wrdMergeFields.Add(wrdSelection.Range, "FirstName");
            wrdSelection.TypeText(" ");
            wrdMergeFields.Add(wrdSelection.Range, "LastName");
            wrdSelection.TypeParagraph();
 
            wrdMergeFields.Add(wrdSelection.Range, "Address");
            wrdSelection.TypeParagraph();
            wrdMergeFields.Add(wrdSelection.Range, "CityStateZip");
 
            InsertLines(2);
 
            // Right justify the line and insert a date field
            // with the current date.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphRight;
 
            Object objDate = "dddd, MMMM dd, yyyy";
            wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing,
                ref oMissing, ref oMissing);
 
            InsertLines(2);
 
            // Justify the rest of the document.
            wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
 
            wrdSelection.TypeText("Dear ");
            wrdMergeFields.Add(wrdSelection.Range, "FirstName");
            wrdSelection.TypeText(",");
            InsertLines(2);
 
            // Create a string and insert it into the document.
            StrToAdd = "Thank you for your recent request for next " +
                "semester's class schedule for the Electrical " +
                "Engineering Department. Enclosed with this " +
                "letter is a booklet containing all the classes " +
                "offered next semester at State University.  " +
                "Several new classes will be offered in the " +
                "Electrical Engineering Department next semester.  " +
                "These classes are listed below.";
            wrdSelection.TypeText(StrToAdd);
 
            InsertLines(2);
 
            // Insert a new table with 9 rows and 4 columns.
            wrdTable = wrdDoc.Tables.Add(wrdSelection.Range, 9, 4,
                ref oMissing, ref oMissing);
            // Set the column widths.
            wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone);
            // Set the shading on the first row to light gray.
            wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex =
                Word.WdColorIndex.wdGray25;
            // Bold the first row.
            wrdTable.Rows[1].Range.Bold = 1;
            // Center the text in Cell (1,1).
            wrdTable.Cell(1, 1).Range.Paragraphs.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
 
            // Fill each row of the table with data.
            FillRow(wrdDoc, 1, "Class Number", "Class Name",
                "Class Time", "Instructor");
            FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II",
                "1:00-2:00 M,W,F", "Dr. Jensen");
            FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I",
                "10:00-11:30 T,T", "Dr. Crump");
            FillRow(wrdDoc, 4, "EE300", "Feedback Control Systems",
                "9:00-10:00 M,W,F", "Dr. Murdy");
            FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design",
                "9:00-10:30 T,T", "Dr. Alley");
            FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems",
                "9:00-10:30 T,T", "Dr. Taylor");
            FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory",
                "1:00-2:30 T,T", "Dr. Lee");
            FillRow(wrdDoc, 8, "EE450", "Plasma Theory",
                "1:00-2:00 M,W,F", "Dr. Davis");
            FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design",
                "3:00-4:00 M,W,F", "Dr. Ellison");
 
            // Go to the end of the document.
            Object oConst1 = Word.WdGoToItem.wdGoToLine;
            Object oConst2 = Word.WdGoToDirection.wdGoToLast;
            wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);
            InsertLines(2);
 
            // Create a string and insert it into the document.
            StrToAdd = "For additional information regarding the " +
                "Department of Electrical Engineering, " +
                "you can visit our Web site at ";
            wrdSelection.TypeText(StrToAdd);
            // Insert a hyperlink to the Web page.
            Object oAddress = "http://www.ee.stateu.tld";
            Object oRange = wrdSelection.Range;
            wrdSelection.Hyperlinks.Add(oRange, ref oAddress, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            // Create a string and insert it into the document
            StrToAdd = ".  Thank you for your interest in the classes " +
                "offered in the Department of Electrical " +
                "Engineering.  If you have any other questions, " +
                "please feel free to give us a call at " +
                "555-1212.\r\n\r\n" +
                "Sincerely,\r\n\r\n" +
                "Kathryn M. Hinsch\r\n" +
                "Department of Electrical Engineering \r\n";
            wrdSelection.TypeText(StrToAdd);
 
            // Perform mail merge.
            //wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
            //wrdMailMerge.Execute(ref oFalse);
 
            wrdDoc.Saved = true;
          
            object fileName = "D:\\daily_report.doc";
            wrdDoc.SaveAs2(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
 
            // Release References.
            wrdSelection = null;
            wrdMailMerge = null;
            wrdMergeFields = null;
            wrdDoc = null;
            wrdApp = null;
 
            // Clean up temp file.
            //System.IO.File.Delete("D:\\DataDoc.doc");
        }
 
        /// <summary>
        /// TO WORD (END)
        /// </summary>
5
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
24.02.2012, 00:52
Ответы с готовыми решениями:

Создание отчетов в формате doc,docx WPF
Добрый день. Такой стал вопрос,созадется приложение что то вроде программы учета,есть в бумажном виде документ куда люди вписывают свои...

Создание отчета .doc / .docx на основе шаблона
Есть шаблон .dot / .dotx, в нем поля с именами. Необходимо из C# создавать файл на основе шаблона, заполнив поля. В рунете никакой свежей...

Создание ms word файла (*.doc) из c++
Как создать документ MS Word средствами с++? Там будет только текстовая часть и таблица с данными.

11
50 / 40 / 5
Регистрация: 30.06.2010
Сообщений: 1,191
07.07.2013, 15:02
ошибка
Ошибка 1 Не удалось найти имя типа или пространства имен "RoutedEventArgs" (пропущена директива using или ссылка на сборку?) c:\users\andrey\documents\visual studio 2012\Projects\WindowsFormsApplication9\W indowsFormsApplication9\Form1.cs 53 52 WindowsFormsApplication9
0
23 / 12 / 2
Регистрация: 23.08.2010
Сообщений: 100
07.07.2013, 18:01
Цитата Сообщение от ProstoMad Посмотреть сообщение
ошибка
ты просто скопировал отсюда? Если да, то создай сам событие нажатия кнопки.
1
50 / 40 / 5
Регистрация: 30.06.2010
Сообщений: 1,191
10.07.2013, 07:18
Вставил код с добавлением колонтитула перед созданием таблицы (перед // Insert a new table with 9 rows and 4 columns.)
C#
1
2
3
4
5
6
7
8
 Microsoft.Office.Interop.Word.Application wapp = new Microsoft.Office.Interop.Word.Application();
            foreach (Microsoft.Office.Interop.Word.Section wordSection in wapp.ActiveDocument.Sections)
            {
                Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
                footerRange.Font.Size = 20;
                footerRange.Text = "Confidential";
            }
показывает ошибку(на скрине)
документ вроди бы открывается до этого куска кода, а закрывается после него... В чём тогда проблема?
Миниатюры
Создание word-отчета (*.doc) в WPF  
0
71 / 69 / 19
Регистрация: 13.12.2011
Сообщений: 274
10.07.2013, 08:22  [ТС]
Цитата Сообщение от ProstoMad Посмотреть сообщение
Вставил код с добавлением колонтитула перед созданием таблицы
Стоп. А где инициализация wapp? Приведенный мною пример не полон. Это только образец.

Вот пример моего проекта:
C#
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
...
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.Windows.Xps.Packaging;
...
 
namespace zakupki_express
{
    /// <summary>
    /// Логика взаимодействия для blank.xaml
    /// </summary>
    public partial class blank : System.Windows.Window
    {
        public blank()
        {
            InitializeComponent();
        }
 
        Word.Application wrdApp;
        Word._Document wrdDoc;
        Object oMissing = System.Reflection.Missing.Value;
        Object oFalse = false;
 
        private void InsertLines(int LineNum)
        {
            int iCount;
 
            // Insert "LineNum" blank lines. 
            for (iCount = 1; iCount <= LineNum; iCount++)
            {
                wrdApp.Selection.TypeParagraph();
            }
        }
 
...
 
private void button21_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                    Word.Selection wrdSelection;
                    Word.MailMerge wrdMailMerge;
                    Word.MailMergeFields wrdMergeFields;
                    Word.Table wrdTable;
                    wrdApp = new Word.Application();
                    wrdApp.Visible = true;
 
                    // Add a new document.
                    wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing,
                        ref oMissing, ref oMissing);
                    wrdDoc.Select();
 
                    wrdApp.Selection.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
 
 
                    wrdSelection = wrdApp.Selection;
                    wrdMailMerge = wrdDoc.MailMerge;
 
                    // Create a string and insert it into the document.    
                    wrdSelection.ParagraphFormat.SpaceAfter = 0;
                    StrToAdd = "Заявка на проведение закупки № \r\nот " + System.DateTime.Now.ToString("dd.MM.yyyy");
                    wrdSelection.ParagraphFormat.Alignment =
                        Word.WdParagraphAlignment.wdAlignParagraphCenter;
                    wrdSelection.Font.Bold = 1;
                    wrdSelection.Font.Size = 16;
                    wrdSelection.Font.Name = "Times New Roman";
                    wrdSelection.ParagraphFormat.LineSpacing = 11;
                    wrdSelection.ParagraphFormat.LineUnitBefore = 0;
                    wrdSelection.TypeText(StrToAdd);
 
                    InsertLines(1);
 
...
 
                    // Go to the end of the document.
                    Object oConst1 = Word.WdGoToItem.wdGoToLine;
                    Object oConst2 = Word.WdGoToDirection.wdGoToLast;
                    wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);
 
...
 
                    wrdDoc.Saved = true;
 
                    object fileName = AppDomain.CurrentDomain.BaseDirectory + "tmp\\izv.doc";
                    wrdDoc.SaveAs2(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                    ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                    wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
                    wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
 
                    // Release References.
                    wrdSelection = null;
                    wrdMailMerge = null;
                    wrdMergeFields = null;
                    wrdDoc = null;
                    wrdApp = null;
            }
            catch (Exception exc)
            {
                MessageBox.Show("Ошибка создания бланка!\n\n" + exc.Message, "Ошибка создания бланка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
 
...
Если будут проблемы - обращайтесь.
0
50 / 40 / 5
Регистрация: 30.06.2010
Сообщений: 1,191
10.07.2013, 09:45
Твой пример у меня работает отлично. Но вставив кусок кода, появляется ошибка. Как можно инициализировать wapp?

Добавлено через 46 секунд
Если что, у меня 13 ворд
0
71 / 69 / 19
Регистрация: 13.12.2011
Сообщений: 274
10.07.2013, 10:19  [ТС]
ProstoMad, скиньте свой проект - я посмотрю.
0
50 / 40 / 5
Регистрация: 30.06.2010
Сообщений: 1,191
10.07.2013, 11:02
C#
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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
namespace WindowsFormsApplication10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Word.Selection wrdSelection;
            Word.MailMerge wrdMailMerge;
            Word.MailMergeFields wrdMergeFields;
            Word.Table wrdTable;
            string StrToAdd;
 
            // Create an instance of Word  and make it visible.
            wrdApp = new Word.Application();
            wrdApp.Visible = true;
 
            // Add a new document.
            wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing,
                ref oMissing, ref oMissing);
            wrdDoc.Select();
 
 
 
 
            wrdSelection = wrdApp.Selection;
            wrdMailMerge = wrdDoc.MailMerge;
 
            // Create a MailMerge Data file.
 
            //CreateMailMergeDataFile();
 
            // Create a string and insert it into the document.
 
            StrToAdd = "State University\r\nElectrical Engineering Department";
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wrdSelection.TypeText(StrToAdd);
 
            InsertLines(4);
 
            // Insert merge data.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wrdMergeFields = wrdMailMerge.Fields;
            wrdMergeFields.Add(wrdSelection.Range, "FirstName");
            wrdSelection.TypeText(" ");
            wrdMergeFields.Add(wrdSelection.Range, "LastName");
            wrdSelection.TypeParagraph();
 
            wrdMergeFields.Add(wrdSelection.Range, "Address");
            wrdSelection.TypeParagraph();
            wrdMergeFields.Add(wrdSelection.Range, "CityStateZip");
 
            InsertLines(2);
 
            // Right justify the line and insert a date field
            // with the current date.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphRight;
 
            Object objDate = "dddd, MMMM dd, yyyy";
            wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing,
                ref oMissing, ref oMissing);
 
            InsertLines(2);
 
            // Justify the rest of the document.
            wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
 
            wrdSelection.TypeText("Dear ");
            wrdMergeFields.Add(wrdSelection.Range, "FirstName");
            wrdSelection.TypeText(",");
            InsertLines(2);
 
            // Create a string and insert it into the document.
            StrToAdd = "Thank you for your recent request for next " +
                "semester's class schedule for the Electrical " +
                "Engineering Department. Enclosed with this " +
                "letter is a booklet containing all the classes " +
                "offered next semester at State University.  " +
                "Several new classes will be offered in the " +
                "Electrical Engineering Department next semester.  " +
                "These classes are listed below.";
            wrdSelection.TypeText(StrToAdd);
 
 
 
 
            InsertLines(2);
 
            Microsoft.Office.Interop.Word.Application wapp = new Microsoft.Office.Interop.Word.Application();
            foreach (Microsoft.Office.Interop.Word.Section wordSection in wapp.ActiveDocument.Sections)
            {
                Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
                footerRange.Font.Size = 20;
                footerRange.Text = "Confidential";
            }
 
 
            // Insert a new table with 9 rows and 4 columns.
            wrdTable = wrdDoc.Tables.Add(wrdSelection.Range, 9, 4,
                ref oMissing, ref oMissing);
            // Set the column widths.
            wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone);
            // Set the shading on the first row to light gray.
            wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex =
                Word.WdColorIndex.wdGray25;
            // Bold the first row.
            wrdTable.Rows[1].Range.Bold = 1;
            // Center the text in Cell (1,1).
            wrdTable.Cell(1, 1).Range.Paragraphs.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
 
            // Fill each row of the table with data.
            FillRow(wrdDoc, 1, "Class Number", "Class Name",
                "Class Time", "Instructor");
            FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II",
                "1:00-2:00 M,W,F", "Dr. Jensen");
            FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I",
                "10:00-11:30 T,T", "Dr. Crump");
            FillRow(wrdDoc, 4, "EE300", "Feedback Control Systems",
                "9:00-10:00 M,W,F", "Dr. Murdy");
            FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design",
                "9:00-10:30 T,T", "Dr. Alley");
            FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems",
                "9:00-10:30 T,T", "Dr. Taylor");
            FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory",
                "1:00-2:30 T,T", "Dr. Lee");
            FillRow(wrdDoc, 8, "EE450", "Plasma Theory",
                "1:00-2:00 M,W,F", "Dr. Davis");
            FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design",
                "3:00-4:00 M,W,F", "Dr. Ellison");
 
            // Go to the end of the document.
            Object oConst1 = Word.WdGoToItem.wdGoToLine;
            Object oConst2 = Word.WdGoToDirection.wdGoToLast;
            wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);
            InsertLines(2);
 
            // Create a string and insert it into the document.
            StrToAdd = "For additional information regarding the " +
                "Department of Electrical Engineering, " +
                "you can visit our Web site at ";
            wrdSelection.TypeText(StrToAdd);
            // Insert a hyperlink to the Web page.
            Object oAddress = "http://www.ee.stateu.tld";
            Object oRange = wrdSelection.Range;
            wrdSelection.Hyperlinks.Add(oRange, ref oAddress, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            // Create a string and insert it into the document
            StrToAdd = ".  Thank you for your interest in the classes " +
                "offered in the Department of Electrical " +
                "Engineering.  If you have any other questions, " +
                "please feel free to give us a call at " +
                "555-1212.\r\n\r\n" +
                "Sincerely,\r\n\r\n" +
                "Kathryn M. Hinsch\r\n" +
                "Department of Electrical Engineering \r\n";
            wrdSelection.TypeText(StrToAdd);
 
            // Perform mail merge.
            //wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
            //wrdMailMerge.Execute(ref oFalse);
 
            
            wrdDoc.Saved = true;
 
            object fileName = "D:\\daily_report.doc";
            wrdDoc.SaveAs2(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
 
            // Release References.
            wrdSelection = null;
            wrdMailMerge = null;
            wrdMergeFields = null;
            wrdDoc = null;
            wrdApp = null;
 
            // Clean up temp file.
            //System.IO.File.Delete("D:\\DataDoc.doc");
            
        }
        Word.Application wrdApp;
        Word._Document wrdDoc;
        Object oMissing = System.Reflection.Missing.Value;
        Object oFalse = false;
 
        private void InsertLines(int LineNum)
        {
            int iCount;
 
            // Insert "LineNum" blank lines. 
            for (iCount = 1; iCount <= LineNum; iCount++)
            {
                wrdApp.Selection.TypeParagraph();
            }
        }
 
        private void FillRow(Word._Document oDoc, int Row, string Text1, string Text2, string Text3, string Text4)
        {
            // Insert the data into the specific cell.
            oDoc.Tables[1].Cell(Row, 1).Range.InsertAfter(Text1);
            oDoc.Tables[1].Cell(Row, 2).Range.InsertAfter(Text2);
            oDoc.Tables[1].Cell(Row, 3).Range.InsertAfter(Text3);
            oDoc.Tables[1].Cell(Row, 4).Range.InsertAfter(Text4);
        }
 
    }
}
0
71 / 69 / 19
Регистрация: 13.12.2011
Сообщений: 274
10.07.2013, 11:07  [ТС]
ProstoMad, лучше весь проект, а не код. Заархивируйте и залейте сюда.
0
50 / 40 / 5
Регистрация: 30.06.2010
Сообщений: 1,191
10.07.2013, 11:20
Вот архив с проектом
Вложения
Тип файла: rar WindowsFormsApplication10.rar (65.6 Кб, 301 просмотров)
0
71 / 69 / 19
Регистрация: 13.12.2011
Сообщений: 274
10.07.2013, 12:09  [ТС]
Вот Ваш рабочий код:
C#
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
private void button1_Click(object sender, EventArgs e)
        {
            Word.Selection wrdSelection;
            Word.MailMerge wrdMailMerge;
            Word.MailMergeFields wrdMergeFields;
            Word.Table wrdTable;
            string StrToAdd;
 
            // Create an instance of Word  and make it visible.
            wrdApp = new Word.Application();
            wrdApp.Visible = true;
 
            // Add a new document.
            wrdDoc = wrdApp.Documents.Add(ref oMissing, ref oMissing,
                ref oMissing, ref oMissing);
            wrdDoc.Select();
 
 
 
 
            wrdSelection = wrdApp.Selection;
            wrdMailMerge = wrdDoc.MailMerge;
 
            // Create a MailMerge Data file.
 
            //CreateMailMergeDataFile();
 
            // Create a string and insert it into the document.
 
            StrToAdd = "State University\r\nElectrical Engineering Department";
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
            wrdSelection.TypeText(StrToAdd);
 
            InsertLines(4);
 
            // Insert merge data.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphLeft;
            wrdMergeFields = wrdMailMerge.Fields;
            wrdMergeFields.Add(wrdSelection.Range, "FirstName");
            wrdSelection.TypeText(" ");
            wrdMergeFields.Add(wrdSelection.Range, "LastName");
            wrdSelection.TypeParagraph();
 
            wrdMergeFields.Add(wrdSelection.Range, "Address");
            wrdSelection.TypeParagraph();
            wrdMergeFields.Add(wrdSelection.Range, "CityStateZip");
 
            InsertLines(2);
 
            // Right justify the line and insert a date field
            // with the current date.
            wrdSelection.ParagraphFormat.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphRight;
 
            Object objDate = "dddd, MMMM dd, yyyy";
            wrdSelection.InsertDateTime(ref objDate, ref oFalse, ref oMissing,
                ref oMissing, ref oMissing);
 
            InsertLines(2);
 
            // Justify the rest of the document.
            wrdSelection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphJustify;
 
            wrdSelection.TypeText("Dear ");
            wrdMergeFields.Add(wrdSelection.Range, "FirstName");
            wrdSelection.TypeText(",");
            InsertLines(2);
 
            // Create a string and insert it into the document.
            StrToAdd = "Thank you for your recent request for next " +
                "semester's class schedule for the Electrical " +
                "Engineering Department. Enclosed with this " +
                "letter is a booklet containing all the classes " +
                "offered next semester at State University.  " +
                "Several new classes will be offered in the " +
                "Electrical Engineering Department next semester.  " +
                "These classes are listed below.";
            wrdSelection.TypeText(StrToAdd);
 
 
 
 
            InsertLines(2);
 
            //Microsoft.Office.Interop.Word.Application wapp = new Microsoft.Office.Interop.Word.Application();
            foreach (Microsoft.Office.Interop.Word.Section wordSection in wrdApp.ActiveDocument.Sections)
            {
                Word.Range footerRange = wordSection.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
                footerRange.Font.ColorIndex = Word.WdColorIndex.wdDarkRed;
                footerRange.Font.Size = 20;
                footerRange.Text = "Confidential";
            }
 
 
            // Insert a new table with 9 rows and 4 columns.
            wrdTable = wrdDoc.Tables.Add(wrdSelection.Range, 9, 4,
                ref oMissing, ref oMissing);
            // Set the column widths.
            wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone);
            wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone);
            // Set the shading on the first row to light gray.
            wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex =
                Word.WdColorIndex.wdGray25;
            // Bold the first row.
            wrdTable.Rows[1].Range.Bold = 1;
            // Center the text in Cell (1,1).
            wrdTable.Cell(1, 1).Range.Paragraphs.Alignment =
                Word.WdParagraphAlignment.wdAlignParagraphCenter;
 
            // Fill each row of the table with data.
            FillRow(wrdDoc, 1, "Class Number", "Class Name",
                "Class Time", "Instructor");
            FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II",
                "1:00-2:00 M,W,F", "Dr. Jensen");
            FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I",
                "10:00-11:30 T,T", "Dr. Crump");
            FillRow(wrdDoc, 4, "EE300", "Feedback Control Systems",
                "9:00-10:00 M,W,F", "Dr. Murdy");
            FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design",
                "9:00-10:30 T,T", "Dr. Alley");
            FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems",
                "9:00-10:30 T,T", "Dr. Taylor");
            FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory",
                "1:00-2:30 T,T", "Dr. Lee");
            FillRow(wrdDoc, 8, "EE450", "Plasma Theory",
                "1:00-2:00 M,W,F", "Dr. Davis");
            FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design",
                "3:00-4:00 M,W,F", "Dr. Ellison");
 
            // Go to the end of the document.
            Object oConst1 = Word.WdGoToItem.wdGoToLine;
            Object oConst2 = Word.WdGoToDirection.wdGoToLast;
            wrdApp.Selection.GoTo(ref oConst1, ref oConst2, ref oMissing, ref oMissing);
            InsertLines(2);
 
            // Create a string and insert it into the document.
            StrToAdd = "For additional information regarding the " +
                "Department of Electrical Engineering, " +
                "you can visit our Web site at ";
            wrdSelection.TypeText(StrToAdd);
            // Insert a hyperlink to the Web page.
            Object oAddress = "http://www.ee.stateu.tld";
            Object oRange = wrdSelection.Range;
            wrdSelection.Hyperlinks.Add(oRange, ref oAddress, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            // Create a string and insert it into the document
            StrToAdd = ".  Thank you for your interest in the classes " +
                "offered in the Department of Electrical " +
                "Engineering.  If you have any other questions, " +
                "please feel free to give us a call at " +
                "555-1212.\r\n\r\n" +
                "Sincerely,\r\n\r\n" +
                "Kathryn M. Hinsch\r\n" +
                "Department of Electrical Engineering \r\n";
            wrdSelection.TypeText(StrToAdd);
 
            // Perform mail merge.
            //wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
            //wrdMailMerge.Execute(ref oFalse);
 
 
            wrdDoc.Saved = true;
 
            object fileName = "D:\\daily_report.doc";
            wrdDoc.SaveAs2(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                            ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
            //wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);
            //wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
 
            // Release References.
            wrdSelection = null;
            wrdMailMerge = null;
            wrdMergeFields = null;
            wrdDoc = null;
            wrdApp = null;
 
            // Clean up temp file.
            //System.IO.File.Delete("D:\\DataDoc.doc");
 
        }
Косяк был в
C#
1
2
//Microsoft.Office.Interop.Word.Application wapp = new Microsoft.Office.Interop.Word.Application();
foreach (Microsoft.Office.Interop.Word.Section wordSection in wrdApp.ActiveDocument.Sections)
Инициализация wapp не нужна, т.к. у Вас уж есть wrdApp.
Подправили соответственно:
foreach (Microsoft.Office.Interop.Word.Section wordSection in wapp.ActiveDocument.Sections)
на
foreach (Microsoft.Office.Interop.Word.Section wordSection in wrdApp.ActiveDocument.Sections)
Удачи!

P.S. Однако пишите на WinForm, но вопросы в ветке WPF...
1
50 / 40 / 5
Регистрация: 30.06.2010
Сообщений: 1,191
10.07.2013, 12:32
Цитата Сообщение от SmirnoFF.Oleg Посмотреть сообщение
Однако пишите на WinForm, но вопросы в ветке WPF...
ну на сколько я понимаю тут это не имеет значение. Зачем создавать много тем, когда есть похожая.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
10.07.2013, 12:32
Помогаю со студенческими работами здесь

Создание отчета в Word
Нужно перенести все отчеты в ворд. У меня что-то не выходит

Создание отчета в MS WORD
Всем здравствуйте! У меня такой вопрос. Как сделать что бы определенная информация из моей программы занеслась в word -овский документ....

Создание отчета Word
Как сделать отчет word так чтобы данные брались из datagridview, и вставлялись в шаблон word. Допустим нужно чтобы отчет представлял...

Создание отчета в Word
может кто сталкивался. создаю документ Word, проблема в том, что после его закрытия ругается на сервер... т.е. выдает ошибку &quot;сервер...

Создание отчёта в Word
Здравствуйте, пожалуйста, подскажите, как создать отчёт не в QuickRep, а в Word. Причем он должен содержать от каждой формы информацию...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
12
Ответ Создать тему
Новые блоги и статьи
Как писать чистый, тестируемый и качественный код на Python
py-thonny 12.07.2025
Помню свой первый проект на Python. Работал тогда быстро, грязно, лишь бы работало. Код был похож на запутанный клубок - переменные по одной букве, функции на 200 строк, комментарии отсутствовали как. . .
Blazor и контроллер сервопривода IoT Meadow Maple
Wired 11.07.2025
Я решил разобраться, как можно соединить современные веб-технологии с миром "железа". Интересная комбинация получилась из Blazor в качестве веб-интерфейса и микроконтроллера Meadow с его веб-сервером. . .
Генерация OpenQASM из кода Q#
EggHead 10.07.2025
Летом 2024-го я начал эксперименты с библиотекой Q# Bridge, и знаете что? Она оказалась просто находкой для тех, кто работает на стыке разных квантовых экосистем. Основная фишка этой библиотеки -. . .
Изучаем новый шаблон ИИ-чата .NET AI Chat Web App
stackOverflow 10.07.2025
В . NET появилось интересное обновление - новый шаблон ИИ-чата под названием . NET AI Chat Web App. Когда я впервые наткнулся на анонс этого шаблона, то сразу понял, что Microsoft наконец-то. . .
Результаты исследования от команды ARP (июль 2025 г.)
Programma_Boinc 10.07.2025
Результаты исследования от команды ARP (июль 2025 г. ) Африканский проект по дождям (ARP) World Community Grid снова запущен! Мы рады поделиться обновленной информацией о нашем прогрессе с осени. . .
Angular vs Svelte - что лучше?
Reangularity 09.07.2025
Сегодня рынок разделился на несколько четких категорий: тяжеловесы корпоративного уровня (Angular), гибкие универсалы (React), прогрессивные решения (Vue) и новая волна компилируемых фреймворков. . .
Code First и Database First в Entity Framework
UnmanagedCoder 09.07.2025
Entity Framework дает нам свободу выбора, предлагая как Code First, так и Database First подходы. Но эта свобода порождает вечный вопрос — какой подход выбрать? Entity Framework — это. . .
Как использовать Bluetooth-модуль HC-05 с Arduino
Wired 08.07.2025
Bluetooth - это технология, созданная чтобы заменить кабельные соединения. Обычно ее используют для связи небольших устройств: мобильных телефонов, ноутбуков, наушников и т. д. Работает она на частоте. . .
Руководство по структурам данных Python
AI_Generated 08.07.2025
Я отчетливо помню свои первые серьезные проекты на Python - я писал код, он работал, заказчики были относительно довольны. Но однажды мой наставник, взглянув на мою реализацию поиска по огромному. . .
Тестирование энергоэффективности и скорости вычислений видеокарт в BOINC проектах
Programma_Boinc 08.07.2025
Тестирование энергоэффективности и скорости вычислений видеокарт в BOINC проектах Опубликовано: 07. 07. 2025 Рубрика: Uncategorized Автор: AlexA Статья размещается на сайте с разрешения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru