Given the following C# code, for generate the word file: using System.Xml.Linq; using…
- User
Given the following C# code, for generate the word file: using System.Xml.Linq; using DocumentFormat.OpenXml.Office2010.Word; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using SharpCompress.Compressors.ADC; using static ProSmart.Dtos.Base.WorkflowService.SdaRouteItemBase; using Checked = DocumentFormat.OpenXml.Office2010.Word.Checked;
namespace ReportConsole { public class WordReportGenerator : IDisposable { private WordprocessingDocument doc; private bool disposedValue; private Stream docStream;
public WordReportGenerator(Stream template) { docStream = template; doc = WordprocessingDocument.Open(template, true); } public void FillRealTable(string tableName, List<List<string>> tableData, int startRow, int startCol) { // Get the main document part and body. var body = doc.MainDocumentPart.Document.Body; var table = body.Descendants<Table>() .FirstOrDefault(tbl => { var firstRow = tbl.Descendants<TableRow>().FirstOrDefault(); if (firstRow == null) return false; // Check the first cell (column 1). var firstCell = firstRow.Descendants<TableCell>().FirstOrDefault(); if (firstCell != null && firstCell.InnerText != null && firstCell.InnerText.Contains(tableName)) { return true; } // If column 1 doesn't contain the name, check the second cell (column 2). var secondCell = firstRow.Descendants<TableCell>().Skip(1).FirstOrDefault(); // Skip the first cell. if (secondCell != null && secondCell.InnerText != null && secondCell.InnerText.Contains(tableName)) { return true; } // If column 1 doesn't contain the name, check the second cell (column 2). var thirdCell = firstRow.Descendants<TableCell>().Skip(2).FirstOrDefault(); // Skip the first cell. if (thirdCell != null && thirdCell.InnerText != null && thirdCell.InnerText.Contains(tableName)) { return true; } return false; // Return false if neither column contains the tableName. }); if (table != null) { // Retrieve all rows in the table. var rows = table.Descendants<TableRow>().ToList(); // Use the last row or a specific row as the template for new rows. var templateRow = rows.LastOrDefault(); // Start filling data at the specified row and column. int dataRowIndex = 0; for (int rowIndex = startRow; rowIndex < tableData.Count + startRow; rowIndex++) // Start from startRow. { TableRow currentRow; if (rowIndex >= rows.Count) { // Clone the template row for new rows if necessary. currentRow = (TableRow)templateRow.CloneNode(true); table.AppendChild(currentRow); // Append the new row to the table. } else { // Use the existing row. currentRow = rows[rowIndex]; } var cells = currentRow.Descendants<TableCell>().ToList(); for (int colIndex = startCol; colIndex < tableData[dataRowIndex].Count + startCol; colIndex++) // Start from startCol. { int dataColIndex = colIndex - startCol; // Adjust column index for data. if (colIndex >= cells.Count) { // Add a new cell if necessary. var newCell = (TableCell)templateRow.Descendants<TableCell>().LastOrDefault()?.CloneNode(true) ?? new TableCell(new Paragraph(new Run(new Text("")))); currentRow.AppendChild(newCell); } // Set the text content of the cell. var cell = currentRow.Descendants<TableCell>().ElementAt(colIndex); var paragraph = cell.GetFirstChild<Paragraph>() ?? cell.AppendChild(new Paragraph()); var run = paragraph.GetFirstChild<Run>() ?? paragraph.AppendChild(new Run()); string text_from_data = tableData[dataRowIndex][dataColIndex]; string[] text_split_for_newline = text_from_data.Split( new string[] { Environment.NewLine }, StringSplitOptions.None ); if (text_split_for_newline.Length > 1) { foreach (var text_break in text_split_for_newline) { run.AppendChild(new Text(text_break)); run.AppendChild(new Break()); } } else { var text = run.GetFirstChild<Text>() ?? run.AppendChild(new Text()); text.Text = text_from_data; } } dataRowIndex++; // Increment to process the next row of data. } } } public void CheckboxItems(Dictionary<string, bool> checkList) { // var body = doc.MainDocumentPart.Document.Body; foreach (var paragraph in body.Descendants<Paragraph>()) { var runs = paragraph.Descendants<Run>(); foreach (var run in runs) { foreach (var item in checkList) { if (run.InnerText.Contains(item.Key)) // Found the target text matching the key. { var textElement = run.GetFirstChild<Text>(); if (textElement != null) { textElement.Remove(); if (item.Value) { var symbolElement = new SymbolChar { Char = "F052", Font = "Wingdings 2" }; run.AppendChild(symbolElement); } else { var symbolElement = new SymbolChar { Char = "F0A3", Font = "Wingdings 2" }; run.AppendChild(symbolElement); } } // Save the document after processing this occurrence. break; } } } } } private SdtBlock CreateCheckBox(bool isChecked) { SdtBlock sdtBlock = null; if (isChecked) { sdtBlock = new SdtBlock( new SdtProperties( new SdtAlias { Val = "Checkbox" }, new Tag { Val = "CheckBoxTag" }, new SdtContentCheckBox // Define the checkbox functionality. { Checked = new Checked { Val = OnOffValues.True } // Initially set to checked. } ), new SdtContentBlock( new Paragraph( new Run( new Text("☒") ) ) ) ); } else { sdtBlock = new SdtBlock( new SdtProperties( new SdtAlias { Val = "Checkbox" }, new Tag { Val = "CheckBoxTag" }, new SdtContentCheckBox() // This is where you define the checkbox functionality. ), new SdtContentBlock( new Paragraph( new Run( new Text("☐") ) ) ) ); } return sdtBlock; } public void ReplaceHolder(Dictionary<string, string> placeHolders) { var body = doc.MainDocumentPart.Document.Body; foreach (var paragraph in body.Descendants<Paragraph>()) { var runs = paragraph.Descendants<Run>().ToList(); var textElements = paragraph.Descendants<Text>().ToList(); for (int i = 0; i < textElements.Count; i++) { foreach (var placeholder in placeHolders) { if (textElements[i].Text.Contains(placeholder.Key)) { string text_from_data = placeholder.Value; string[] text_split_for_newline = text_from_data.Split( new string[] { Environment.NewLine }, StringSplitOptions.None ); if (text_split_for_newline.Length > 1) { textElements[i].Text = ""; foreach (var text_break in text_split_for_newline) { runs[0].AppendChild(new Text(text_break)); runs[0].AppendChild(new Break()); } } else { textElements[i].Text = textElements[i].Text.Replace(placeholder.Key, placeholder.Value); } // Replace placeholder text directly in the Text element } } } } } public void Save(MemoryStream outputStream) { doc.Save(); docStream.Position = 0; docStream.CopyTo(outputStream); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { doc.Dispose(); } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~WordReportGenerator() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } } - Assistant
- User
Create the new function for duplicate page with range from template based on the functionDuplicatePageFromTemplate
- Assistant