Made word table component
This commit is contained in:
parent
502eb76c23
commit
973a9d37d2
36
NevaevaLibrary/NevaevaLibrary/LogicalComponents/WordTableComponent.Designer.cs
generated
Normal file
36
NevaevaLibrary/NevaevaLibrary/LogicalComponents/WordTableComponent.Designer.cs
generated
Normal file
@ -0,0 +1,36 @@
|
||||
namespace NevaevaLibrary.LogicalComponents
|
||||
{
|
||||
partial class WordTableComponent
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -0,0 +1,171 @@
|
||||
using Microsoft.Office.Interop.Word;
|
||||
using Microsoft.VisualBasic;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace NevaevaLibrary.LogicalComponents
|
||||
{
|
||||
public partial class WordTableComponent : Component
|
||||
{
|
||||
public WordTableComponent()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public WordTableComponent(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private object missing = System.Reflection.Missing.Value;
|
||||
|
||||
public void createWithTable<T>(string path, string title, List<(int, int)> merges, List<int> widths, List<(string, string)> headers, List<T> items)
|
||||
{
|
||||
if (merges.Count == 0 || widths.Count == 0 || headers.Count == 0 || items.Count == 0) throw new ArgumentException("Недостаточно данных");
|
||||
int[] cellsArray = new int[widths.Count];
|
||||
foreach (var merge in merges)
|
||||
{
|
||||
if (merge.Item1 >= merge.Item2) throw new ArgumentException("Неправильно заполнены объединения строк");
|
||||
for (int i = merge.Item1; i < merge.Item2 + 1; i++)
|
||||
{
|
||||
cellsArray[i]++;
|
||||
}
|
||||
}
|
||||
foreach (int cell in cellsArray)
|
||||
{
|
||||
if (cell > 1) throw new ArgumentException("Объединения заходят друг на друга");
|
||||
}
|
||||
|
||||
var winword = new Microsoft.Office.Interop.Word.Application();
|
||||
var document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
|
||||
document.PageSetup.RightMargin = 50;
|
||||
document.PageSetup.LeftMargin = 50;
|
||||
document.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
|
||||
|
||||
var header = document.Content.Paragraphs.Add(Type.Missing);
|
||||
header.Range.Text = title;
|
||||
header.Format.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
|
||||
header.Range.Font.Name = "Times New Roman";
|
||||
header.Range.Font.Size = 22;
|
||||
header.Range.Font.Bold = 2;
|
||||
header.Format.SpaceAfter = 18;
|
||||
header.Range.InsertParagraphAfter();
|
||||
|
||||
var table = document.Tables.Add(document.Bookmarks.get_Item("\\endofdoc").Range,
|
||||
items.Count + 2, widths.Count, Type.Missing, Type.Missing);
|
||||
table.Borders.Enable = 1;
|
||||
|
||||
for (int i = 0; i < widths.Count; i++)
|
||||
{
|
||||
table.Cell(1, i + 1).Width = widths[i];
|
||||
table.Cell(1, i + 1).Height = 20;
|
||||
table.Cell(2, i + 1).Width = widths[i];
|
||||
table.Cell(2, i + 1).Height = 20;
|
||||
}
|
||||
|
||||
//checks
|
||||
List<Cell> ranges = new List<Cell>();
|
||||
foreach (var merge in merges)
|
||||
{
|
||||
ranges.Add(table.Rows[1].Cells[merge.Item1 + 1]);
|
||||
}
|
||||
|
||||
//number of merged cell
|
||||
int rangeIndex = 0;
|
||||
//number of cell
|
||||
int headerIndex = 0;
|
||||
List<FieldInfo> cellFields = new List<FieldInfo>();
|
||||
var type = typeof(T);
|
||||
for (int i = 0; i < widths.Count; i++)
|
||||
{
|
||||
if (cellsArray[i] == 1)
|
||||
{
|
||||
//work with merge
|
||||
if (!string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
|
||||
|
||||
var headerCell = ranges[rangeIndex];
|
||||
headerCell.Range.Text = headers[headerIndex].Item2;
|
||||
headerCell.Range.Font.Size = 11;
|
||||
headerIndex++;
|
||||
|
||||
//work with cells in merge
|
||||
for (; i <= merges[rangeIndex].Item2; i++)
|
||||
{
|
||||
//work with cell
|
||||
if (string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
|
||||
var field = type.GetField(headers[headerIndex].Item1);
|
||||
if (field == null) throw new ArgumentException("В заголовках указано поле, которого нет в переданном классе");
|
||||
//format header
|
||||
var cell = table.Cell(2, i + 1);
|
||||
cell.Range.Text = headers[headerIndex].Item2;
|
||||
cell.Width = widths[i];
|
||||
cell.Range.Font.Size = 11;
|
||||
|
||||
cellFields.Add(field);
|
||||
headerIndex++;
|
||||
}
|
||||
i--;
|
||||
rangeIndex++;
|
||||
}
|
||||
else
|
||||
{
|
||||
//work with cell
|
||||
if (string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
|
||||
var field = type.GetField(headers[headerIndex].Item1);
|
||||
if (field == null) throw new ArgumentException("В заголовках указано поле, которого нет в переданном классе");
|
||||
//format header
|
||||
var cell = table.Cell(1, i + 1);
|
||||
|
||||
cell.Merge(table.Cell(2, i + 1));
|
||||
cell.Range.Text = headers[headerIndex].Item2;
|
||||
cell.Width = widths[i];
|
||||
cell.Range.Font.Size = 11;
|
||||
|
||||
cellFields.Add(field);
|
||||
headerIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
int xOffset = 0;
|
||||
foreach (var merge in merges)
|
||||
{
|
||||
table.Cell(1, merge.Item1 + 1 - xOffset).Merge(table.Cell(1, merge.Item2 + 1 - xOffset));
|
||||
xOffset += merge.Item2 - merge.Item1;
|
||||
}
|
||||
|
||||
int rowNum = 3;
|
||||
foreach (T item in items)
|
||||
{
|
||||
int columnNum = 1;
|
||||
foreach (var cellField in cellFields)
|
||||
{
|
||||
var cell = table.Cell(rowNum, columnNum);
|
||||
cell.Range.Text = cellField.GetValue(item)?.ToString();
|
||||
cell.Width = widths[columnNum - 1];
|
||||
cell.Range.Bold = 0;
|
||||
cell.Range.Font.Size = 11;
|
||||
cell.Height = 20;
|
||||
|
||||
columnNum++;
|
||||
}
|
||||
rowNum++;
|
||||
}
|
||||
|
||||
document.SaveAs(path, Type.Missing, Type.Missing, Type.Missing,
|
||||
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
|
||||
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
|
||||
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
|
||||
document.Close(ref missing, ref missing, ref missing);
|
||||
document = null;
|
||||
winword.Quit(ref missing, ref missing, ref missing);
|
||||
}
|
||||
}
|
||||
}
|
15
NevaevaLibrary/TestApp/FormTest.Designer.cs
generated
15
NevaevaLibrary/TestApp/FormTest.Designer.cs
generated
@ -42,6 +42,8 @@
|
||||
this.buttonWordText = new System.Windows.Forms.Button();
|
||||
this.wordLongTextComponent = new NevaevaLibrary.LogicalComponents.WordLongTextComponent(this.components);
|
||||
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
|
||||
this.buttonTable = new System.Windows.Forms.Button();
|
||||
this.wordTableComponent = new NevaevaLibrary.LogicalComponents.WordTableComponent(this.components);
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// comboBoxControl
|
||||
@ -154,11 +156,22 @@
|
||||
//
|
||||
this.openFileDialog.FileName = "openFileDialog1";
|
||||
//
|
||||
// buttonTable
|
||||
//
|
||||
this.buttonTable.Location = new System.Drawing.Point(178, 319);
|
||||
this.buttonTable.Name = "buttonTable";
|
||||
this.buttonTable.Size = new System.Drawing.Size(145, 29);
|
||||
this.buttonTable.TabIndex = 11;
|
||||
this.buttonTable.Text = "Word (таблица)";
|
||||
this.buttonTable.UseVisualStyleBackColor = true;
|
||||
this.buttonTable.Click += new System.EventHandler(this.buttonTable_Click);
|
||||
//
|
||||
// FormTest
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.ClientSize = new System.Drawing.Size(1109, 363);
|
||||
this.Controls.Add(this.buttonTable);
|
||||
this.Controls.Add(this.buttonWordText);
|
||||
this.Controls.Add(this.buttonGetSelectedList);
|
||||
this.Controls.Add(this.buttonInsertList);
|
||||
@ -191,5 +204,7 @@
|
||||
private Button buttonWordText;
|
||||
private NevaevaLibrary.LogicalComponents.WordLongTextComponent wordLongTextComponent;
|
||||
private OpenFileDialog openFileDialog;
|
||||
private Button buttonTable;
|
||||
private NevaevaLibrary.LogicalComponents.WordTableComponent wordTableComponent;
|
||||
}
|
||||
}
|
@ -77,5 +77,28 @@ namespace TestApp
|
||||
wordLongTextComponent.createWithLongText(new WordLongTextInfo(path, "Header", paragraphs));
|
||||
MessageBox.Show("Готово!");
|
||||
}
|
||||
|
||||
private void buttonTable_Click(object sender, EventArgs e)
|
||||
{
|
||||
List<OfficeWorker> workers = new List<OfficeWorker>();
|
||||
|
||||
workers.Add(new OfficeWorker(1, "Иванов", "Иван", 20, "Отдел продаж", "Бухгалтер", 25, "+7(834)234-03-49"));
|
||||
workers.Add(new OfficeWorker(2, "Петров", "Петр", 25, "Отдел продаж", "Менеджер", 20, "+7(834)123-03-49"));
|
||||
workers.Add(new OfficeWorker(3, "Сидоров", "Сергей", 27, "Отдел кадров", "HR", 2, "+7(834)593-03-49", true));
|
||||
string path = AppDomain.CurrentDomain.BaseDirectory + "test2.docx";
|
||||
List<(int, int)> merges = new List<(int, int)>();
|
||||
merges.Add((1, 3));
|
||||
merges.Add((4, 6));
|
||||
List<int> widths = Enumerable.Repeat(70, 8).ToList();
|
||||
|
||||
List<(string, string)> headers = new List<(string, string)> { ("id", "id"), ("", "Личные данные"),
|
||||
("lastName", "Фамилия"), ("firstName", "Имя"),
|
||||
("age", "Возраст"), ("", "Работа"),
|
||||
("department", "Отдел"), ("position", "Должность"),
|
||||
("boxNumber", "Номер бокса"), ("phoneNumber", "Телефон")};
|
||||
|
||||
wordTableComponent.createWithTable(path, "header", merges, widths, headers, workers);
|
||||
MessageBox.Show("Готово!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -63,4 +63,7 @@
|
||||
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>248, 17</value>
|
||||
</metadata>
|
||||
<metadata name="wordTableComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>407, 17</value>
|
||||
</metadata>
|
||||
</root>
|
34
NevaevaLibrary/TestApp/OfficeWorker.cs
Normal file
34
NevaevaLibrary/TestApp/OfficeWorker.cs
Normal file
@ -0,0 +1,34 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TestApp
|
||||
{
|
||||
public class OfficeWorker
|
||||
{
|
||||
public OfficeWorker(int id, string lastName, string firstName, int age, string department, string position, int boxNumber, string phoneNumber, bool isInVacation = false)
|
||||
{
|
||||
this.id = id;
|
||||
this.lastName = lastName;
|
||||
this.firstName = firstName;
|
||||
this.age = age;
|
||||
this.department = department;
|
||||
this.position = position;
|
||||
this.boxNumber = boxNumber;
|
||||
this.phoneNumber = phoneNumber;
|
||||
this.isInVacation = isInVacation;
|
||||
}
|
||||
|
||||
public int id;
|
||||
public string lastName;
|
||||
public string firstName;
|
||||
public int age;
|
||||
public string department;
|
||||
public string position;
|
||||
public int boxNumber;
|
||||
public string phoneNumber;
|
||||
public bool isInVacation;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user