Добавление фото в ячейку таблицы Word
22.12.2021, 19:28. Показов 1285. Ответов 2
Форумчани, всем привет.
Столкнулся с трудностью добавления фото в документ ворд
Суть, есть объединённые две ячейки, куда необходимо добавить фото из picturebox. Код прилагаю, если не трудно просьба показать на нем.
Блок создание документа
| 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
| private void CreateDocument()
{
try
{
Word.Application wordApplication = new Word.Application(); //объявили переменную типа Word
Object template = Type.Missing;
Object newTemplate = Type.Missing;
Object documentType = Type.Missing;
Object visible = Type.Missing;
wordApplication.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);//добавили в проложение документ
Word.Document doc = wordApplication.ActiveDocument;
wordApplication.Visible = true; //делаем что бы word не работал в фоновом режиме
Object r = Type.Missing;
Word.Paragraph par = doc.Content.Paragraphs.Add(ref r);//дабавляем в документ параграф
Object missing = Type.Missing;
Word.Range rng = doc.Range(ref missing, ref missing); //получаем текстовую область параграфа
rng.Tables.Add(doc.Paragraphs[doc.Paragraphs.Count].Range, 15, 2, ref missing, ref missing);//вставляем в текстовую область таблицу
Word.Table tbl = doc.Tables[doc.Tables.Count];//для удобства работы присваиваем таблицу переменной
tbl.Cell(1, 1).Range.Text = Уровень.Text;
tbl.Cell(1, 2).Range.Text = "";
tbl.Rows[1].Cells[1].Merge(tbl.Rows[1].Cells[2]);
tbl.Rows[2].Cells[1].Merge(tbl.Rows[3].Cells[1]);
tbl.Cell(3, 2).Range.Text = "Бригадир" + " " + ФИОбриг.Text;
tbl.Cell(4, 2).Range.Text = "";
tbl.Cell(2, 2).Range.Text = "ФИО" + '\n' + Фамилия.Text + '\n' + Имя.Text + '\n' + Отчество.Text;
tbl.Cell(4, 1).Range.Text = "Дата рождения";
tbl.Cell(4, 2).Range.Text = др.Text;
tbl.Cell(5, 1).Range.Text = "Мобильный телефон";
tbl.Cell(5, 2).Range.Text = Телефон.Text;
tbl.Cell(6, 1).Range.Text = "Место регистрации";
tbl.Cell(6, 2).Range.Text = Рег1.Text + "," + "г." + Рег2.Text + "," + "ул." + Рег3.Text + "," + "д." + Рег4.Text + "," + "кв." + Рег5.Text;
tbl.Cell(7, 1).Range.Text = "Место жительства";
tbl.Cell(7, 2).Range.Text = Прож1.Text + "," + "г." + Прож2.Text + "," + "ул." + Прож3.Text + "," + "д." + Прож4.Text + "," + "кв." + Прож5.Text;
tbl.Cell(8, 1).Range.Text = "Место работы/учебы";
tbl.Cell(8, 2).Range.Text = рабуч.Text;
tbl.Cell(9, 1).Range.Text = "Опыт общественной деятельности";
tbl.Cell(9, 2).Range.Text = Общественная.Text;
tbl.Cell(10, 1).Range.Text = "Vk.com";
tbl.Cell(10, 2).Range.Text = Вконтакте.Text;
tbl.Cell(11, 1).Range.Text = "Instagram.com";
tbl.Cell(11, 2).Range.Text = Instagram.Text;
tbl.Cell(12, 1).Range.Text = "Ok.ru";
tbl.Cell(12, 2).Range.Text = Одноклассники.Text;
tbl.Cell(13, 1).Range.Text = "Facebook.com";
tbl.Cell(13, 2).Range.Text = Facebook.Text;
tbl.Cell(14, 1).Range.Text = "Twitter.com";
tbl.Cell(14, 2).Range.Text = Твиттер.Text;
tbl.Cell(15, 1).Range.Text = "Telegram (ник в мессенджере)";
tbl.Cell(15, 2).Range.Text = Телеграмм.Text;
Word.Border[] borders = new Word.Border[6];//массив бордеров
borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft];//левая граница
borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight];//правая граница
borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop];//нижняя граница
borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom];//верхняя граница
borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal];//горизонтальная граница
borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical];//вертикальная граница
foreach (Word.Border border in borders)
{
border.LineStyle = Word.WdLineStyle.wdLineStyleSingle;//ставим стиль границы
border.Color = Word.WdColor.wdColorBlack;//задаем цвет границы
}
MessageBox.Show("Документ успешно создан", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
} |
|
Весь код
| 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
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
namespace редакторсоздания
{
public partial class Анкета_Активиста_Ф : Form
{
private static string photo_path = null;
private static string file_name = null;
public Анкета_Активиста_Ф()
{
InitializeComponent();
}
private void Формирование_Click(object sender, EventArgs e)
{
if (Телефон.TextLength < 11)
{
MessageBox.Show("Некорректная длина номера телефона", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (Имя.Text != null)
{
CreateDocument();
}
else
{
MessageBox.Show("Все обязательные поля и фотография необходимо заполнить", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void CreateDocument()
{
try
{
Word.Application wordApplication = new Word.Application(); //объявили переменную типа Word
Object template = Type.Missing;
Object newTemplate = Type.Missing;
Object documentType = Type.Missing;
Object visible = Type.Missing;
wordApplication.Documents.Add(ref template, ref newTemplate, ref documentType, ref visible);//добавили в проложение документ
Word.Document doc = wordApplication.ActiveDocument;
wordApplication.Visible = true; //делаем что бы word не работал в фоновом режиме
Object r = Type.Missing;
Word.Paragraph par = doc.Content.Paragraphs.Add(ref r);//дабавляем в документ параграф
Object missing = Type.Missing;
Word.Range rng = doc.Range(ref missing, ref missing); //получаем текстовую область параграфа
rng.Tables.Add(doc.Paragraphs[doc.Paragraphs.Count].Range, 15, 2, ref missing, ref missing);//вставляем в текстовую область таблицу
Word.Table tbl = doc.Tables[doc.Tables.Count];//для удобства работы присваиваем таблицу переменной
tbl.Cell(1, 1).Range.Text = Уровень.Text;
tbl.Cell(1, 2).Range.Text = "";
tbl.Rows[1].Cells[1].Merge(tbl.Rows[1].Cells[2]);
tbl.Rows[2].Cells[1].Merge(tbl.Rows[3].Cells[1]);
tbl.Cell(3, 2).Range.Text = "Бригадир" + " " + ФИОбриг.Text;
tbl.Cell(4, 2).Range.Text = "";
tbl.Cell(2, 2).Range.Text = "ФИО" + '\n' + Фамилия.Text + '\n' + Имя.Text + '\n' + Отчество.Text;
tbl.Cell(4, 1).Range.Text = "Дата рождения";
tbl.Cell(4, 2).Range.Text = др.Text;
tbl.Cell(5, 1).Range.Text = "Мобильный телефон";
tbl.Cell(5, 2).Range.Text = Телефон.Text;
tbl.Cell(6, 1).Range.Text = "Место регистрации";
tbl.Cell(6, 2).Range.Text = Рег1.Text + "," + "г." + Рег2.Text + "," + "ул." + Рег3.Text + "," + "д." + Рег4.Text + "," + "кв." + Рег5.Text;
tbl.Cell(7, 1).Range.Text = "Место жительства";
tbl.Cell(7, 2).Range.Text = Прож1.Text + "," + "г." + Прож2.Text + "," + "ул." + Прож3.Text + "," + "д." + Прож4.Text + "," + "кв." + Прож5.Text;
tbl.Cell(8, 1).Range.Text = "Место работы/учебы";
tbl.Cell(8, 2).Range.Text = рабуч.Text;
tbl.Cell(9, 1).Range.Text = "Опыт общественной деятельности";
tbl.Cell(9, 2).Range.Text = Общественная.Text;
tbl.Cell(10, 1).Range.Text = "Vk.com";
tbl.Cell(10, 2).Range.Text = Вконтакте.Text;
tbl.Cell(11, 1).Range.Text = "Instagram.com";
tbl.Cell(11, 2).Range.Text = Instagram.Text;
tbl.Cell(12, 1).Range.Text = "Ok.ru";
tbl.Cell(12, 2).Range.Text = Одноклассники.Text;
tbl.Cell(13, 1).Range.Text = "Facebook.com";
tbl.Cell(13, 2).Range.Text = Facebook.Text;
tbl.Cell(14, 1).Range.Text = "Twitter.com";
tbl.Cell(14, 2).Range.Text = Твиттер.Text;
tbl.Cell(15, 1).Range.Text = "Telegram (ник в мессенджере)";
tbl.Cell(15, 2).Range.Text = Телеграмм.Text;
Word.Border[] borders = new Word.Border[6];//массив бордеров
borders[0] = tbl.Borders[Word.WdBorderType.wdBorderLeft];//левая граница
borders[1] = tbl.Borders[Word.WdBorderType.wdBorderRight];//правая граница
borders[2] = tbl.Borders[Word.WdBorderType.wdBorderTop];//нижняя граница
borders[3] = tbl.Borders[Word.WdBorderType.wdBorderBottom];//верхняя граница
borders[4] = tbl.Borders[Word.WdBorderType.wdBorderHorizontal];//горизонтальная граница
borders[5] = tbl.Borders[Word.WdBorderType.wdBorderVertical];//вертикальная граница
foreach (Word.Border border in borders)
{
border.LineStyle = Word.WdLineStyle.wdLineStyleSingle;//ставим стиль границы
border.Color = Word.WdColor.wdColorBlack;//задаем цвет границы
}
MessageBox.Show("Документ успешно создан", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
internal bool Process(Dictionary<string, string> items, string photo_path)
{
Word.Application app = null;
Word.InlineShape pic = null;
try
{
Object file = _fileInfo.FullName;
app = new Word.Application();
Document doc = app.Documents.Open(file);
Object missing = Type.Missing;
// app.Documents.Open(file);
Table wdtbl = doc.Tables[1];
Paragraph oPara1 = doc.Content.Paragraphs.Add(wdtbl.Cell(2, 1).Range);
pic = oPara1.Range.InlineShapes.AddPicture(photo_path, false, true, oPara1.Range);
return true;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
finally
{
if (app != null)
{
app.Quit();
}
}
return false;
}
private void Очистка_Click(object sender, EventArgs e)
{
Имя.Clear();
Фамилия.Clear();
Отчество.Clear();
др.Value = DateTime.Now;
Телефон.Clear();
рабуч.Clear();
ФИОбриг.Clear();
Рег1.Clear();
Рег2.Clear();
Рег3.Clear();
Рег4.Clear();
Рег5.Clear();
Прож1.Clear();
Прож2.Clear();
Прож3.Clear();
Прож4.Clear();
Прож5.Clear();
Общественная.Clear();
Твиттер.Clear();
Вконтакте.Clear();
Одноклассники.Clear();
Facebook.Clear();
Instagram.Clear();
Телеграмм.Clear();
Уровень.SelectedIndex = -1;
}
private void Удаление_Click(object sender, EventArgs e)
{
pictureBox1.Image = null;
}
private void Загрузка_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Image Files (*JPG)|*.JPG"; //форматы файлов
if (ofd.ShowDialog() == DialogResult.OK)
photo_path = ofd.FileName;
{
try
{
pictureBox1.Image = new Bitmap(photo_path);
}
catch
{
MessageBox.Show("Невозможно открыть выбранный файл", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
} |
|
0
|