/// <summary> /// Apply a cell style to a specific cell /// </summary> /// <param name="worksheet">worksheet containing the cell to be affected</param> /// <param name="fromColumn">Starting Cell Column</param> /// <param name="toColumn">Ending Cell Column</param> /// <param name="fromRow">Starting Cell Row</param> /// <param name="toRow">Ending Cell Row</param> /// <param name="cellStyle">Cell Style</param> public static OpenXmlPowerToolsDocument SetCellStyle(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int fromRow, int toRow, string cellStyle) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (short col = fromColumn; col <= toColumn; col++) { XElement cellXelement = GetCell(worksheetXDocument, col, row); cellXelement.SetAttributeValue("s", SpreadSheetStyleAccessor.GetCellStyleIndex(document, cellStyle)); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return(streamDoc.GetModifiedDocument()); } }
/// <summary> /// Set the width for a range of columns /// </summary> /// <param name="worksheet">Worksheet containing the columns to be affected</param> /// <param name="fromColumn">Initial column to affect</param> /// <param name="toColumn">Final column to affect</param> /// <param name="width">Column width</param> public static OpenXmlPowerToolsDocument SetColumnWidth(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int width) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); //Get the worksheet markup XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); //Look for worksheet cols element XElement colsXElement = worksheetXDocument.Root.Element(ns + "cols"); if (colsXElement == null) { //cols elements does not exist //create a new one colsXElement = new XElement(ns + "cols"); //create a new col element (for setting the width) //the col element could span more than one column -span is controlled by min (initial column) and max (final column) attributes colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); //cols element must be added before worksheet sheetData element worksheetXDocument.Root.Element(ns + "sheetData").AddBeforeSelf(colsXElement); } else { //look for a col element for the column range indicated for fromColumn and toColumn XElement colXElement = colsXElement.Elements(ns + "col") .Where(c => (System.Convert.ToInt32(c.Attribute("min").Value) == fromColumn) && (System.Convert.ToInt32(c.Attribute("max").Value) == toColumn)).FirstOrDefault(); if (colXElement != null) { //col element does exist //change its width value colXElement.SetAttributeValue("width", width); } else { //col element does not exist //create a new one colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); } } //Update the worksheet part markup at worksheet part stream XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return(streamDoc.GetModifiedDocument()); } }
public static IEnumerable <ValidationErrorInfo> GetOpenXmlValidationErrors(string fileName, string officeVersion) { #if !NET35 FileFormatVersions fileFormatVersion = FileFormatVersions.Office2013; #else FileFormatVersions fileFormatVersion = FileFormatVersions.Office2010; #endif try { fileFormatVersion = (FileFormatVersions)Enum.Parse(fileFormatVersion.GetType(), officeVersion); } catch (Exception) { #if !NET35 fileFormatVersion = FileFormatVersions.Office2013; #else fileFormatVersion = FileFormatVersions.Office2010; #endif } FileInfo fi = new FileInfo(fileName); if (Util.IsWordprocessingML(fi.Extension)) { WmlDocument wml = new WmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wml)) using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return(errors.ToList()); } } else if (Util.IsSpreadsheetML(fi.Extension)) { SmlDocument Sml = new SmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Sml)) using (SpreadsheetDocument wDoc = streamDoc.GetSpreadsheetDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return(errors.ToList()); } } else if (Util.IsPresentationML(fi.Extension)) { PmlDocument Pml = new PmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Pml)) using (PresentationDocument wDoc = streamDoc.GetPresentationDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return(errors.ToList()); } } return(Enumerable.Empty <ValidationErrorInfo>()); }
// *********************************************************************************************************************************** #region PublicApis public static XElement ConvertTableToHtml(SmlDocument smlDoc, SmlToHtmlConverterSettings settings, string tableName) { using (MemoryStream ms = new MemoryStream()) { ms.Write(smlDoc.DocumentByteArray, 0, smlDoc.DocumentByteArray.Length); using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(ms, false)) { var rangeXml = SmlDataRetriever.RetrieveTable(sDoc, tableName); var xhtml = SmlToHtmlConverter.ConvertToHtmlInternal(sDoc, settings, rangeXml); return(xhtml); } } }
public static IEnumerable <ValidationErrorInfo> GetOpenXmlValidationErrors(string fileName, string officeVersion) { FileFormatVersions fileFormatVersion; if (!Enum.TryParse(officeVersion, out fileFormatVersion)) { fileFormatVersion = FileFormatVersions.Office2013; } FileInfo fi = new FileInfo(fileName); if (Util.IsWordprocessingML(fi.Extension)) { WmlDocument wml = new WmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wml)) using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return(errors.ToList()); } } else if (Util.IsSpreadsheetML(fi.Extension)) { SmlDocument Sml = new SmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Sml)) using (SpreadsheetDocument wDoc = streamDoc.GetSpreadsheetDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return(errors.ToList()); } } else if (Util.IsPresentationML(fi.Extension)) { PmlDocument Pml = new PmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Pml)) using (PresentationDocument wDoc = streamDoc.GetPresentationDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return(errors.ToList()); } } return(Enumerable.Empty <ValidationErrorInfo>()); }
public static XElement GetMetrics(string fileName, MetricsGetterSettings settings) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) throw new FileNotFoundException("{0} does not exist.", fi.FullName); if (Util.IsWordprocessingML(fi.Extension)) { WmlDocument wmlDoc = new WmlDocument(fi.FullName, true); return GetDocxMetrics(wmlDoc, settings); } if (Util.IsSpreadsheetML(fi.Extension)) { SmlDocument smlDoc = new SmlDocument(fi.FullName, true); return GetXlsxMetrics(smlDoc, settings); } if (Util.IsPresentationML(fi.Extension)) { PmlDocument pmlDoc = new PmlDocument(fi.FullName, true); return GetPptxMetrics(pmlDoc, settings); } return null; }
/// <summary> /// Set the value for a specific cell /// </summary> /// <param name="worksheet">Worksheet part containing the cell to be affected</param> /// <param name="fromColumn">Initial column for setting the value</param> /// <param name="fromRow">Initial row for setting the value</param> /// <param name="toColumn">Final column for setting the value</param> /// <param name="toRow">Final row for setting the value</param> /// <param name="value">Cell value</param> public static OpenXmlPowerToolsDocument SetCellValue(SmlDocument doc, string worksheetName, int fromRow, int toRow, int fromColumn, int toColumn, string value) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (int col = fromColumn; col <= toColumn; col++) { AddValue(worksheetXDocument, row, col, value); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return(streamDoc.GetModifiedDocument()); } }
public static IEnumerable<ValidationErrorInfo> GetOpenXmlValidationErrors(string fileName, string officeVersion) { #if !NET35 FileFormatVersions fileFormatVersion = FileFormatVersions.Office2013; #else FileFormatVersions fileFormatVersion = FileFormatVersions.Office2010; #endif try { fileFormatVersion = (FileFormatVersions)Enum.Parse(fileFormatVersion.GetType(), officeVersion); } catch (Exception) { #if !NET35 fileFormatVersion = FileFormatVersions.Office2013; #else fileFormatVersion = FileFormatVersions.Office2010; #endif } FileInfo fi = new FileInfo(fileName); if (Util.IsWordprocessingML(fi.Extension)) { WmlDocument wml = new WmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wml)) using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return errors.ToList(); } } else if (Util.IsSpreadsheetML(fi.Extension)) { SmlDocument Sml = new SmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Sml)) using (SpreadsheetDocument wDoc = streamDoc.GetSpreadsheetDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return errors.ToList(); } } else if (Util.IsPresentationML(fi.Extension)) { PmlDocument Pml = new PmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Pml)) using (PresentationDocument wDoc = streamDoc.GetPresentationDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return errors.ToList(); } } return Enumerable.Empty<ValidationErrorInfo>(); }
public static XElement GetXlsxMetrics(SmlDocument smlDoc, MetricsGetterSettings settings) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(smlDoc)) { using (SpreadsheetDocument sDoc = streamDoc.GetSpreadsheetDocument()) { List<XElement> metrics = new List<XElement>(); bool valid = ValidateAgainstSpecificVersion(sDoc, metrics, DocumentFormat.OpenXml.FileFormatVersions.Office2007, H.SdkValidationError2007); valid |= ValidateAgainstSpecificVersion(sDoc, metrics, DocumentFormat.OpenXml.FileFormatVersions.Office2010, H.SdkValidationError2010); #if !NET35 valid |= ValidateAgainstSpecificVersion(sDoc, metrics, DocumentFormat.OpenXml.FileFormatVersions.Office2013, H.SdkValidationError2013); #endif return new XElement(H.Metrics, new XAttribute(H.FileName, smlDoc.FileName), new XAttribute(H.FileType, "SpreadsheetML"), metrics, GetTableInfoForWorkbook(sDoc, settings)); } } }
/// <summary> /// Method for adding a new table definition part /// </summary> /// <param name="worksheet">Worksheet to add the table to</param> /// <param name="tableStyle">Style to be assigned to the table</param> /// <param name="useHeaders">Set a header row</param> /// <param name="fromColumn">Initial column for table</param> /// <param name="toColumn">Final column for table</param> /// <param name="fromRow">Intial row for table</param> /// <param name="toRow">Final row for table</param> public static OpenXmlPowerToolsDocument Add(SmlDocument doc, string worksheetName, string tableStyle, bool useHeaders, short fromColumn, short toColumn, int fromRow, int toRow) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { //Getting the id for this table int tableId = GetNextTableId(document); //Set the table cell range string tableRange = string.Format("{0}{1}:{2}{3}", WorksheetAccessor.GetColumnId(fromColumn), fromRow, WorksheetAccessor.GetColumnId(toColumn), toRow); //Creating a new id for the relationship between the table definition part and the worksheet string tableRelationShipId = "rId" + Guid.NewGuid(); //Create a new table definition part WorksheetPart worksheet = WorksheetAccessor.Get(document, worksheetName); TableDefinitionPart table = worksheet.AddNewPart<TableDefinitionPart>(tableRelationShipId); //string tableColumns = string.Empty; XElement tableColumnsXElement = new XElement(ns + "tableColumns", new XAttribute("count", (toColumn - fromColumn) + 1)); //Get the name for table column elements from the first table row string[] tableHeaders = GetTableHeaders(document, worksheet, fromRow, fromColumn, toColumn); for (int i = 0; i <= (toColumn - fromColumn); i++) { //Create the markup for the SpreadsheetML table column elements tableColumnsXElement.Add( new XElement(ns + "tableColumn", new XAttribute("id", i + 1), new XAttribute("name", tableHeaders[i]))); } XElement tableXElement = new XElement(ns + "table", new XAttribute("xmlns", ns), //default namespace new XAttribute("id", tableId), new XAttribute("name", "Table" + tableId.ToString()), new XAttribute("displayName", "Table" + tableId.ToString()), new XAttribute("ref", tableRange), new XAttribute("totalsRowShown", "0")); if (useHeaders) { tableXElement.Add( new XElement(ns + "autoFilter", new XAttribute("ref", tableRange))); } tableXElement.Add(tableColumnsXElement); tableXElement.Add( new XElement(ns + "tableStyleInfo", new XAttribute("name", tableStyle), new XAttribute("showFirstColumn", "0"), new XAttribute("showLastColumn", "0"), new XAttribute("showRowStripes", "0"), new XAttribute("showColumnStripes", "0"))); //Write the markup to the Table Definition Part Stream XmlWriter tablePartStreamWriter = XmlWriter.Create(table.GetStream()); tableXElement.WriteTo(tablePartStreamWriter); tablePartStreamWriter.Flush(); tablePartStreamWriter.Close(); //Create or modify the table parts definition at worksheet (for setting the relationship id with the new table) XDocument worksheetMarkup = worksheet.GetXDocument(); //Look for the tableParts element at worksheet markup XElement tablePartsElement = worksheetMarkup.Root.Element(ns + "tableParts"); if (tablePartsElement != null) { //tableParts elements does exist at worksheet markup //increment the tableParts count attribute value short tableCount = System.Convert.ToInt16(tablePartsElement.Attribute("count").Value); tablePartsElement.SetAttributeValue("count", tableCount++.ToString()); } else { //tableParts does not exist at worksheet markup //create a new tableParts element tablePartsElement = new XElement(ns + "tableParts", new XAttribute(ns + "count", "1")); worksheetMarkup.Root.Add(tablePartsElement); } //create the tablePart element XElement tablePartEntryElement = new XElement(ns + "tablePart", new XAttribute(relationshipns + "id", tableRelationShipId)); //add the new tablePart element to the worksheet tableParts element tablePartsElement.Add(tablePartEntryElement); worksheet.PutXDocument(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Method for adding a new table definition part /// </summary> /// <param name="worksheet">Worksheet to add the table to</param> /// <param name="tableStyle">Style to be assigned to the table</param> /// <param name="useHeaders">Set a header row</param> /// <param name="fromColumn">Initial column for table</param> /// <param name="toColumn">Final column for table</param> /// <param name="fromRow">Intial row for table</param> /// <param name="toRow">Final row for table</param> public static OpenXmlPowerToolsDocument Add(SmlDocument doc, string worksheetName, string tableStyle, bool useHeaders, short fromColumn, short toColumn, int fromRow, int toRow) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { //Getting the id for this table int tableId = GetNextTableId(document); //Set the table cell range string tableRange = string.Format("{0}{1}:{2}{3}", WorksheetAccessor.GetColumnId(fromColumn), fromRow, WorksheetAccessor.GetColumnId(toColumn), toRow); //Creating a new id for the relationship between the table definition part and the worksheet string tableRelationShipId = "rId" + Guid.NewGuid(); //Create a new table definition part WorksheetPart worksheet = WorksheetAccessor.Get(document, worksheetName); TableDefinitionPart table = worksheet.AddNewPart <TableDefinitionPart>(tableRelationShipId); //string tableColumns = string.Empty; XElement tableColumnsXElement = new XElement(ns + "tableColumns", new XAttribute("count", (toColumn - fromColumn) + 1)); //Get the name for table column elements from the first table row string[] tableHeaders = GetTableHeaders(document, worksheet, fromRow, fromColumn, toColumn); for (int i = 0; i <= (toColumn - fromColumn); i++) { //Create the markup for the SpreadsheetML table column elements tableColumnsXElement.Add( new XElement(ns + "tableColumn", new XAttribute("id", i + 1), new XAttribute("name", tableHeaders[i]))); } XElement tableXElement = new XElement(ns + "table", new XAttribute("xmlns", ns), //default namespace new XAttribute("id", tableId), new XAttribute("name", "Table" + tableId.ToString()), new XAttribute("displayName", "Table" + tableId.ToString()), new XAttribute("ref", tableRange), new XAttribute("totalsRowShown", "0")); if (useHeaders) { tableXElement.Add( new XElement(ns + "autoFilter", new XAttribute("ref", tableRange))); } tableXElement.Add(tableColumnsXElement); tableXElement.Add( new XElement(ns + "tableStyleInfo", new XAttribute("name", tableStyle), new XAttribute("showFirstColumn", "0"), new XAttribute("showLastColumn", "0"), new XAttribute("showRowStripes", "0"), new XAttribute("showColumnStripes", "0"))); //Write the markup to the Table Definition Part Stream XmlWriter tablePartStreamWriter = XmlWriter.Create(table.GetStream()); tableXElement.WriteTo(tablePartStreamWriter); tablePartStreamWriter.Flush(); tablePartStreamWriter.Close(); //Create or modify the table parts definition at worksheet (for setting the relationship id with the new table) XDocument worksheetMarkup = worksheet.GetXDocument(); //Look for the tableParts element at worksheet markup XElement tablePartsElement = worksheetMarkup.Root.Element(ns + "tableParts"); if (tablePartsElement != null) { //tableParts elements does exist at worksheet markup //increment the tableParts count attribute value short tableCount = System.Convert.ToInt16(tablePartsElement.Attribute("count").Value); tablePartsElement.SetAttributeValue("count", tableCount++.ToString()); } else { //tableParts does not exist at worksheet markup //create a new tableParts element tablePartsElement = new XElement(ns + "tableParts", new XAttribute(ns + "count", "1")); worksheetMarkup.Root.Add(tablePartsElement); } //create the tablePart element XElement tablePartEntryElement = new XElement(ns + "tablePart", new XAttribute(relationshipns + "id", tableRelationShipId)); //add the new tablePart element to the worksheet tableParts element tablePartsElement.Add(tablePartEntryElement); worksheet.PutXDocument(); } return(streamDoc.GetModifiedDocument()); } }
public static IEnumerable<ValidationErrorInfo> GetOpenXmlValidationErrors(string fileName, string officeVersion) { FileFormatVersions fileFormatVersion; if (!Enum.TryParse(officeVersion, out fileFormatVersion)) fileFormatVersion = FileFormatVersions.Office2013; FileInfo fi = new FileInfo(fileName); if (Util.IsWordprocessingML(fi.Extension)) { WmlDocument wml = new WmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wml)) using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return errors.ToList(); } } else if (Util.IsSpreadsheetML(fi.Extension)) { SmlDocument Sml = new SmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Sml)) using (SpreadsheetDocument wDoc = streamDoc.GetSpreadsheetDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return errors.ToList(); } } else if (Util.IsPresentationML(fi.Extension)) { PmlDocument Pml = new PmlDocument(fileName); using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Pml)) using (PresentationDocument wDoc = streamDoc.GetPresentationDocument()) { OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion); var errors = validator.Validate(wDoc); return errors.ToList(); } } return Enumerable.Empty<ValidationErrorInfo>(); }
/// <summary> /// Set the width for a range of columns /// </summary> /// <param name="worksheet">Worksheet containing the columns to be affected</param> /// <param name="fromColumn">Initial column to affect</param> /// <param name="toColumn">Final column to affect</param> /// <param name="width">Column width</param> public static OpenXmlPowerToolsDocument SetColumnWidth(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int width) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); //Get the worksheet markup XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); //Look for worksheet cols element XElement colsXElement = worksheetXDocument.Root.Element(ns + "cols"); if (colsXElement == null) { //cols elements does not exist //create a new one colsXElement = new XElement(ns + "cols"); //create a new col element (for setting the width) //the col element could span more than one column -span is controlled by min (initial column) and max (final column) attributes colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); //cols element must be added before worksheet sheetData element worksheetXDocument.Root.Element(ns + "sheetData").AddBeforeSelf(colsXElement); } else { //look for a col element for the column range indicated for fromColumn and toColumn XElement colXElement = colsXElement.Elements(ns + "col") .Where(c => (System.Convert.ToInt32(c.Attribute("min").Value) == fromColumn) && (System.Convert.ToInt32(c.Attribute("max").Value) == toColumn)).FirstOrDefault(); if (colXElement != null) { //col element does exist //change its width value colXElement.SetAttributeValue("width", width); } else { //col element does not exist //create a new one colsXElement.Add(new XElement(ns + "col", new XAttribute("min", fromColumn.ToString()), new XAttribute("max", toColumn.ToString()), new XAttribute("width", width.ToString()), new XAttribute("customWidth", "1"))); } } //Update the worksheet part markup at worksheet part stream XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Set the value for a specific cell /// </summary> /// <param name="worksheet">Worksheet part containing the cell to be affected</param> /// <param name="fromColumn">Initial column for setting the value</param> /// <param name="fromRow">Initial row for setting the value</param> /// <param name="toColumn">Final column for setting the value</param> /// <param name="toRow">Final row for setting the value</param> /// <param name="value">Cell value</param> public static OpenXmlPowerToolsDocument SetCellValue(SmlDocument doc, string worksheetName, int fromRow, int toRow, int fromColumn, int toColumn, string value) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (int col = fromColumn; col <= toColumn; col++) { AddValue(worksheetXDocument, row, col, value); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return streamDoc.GetModifiedDocument(); } }
/// <summary> /// Apply a cell style to a specific cell /// </summary> /// <param name="worksheet">worksheet containing the cell to be affected</param> /// <param name="fromColumn">Starting Cell Column</param> /// <param name="toColumn">Ending Cell Column</param> /// <param name="fromRow">Starting Cell Row</param> /// <param name="toRow">Ending Cell Row</param> /// <param name="cellStyle">Cell Style</param> public static OpenXmlPowerToolsDocument SetCellStyle(SmlDocument doc, string worksheetName, short fromColumn, short toColumn, int fromRow, int toRow, string cellStyle) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc)) { using (SpreadsheetDocument document = streamDoc.GetSpreadsheetDocument()) { WorksheetPart worksheet = Get(document, worksheetName); XDocument worksheetXDocument = XDocument.Load(new XmlTextReader(worksheet.GetStream())); for (int row = fromRow; row <= toRow; row++) { for (short col = fromColumn; col <= toColumn; col++) { XElement cellXelement = GetCell(worksheetXDocument, col, row); cellXelement.SetAttributeValue("s", SpreadSheetStyleAccessor.GetCellStyleIndex(document, cellStyle)); } } XmlWriter worksheetWriter = XmlTextWriter.Create(worksheet.GetStream(System.IO.FileMode.Create)); worksheetXDocument.WriteTo(worksheetWriter); worksheetWriter.Flush(); worksheetWriter.Close(); } return streamDoc.GetModifiedDocument(); } }