commit try create table
This commit is contained in:
parent
cc45235f69
commit
12c7f4caff
@ -1,9 +1,7 @@
|
||||
using ComponentsView;
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection.Metadata;
|
||||
using static System.Net.Mime.MediaTypeNames;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab;
|
||||
|
||||
|
||||
namespace ComponentsLibrary
|
||||
@ -25,25 +23,28 @@ namespace ComponentsLibrary
|
||||
//публичный метод
|
||||
public void SetText(string fileUrl, string fileName, string[] text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(fileUrl) || string.IsNullOrEmpty(fileName))
|
||||
{
|
||||
throw new ArgumentException("File URL or filename cannot be empty.");
|
||||
}
|
||||
|
||||
// Создаем новый документ Word и сохраняем его по указанному пути
|
||||
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(Path.Combine(fileUrl, fileName), WordprocessingDocumentType.Document))
|
||||
{
|
||||
// Добавляем главный документ
|
||||
|
||||
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
|
||||
mainPart.Document = new Document();
|
||||
Body body = new Body();
|
||||
|
||||
// Добавляем текст в документ
|
||||
|
||||
foreach (var line in text)
|
||||
{
|
||||
Paragraph paragraph = new Paragraph(new Run(new Text(line)));
|
||||
body.Append(paragraph);
|
||||
}
|
||||
|
||||
// Заключаем тело документа
|
||||
|
||||
mainPart.Document.Append(body);
|
||||
mainPart.Document.Save(); // Сохраняем изменения в документе
|
||||
mainPart.Document.Save();
|
||||
}
|
||||
|
||||
}
|
||||
|
36
ComponentsLibrary/ComponentTable.Designer.cs
generated
Normal file
36
ComponentsLibrary/ComponentTable.Designer.cs
generated
Normal file
@ -0,0 +1,36 @@
|
||||
namespace ComponentsLibrary
|
||||
{
|
||||
partial class ComponentTable
|
||||
{
|
||||
/// <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
|
||||
}
|
||||
}
|
111
ComponentsLibrary/ComponentTable.cs
Normal file
111
ComponentsLibrary/ComponentTable.cs
Normal file
@ -0,0 +1,111 @@
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Wordprocessing;
|
||||
using System.ComponentModel;
|
||||
|
||||
|
||||
namespace ComponentsLibrary
|
||||
{
|
||||
public partial class ComponentTable : Component
|
||||
{
|
||||
public ComponentTable()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public ComponentTable(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public void CreateDocument(string filePath, DocumentTable<T> documentTable)
|
||||
{
|
||||
ValidateInput(documentTable);
|
||||
|
||||
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
|
||||
{
|
||||
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
|
||||
mainPart.Document = new Document();
|
||||
Body body = new Body();
|
||||
|
||||
// Добавление заголовка
|
||||
Paragraph titleParagraph = new Paragraph(new Run(new Text(documentTable.DocumentTitle)));
|
||||
body.Append(titleParagraph);
|
||||
|
||||
// Создание таблицы
|
||||
Table table = new Table();
|
||||
CreateHeaderRows(documentTable, table);
|
||||
FillTableData(documentTable, table);
|
||||
|
||||
body.Append(table);
|
||||
mainPart.Document.Append(body);
|
||||
mainPart.Document.Save();
|
||||
}
|
||||
}
|
||||
|
||||
private void ValidateInput(DocumentTable<T> documentTable)
|
||||
{
|
||||
// Проводим проверки на заполненность и соответствие
|
||||
if (string.IsNullOrEmpty(documentTable.DocumentTitle))
|
||||
throw new ArgumentException("Заголовок документа не может быть пустым.");
|
||||
|
||||
if (documentTable.Headers == null || documentTable.Headers.Count == 0 || documentTable.PropertyMappings == null || documentTable.PropertyMappings.Count == 0)
|
||||
throw new ArgumentException("Заголовки и отображения свойств должны быть заполнены.");
|
||||
|
||||
if (documentTable.Data == null || !documentTable.Data.Any())
|
||||
throw new ArgumentException("Данные таблицы не могут быть пустыми.");
|
||||
|
||||
// Проверка на некорректные столбцы объединения
|
||||
foreach (var column in documentTable.MergedColumns)
|
||||
{
|
||||
if (column < 0 || column >= documentTable.Headers.Count)
|
||||
throw new ArgumentOutOfRangeException($"Неверный номер объединяемого столбца: {column}");
|
||||
}
|
||||
|
||||
// Проверка, что все заголовки заполнены
|
||||
foreach (var header in documentTable.Headers)
|
||||
{
|
||||
if (string.IsNullOrEmpty(header))
|
||||
throw new ArgumentException("Все заголовки должны быть заполнены.");
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateHeaderRows(DocumentTable<T> documentTable, Table table)
|
||||
{
|
||||
// Создаем две строки заголовков
|
||||
for (int rowIndex = 0; rowIndex < 2; rowIndex++)
|
||||
{
|
||||
TableRow headerRow = new TableRow();
|
||||
for (int colIndex = 0; colIndex < documentTable.Headers.Count; colIndex++)
|
||||
{
|
||||
TableCell cell = new TableCell(new Paragraph(new Run(new Text(documentTable.Headers[colIndex]))));
|
||||
if (!documentTable.MergedColumns.Contains(colIndex))
|
||||
{
|
||||
// Объединяем ячейку по строкам
|
||||
cell.VerticalMerge = new TableCellVerticalMerge();
|
||||
}
|
||||
|
||||
headerRow.Append(cell);
|
||||
}
|
||||
table.Append(headerRow);
|
||||
}
|
||||
}
|
||||
|
||||
private void FillTableData(DocumentTable<T> documentTable, Table table)
|
||||
{
|
||||
// Заполнение данных таблицы
|
||||
foreach (var item in documentTable.Data)
|
||||
{
|
||||
TableRow dataRow = new TableRow();
|
||||
for (int colIndex = 0; colIndex < documentTable.PropertyMappings.Count; colIndex++)
|
||||
{
|
||||
var propertyValue = typeof(T).GetProperty(documentTable.PropertyMappings[colIndex])?.GetValue(item, null);
|
||||
TableCell cell = new TableCell(new Paragraph(new Run(new Text(propertyValue?.ToString() ?? string.Empty))));
|
||||
dataRow.Append(cell);
|
||||
}
|
||||
table.Append(dataRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -7,4 +7,8 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -1,12 +1,12 @@
|
||||
namespace ComponentsView
|
||||
{
|
||||
public class DocumentEntry
|
||||
public class DocumentSymple
|
||||
{
|
||||
public string FileUrl { get; set; } = string.Empty;
|
||||
public string FileName { get; set; } = string.Empty;
|
||||
public string[] Text { get; set; }
|
||||
|
||||
public DocumentEntry(string fileUrl, string fileName, string[] text)
|
||||
public DocumentSymple(string fileUrl, string fileName, string[] text)
|
||||
{
|
||||
FileUrl = fileUrl;
|
||||
FileName = fileName;
|
31
ComponentsLibrary/DocumentTable.cs
Normal file
31
ComponentsLibrary/DocumentTable.cs
Normal file
@ -0,0 +1,31 @@
|
||||
|
||||
namespace ComponentsLibrary
|
||||
{
|
||||
public class DocumentTable<T>
|
||||
{
|
||||
public string DocumentTitle { get; set; } = string.Empty;
|
||||
public string DocumentPath { get; set; } = string.Empty;
|
||||
public List<int> MergedColumns { get; set; }
|
||||
public List<double> ColumnWidths { get; set; }
|
||||
public List<string> Headers { get; set; }
|
||||
public List<T> Data { get; set; }
|
||||
public List<string> PropertyMappings { get; set; }
|
||||
|
||||
public DocumentTable(string documentTitle,
|
||||
string documentPath,
|
||||
List<int> mergedColumns,
|
||||
List<double> columnWidths,
|
||||
List<string> headers,
|
||||
List<T> data,
|
||||
List<string> propertyMappings)
|
||||
{
|
||||
DocumentTitle = documentTitle;
|
||||
DocumentPath = documentPath;
|
||||
MergedColumns = mergedColumns;
|
||||
ColumnWidths = columnWidths;
|
||||
Headers = headers;
|
||||
Data = data;
|
||||
PropertyMappings = propertyMappings;
|
||||
}
|
||||
}
|
||||
}
|
29
ComponentsView/FormComponents.Designer.cs
generated
29
ComponentsView/FormComponents.Designer.cs
generated
@ -35,6 +35,10 @@
|
||||
componentBigText = new ComponentsLibrary.ComponentBigText(components);
|
||||
richTextBoxWord = new RichTextBox();
|
||||
buttonSaveTextWord = new Button();
|
||||
componentTable = new ComponentsLibrary.ComponentTable(components);
|
||||
dataGridViewTable = new DataGridView();
|
||||
buttonSaveTable = new Button();
|
||||
((System.ComponentModel.ISupportInitialize)dataGridViewTable).BeginInit();
|
||||
SuspendLayout();
|
||||
//
|
||||
// richTextBoxTest
|
||||
@ -73,17 +77,39 @@
|
||||
buttonSaveTextWord.UseVisualStyleBackColor = true;
|
||||
buttonSaveTextWord.Click += buttonSaveTextWord_Click;
|
||||
//
|
||||
// dataGridViewTable
|
||||
//
|
||||
dataGridViewTable.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
|
||||
dataGridViewTable.Location = new Point(12, 143);
|
||||
dataGridViewTable.Name = "dataGridViewTable";
|
||||
dataGridViewTable.RowTemplate.Height = 25;
|
||||
dataGridViewTable.Size = new Size(350, 167);
|
||||
dataGridViewTable.TabIndex = 4;
|
||||
//
|
||||
// buttonSaveTable
|
||||
//
|
||||
buttonSaveTable.Location = new Point(12, 316);
|
||||
buttonSaveTable.Name = "buttonSaveTable";
|
||||
buttonSaveTable.Size = new Size(350, 23);
|
||||
buttonSaveTable.TabIndex = 5;
|
||||
buttonSaveTable.Text = "Сохранить";
|
||||
buttonSaveTable.UseVisualStyleBackColor = true;
|
||||
buttonSaveTable.Click += buttonSaveTable_Click;
|
||||
//
|
||||
// FormComponents
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(800, 450);
|
||||
Controls.Add(buttonSaveTable);
|
||||
Controls.Add(dataGridViewTable);
|
||||
Controls.Add(buttonSaveTextWord);
|
||||
Controls.Add(richTextBoxWord);
|
||||
Controls.Add(buttonSaveText);
|
||||
Controls.Add(richTextBoxTest);
|
||||
Name = "FormComponents";
|
||||
Text = "Form1";
|
||||
((System.ComponentModel.ISupportInitialize)dataGridViewTable).EndInit();
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
@ -95,5 +121,8 @@
|
||||
private ComponentsLibrary.ComponentBigText componentBigText;
|
||||
private RichTextBox richTextBoxWord;
|
||||
private Button buttonSaveTextWord;
|
||||
private ComponentsLibrary.ComponentTable componentTable;
|
||||
private DataGridView dataGridViewTable;
|
||||
private Button buttonSaveTable;
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,14 @@
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ComponentsView
|
||||
{
|
||||
public partial class FormComponents : Form
|
||||
{
|
||||
|
||||
public FormComponents()
|
||||
{
|
||||
InitializeComponent();
|
||||
testComponent.FileName = "2.txt";
|
||||
InitializeDataGridView();
|
||||
}
|
||||
|
||||
private void buttonSaveText_Click(object sender, EventArgs e)
|
||||
@ -27,7 +29,60 @@ namespace ComponentsView
|
||||
|
||||
private void buttonSaveTextWord_Click(object sender, EventArgs e)
|
||||
{
|
||||
componentBigText.SetText(string.Empty);
|
||||
try
|
||||
{
|
||||
var docEntry = new DocumentSymple(@"C:\Users\Natalia\Desktop\5semestr\KOP\KOP-PIbd-32-Katysheva-N-E\docs", "Word.docx", richTextBoxWord.Lines);
|
||||
componentBigText.SetText(docEntry.FileUrl, docEntry.FileName, docEntry.Text);
|
||||
MessageBox.Show("Ñîõàðíåíî óñïåøíî", "Ðåçóëüòàò",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Îøèáêà!",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void InitializeDataGridView()
|
||||
{
|
||||
dataGridViewTable.Columns.Add("Column1", "Íàçâàíèå");
|
||||
dataGridViewTable.Columns.Add("Column2", "Çíà÷åíèå");
|
||||
|
||||
// Äîáàâüòå íåêîòîðûå òåñòîâûå äàííûå
|
||||
dataGridViewTable.Rows.Add("Òåñò1", "Çíà÷åíèå1");
|
||||
dataGridViewTable.Rows.Add("Òåñò2", "Çíà÷åíèå2");
|
||||
}
|
||||
|
||||
private void buttonSaveTable_Click(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
List<string[]> data = new List<string[]>();
|
||||
|
||||
// Èçâëå÷åíèå äàííûõ èç DataGridView
|
||||
foreach (DataGridViewRow row in dataGridViewTable.Rows)
|
||||
{
|
||||
if (row.IsNewRow) continue; // Ïðîïóñòèòü ïóñòóþ ñòðîêó
|
||||
string[] rowData = new string[dataGridViewTable.Columns.Count];
|
||||
for (int i = 0; i < dataGridViewTable.Columns.Count; i++)
|
||||
{
|
||||
rowData[i] = row.Cells[i].Value?.ToString() ?? string.Empty;
|
||||
}
|
||||
data.Add(rowData);
|
||||
}
|
||||
|
||||
// Ñîçäàíèå äîêóìåíòà ñ äàííûìè èç òàáëèöû
|
||||
var docEntry = new DocumentSymple(@"C:\Users\Natalia\Desktop\5semestr\KOP\KOP-PIbd-32-Katysheva-N-E\docs", "Table.docx", data.Select(row => string.Join("\t", row)).ToArray());
|
||||
componentBigText.SetText(docEntry.FileUrl, docEntry.FileName, docEntry.Text);
|
||||
|
||||
MessageBox.Show("Ñîõðàíåíî óñïåøíî", "Ðåçóëüòàò",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Îøèáêà!",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -123,4 +123,7 @@
|
||||
<metadata name="componentBigText.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>154, 17</value>
|
||||
</metadata>
|
||||
<metadata name="componentTable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>308, 17</value>
|
||||
</metadata>
|
||||
</root>
|
Loading…
Reference in New Issue
Block a user