private ExcelTemplate RetreiveTemplate(string name, byte[] body) { #warning Order and for each Entity entity = null; object entityID, attributeID, formatID; Teleform.Reporting.Attribute attribute = null; var placeholders = GetExcelPlaceHolders(body); if (placeholders.Count == 0) { throw new Exception("Указанный файл не содержит шаблон."); } var fields = new List <TemplateField>(); var creatorID = new Teleform.Reporting.UniqueIDCreator(); creatorID.Split(placeholders.First().ID, out entityID, out attributeID, out formatID); entity = Global.Schema.Entities.FirstOrDefault(o => o.ID.ToString() == entityID.ToString()); foreach (var holder in placeholders) { creatorID.Split(holder.ID, out entityID, out attributeID, out formatID); attribute = entity.Attributes.FirstOrDefault(o => o.ID.ToString() == attributeID.ToString()); if (attribute == null) { throw new InvalidOperationException( string.Format("Сущность '{0}' не имеет атрибут с идентификатором {1}.", entity.Name, attributeID)); } var field = new TemplateField(attribute); field.Format = attribute.Type.GetAdmissableFormats().FirstOrDefault(o => o.ID.ToString() == formatID.ToString()); if (field.Format == null) { throw new InvalidOperationException( string.Format("Тип '{0}' атрибута {1} не имеет формат с идентификатором {2}.", attribute.Type.Name, attribute.Name, formatID)); } field.Name = holder.Alias; fields.Add(field); } #warning sheetName var template = new Teleform.Reporting.MicrosoftOffice.ExcelTemplate(name, entity, "ExcelBased", body, fields, "Лист1"); return(template); }
public void Create(Stream output, GroupReport report) { #if f if (output == null) { throw new ArgumentNullException("output", Message.Get("Common.NullArgument", "output")); } if (report == null) { throw new ArgumentNullException("report", Message.Get("Common.NullArgument", "report")); } #endif // Открываем содержимое в памяти. var content = report.Template.Content; using (var memory = new MemoryStream()) { memory.Write(content, 0, (int)content.Length); try { Document = WordprocessingDocument.Open(memory, true); Document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); } #warning TODO Посмотреть актуальные исключения на операции. catch (Exception ex) { throw new InvalidOperationException("Возникла ошибка при чтении тела шаблона.\n", ex.InnerException); } var properties = report.Instances.First().TelefReprotProperties; var baseProperties = report.Instances.First().OwnProperties; bool useBaseProperties = baseProperties != null; // Получаем список закладок... var placeholders = Document.ContentControls(); if (placeholders.Count() == 0) { Document.Close(); throw new InvalidOperationException("В теле шаблона не найдено Structured Document Tag элементов."); } foreach (var placeholder in placeholders) { var placeholderId = placeholder.GetSdtTagText(); object entityId, hashedAttributeId, formatId; var uid = new UniqueIDCreator(); uid.Split(placeholderId, out entityId, out hashedAttributeId, out formatId); // В случае отсутствия value - оставлять элемент с оригинальным текстом, но выделять красным шрифтом. if (!useBaseProperties) { if (properties.First(x => x.Field.Attribute.ID.ToString() == hashedAttributeId.ToString()).Value == null) { (placeholder as SdtElement).SetSdtTextColor("FF0000"); } else { // Заполняем try { var value = properties .Where( x => (x.Field.Attribute.ID.ToString() == hashedAttributeId.ToString()) && (x.Field.Format.ID.ToString() == formatId.ToString()) ) .First().Value; var element = placeholder as SdtElement; element.SetSdtText(value.ToString()); element.SetSdtTextColor("000000"); } catch (InvalidOperationException ex) { Document.Close(); throw new InvalidOperationException(String.Format("Не удалось найти атрибут.\n{0}.", ex.Message)); } } } else { var property = baseProperties.SingleOrDefault(x => x.Attribute.ID.ToString() == hashedAttributeId.ToString()); if (property == null || property.Value == null || property.Value is DBNull) { (placeholder as SdtElement).SetSdtTextColor("FF0000"); } else { try { var element = placeholder as SdtElement; var format = property.Attribute.Type.GetAdmissableFormats(). First(o => o.ID.ToString() == formatId.ToString()); element.SetSdtText(string.Format(format.Provider, format.FormatString, property.Value)); element.SetSdtTextColor("000000"); } catch (InvalidOperationException ex) { Document.Close(); throw new InvalidOperationException(String.Format("Не удалось найти атрибут.\n{0}.", ex.Message)); } } } #warning Неплохо бы выводить сведения о хеше. } Document.Close(); // Результат - пишем в поток. try { memory.Seek(0, SeekOrigin.Begin); memory.CopyTo(output); } catch (NotSupportedException ex) { throw new InvalidOperationException(String.Format("Поток назначения не поддерживает запись:\n{0}.", ex.Message)); } catch (ObjectDisposedException ex) { throw new InvalidOperationException(String.Format("Поток назначения был преждевременно закрыт:\n{0}.", ex.Message)); } catch (IOException ex) { throw new InvalidOperationException(String.Format("Возникла общая ошибка ввода-вывода:\n{0}.", ex.Message)); } } }