public static Cell createTextCell( int columnIndex, int rowIndex, object cellValue) { Cell cell = new Cell(); cell.DataType = CellValues.InlineString; cell.CellReference = getColumnName(columnIndex) + rowIndex; InlineString inlineString = new InlineString(); DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text(); t.Text = cellValue.ToString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); return cell; }
public string TagListFromInline(InlineString text) { if (ShowTag != TagShowing.Name && ShowTag != TagShowing.Disp) { return(null); } var sb = new StringBuilder(); foreach (var tag in text.Tags) { if (sb.Length > 0) { sb.AppendLine(); } if (!string.IsNullOrWhiteSpace(tag.Code)) { switch (ShowTag) { case TagShowing.Name: sb.Append(BuildTagString(tag, tag.Number.ToString())); break; case TagShowing.Disp: sb.Append(Enclose(tag.Display) ?? BuildTagString(tag, tag.Name)); break; } sb.Append(" = ").Append(tag.Code); } } return(sb.ToString()); }
private Cell CreateTextCell(string header, uint index, string text) { var cell = new Cell { CellReference = header + index, }; // try to convert value to int to set up correct cell format // if text can be converted to int but starts from zeros, it will be pasted as string in order to save zeros int intValue; if (int.TryParse(text, out intValue) && text == intValue.ToString()) { cell.DataType = new EnumValue <CellValues>(CellValues.Number); cell.CellValue = new CellValue(text); } else { cell.DataType = CellValues.InlineString; var istring = new InlineString(); var t = new Text { Text = text }; istring.AppendChild(t); cell.AppendChild(istring); } return(cell); }
/// <summary> /// Переместить значение хранящиеся в данном объекте в форматированную строку /// </summary> /// <param name="cell"></param> public static void TurnValueToInlineString(Cell cell) { if (cell.DataType != null && cell.DataType == CellValues.InlineString) { return; } if (cell.CellValue == null) { cell.CellValue = new CellValue(); } InlineString newInStr; if (cell.DataType != null && cell.DataType == CellValues.SharedString) { var ssItem = cell.GetSharedStringItem(); newInStr = new InlineString(ssItem.Elements().Select(el => el.CloneNode(true))); } else { var text = cell.CellValue.Text; newInStr = new InlineString(); newInStr.Text = new Text(text); } cell.CellValue = new CellValue(); cell.InlineString = newInStr; cell.DataType = CellValues.InlineString; }
/// <summary> /// Converts the object to cell. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> private static Cell ConvertObjectToCell(object value) { var objType = value.GetType(); var cell = new Cell(); if (objType == typeof(decimal)) { cell.DataType = CellValues.Number; cell.CellValue = new CellValue(value.ToString()); } else if (objType == typeof(int)) { cell.DataType = CellValues.Number; cell.CellValue = new CellValue(value.ToString()); } else { cell.DataType = CellValues.InlineString; var inlineString = new InlineString(); var text = new Text { Text = value.ToString() }; inlineString.AppendChild(text); cell.AppendChild(inlineString); } return(cell); }
private static Row CreateNewRow(int rowIndex, params string[] data) { // New Row Row row = new Row { RowIndex = (UInt32)rowIndex }; for (int i = 0; i < data.Length; i++) { // A = 65 for the first column, B = 66, C = 67... string column = ((char) (65 + i)).ToString(); // New Cell Cell cell = new Cell { DataType = CellValues.InlineString, CellReference = column + rowIndex }; // Create Text object Text t = new Text {Text = data[i]}; // Append Text to InlineString object InlineString inlineString = new InlineString(); inlineString.AppendChild(t); // Append InlineString to Cell cell.AppendChild(inlineString); // Append Cell to Row row.AppendChild(cell); } return row; }
private void WriteCellValue(string cellValue, string cellReference, CellValues cellType, List <OpenXmlAttribute> attributes) { attributes.Add(cellValueAttributes[cellType]); cellReferenceAttribute.Value = cellReference; attributes.Add(cellReferenceAttribute); this.writer.WriteStartElement(new Cell(), attributes); switch (cellType) { case CellValues.InlineString: var parsedInlineString = new InlineString(new Text(cellValue)); this.writer.WriteElement(parsedInlineString); break; case CellValues.SharedString: var sharedStringIndex = this.InsertSharedString(cellValue); this.writer.WriteElement(new CellValue(sharedStringIndex)); break; default: this.writer.WriteElement(new CellValue(cellValue)); break; } this.writer.WriteEndElement(); }
private static Cell CreateTextCell(string header, UInt32 index, string text, uint styleIndex = 0) { long result = 0; Cell cell = null; if (long.TryParse(text, out result)) { cell = new Cell { DataType = CellValues.Number, CellReference = header + index, StyleIndex = styleIndex }; } else { cell = new Cell { DataType = CellValues.InlineString, CellReference = header + index, StyleIndex = styleIndex }; } var istring = new InlineString(); var t = new Text { Text = text }; istring.AppendChild(t); cell.AppendChild(istring); return(cell); }
internal void FromHash(string Hash) { var istr = new InlineString(); istr.InnerXml = Hash; FromInlineString(istr); }
/// <summary> /// Crea una celda en una posicion especificada con un valor definido /// Se define si el campo va en negrita (bold) /// Opcionalmente se puede establecer el tamaño de la fuente /// </summary> /// <param name="posicion"></param> /// <param name="valor"></param> /// <param name="bold"></param> /// <param name="fontSize"></param> /// <returns></returns> private static Cell crearCelda(string posicion, string valor, bool bold, int fontSize = 12) { Cell celda = new Cell() { DataType = CellValues.InlineString, CellReference = posicion }; RunProperties runProperties = new RunProperties(); if (bold) { runProperties.Append(new Bold()); } runProperties.Append(new FontSize() { Val = fontSize }); Run run = new Run(); run.Append(new Text(valor)); run.RunProperties = runProperties; InlineString inlineString = new InlineString(); inlineString.Append(run); celda.Append(inlineString); return(celda); }
protected virtual Cell CreateTextCell(string header, UInt32 index, string text, string formula) { var cell = new Cell { DataType = CellValues.InlineString, CellReference = header + index }; if (formula?.Length > 0) { var cellFormula1 = new CellFormula { Text = formula }; var cellValue1 = new CellValue { Text = text }; cell.Append(cellFormula1); cell.Append(cellValue1); } else { var istring = new InlineString(); var t = new Text { Text = text }; istring.AppendChild(t); cell.AppendChild(istring); } return(cell); }
//gavdcodeend 01 //gavdcodebegin 02 public static void ExcelOpenXmlInsertTextInCell() { using (SpreadsheetDocument myExcelDoc = SpreadsheetDocument.Open(@"C:\Temporary\ExcelDoc01.xlsx", true)) { WorkbookPart myWorkbookPart = myExcelDoc.WorkbookPart; WorksheetPart myWorksheetPart = myWorkbookPart.WorksheetParts.First(); SheetData mySheetData = myWorksheetPart.Worksheet.Elements <SheetData>(). First(); Row newRow = mySheetData.Elements <Row>().FirstOrDefault(); Cell newCell = new Cell() { DataType = CellValues.InlineString, CellReference = "C3" }; InlineString myInlineString = new InlineString(); Text myText = new Text() { Text = "Text in Cell" }; myInlineString.AppendChild(myText); newCell.AppendChild(myInlineString); newRow.Append(newCell); } }
public void Ctors_1() { var a = new InlineString(); a.Is(); a.IsEmpty.IsTrue(); }
private Cell CreateCell(string header, UInt32 index, string text) { Cell cell; double number; if (double.TryParse(text, out number)) { cell = new Cell { DataType = CellValues.Number, CellReference = header + index, CellValue = new CellValue(number.ToString(CultureInfo.InvariantCulture)) }; } else { cell = new Cell { DataType = CellValues.InlineString, CellReference = header + index }; var istring = new InlineString(); var t = new Text { Text = text }; istring.AppendChild(t); cell.AppendChild(istring); } return(cell); }
/// <summary> /// Creates a new Cell object with the InlineString data type. /// </summary> private static Cell CreateTextCell( object cellValue, uint?styleIndex, bool isRelationshipValue = false) { var cell = new Cell { DataType = CellValues.InlineString }; //apply the cell style if supplied if (styleIndex.HasValue) { cell.StyleIndex = styleIndex.Value; } var inlineString = new InlineString( ); var t = new DocumentFormat.OpenXml.Spreadsheet.Text( ); if (cellValue != null) { t.Text = isRelationshipValue ? DatabaseTypeHelper.GetEntityXmlName(cellValue.ToString( )) : cellValue.ToString( ); } inlineString.AppendChild(t); cell.AppendChild(inlineString); return(cell); }
internal void FromHash(string Hash) { InlineString istr = new InlineString(); istr.InnerXml = Hash; this.FromInlineString(istr); }
/// <summary> /// Form a DocumentFormat.OpenXml.Spreadsheet.InlineString class from this SLRstType class. /// </summary> /// <returns>A DocumentFormat.OpenXml.Spreadsheet.InlineString class.</returns> public InlineString ToInlineString() { InlineString istr = new InlineString(); istr.InnerXml = SLTool.RemoveNamespaceDeclaration(this.istrReal.InnerXml); return(istr); }
/// <summary> /// This method is used to create the Row to append in excel /// </summary> /// <param name="rIndex"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <returns></returns> private static Row GetRowToAppendInExcel(SpreadsheetDocument document, WorksheetPart worksheetPart, int rIndex, List <ExcelCellValues> columnValueList) { Row r = new Row(); try { r.RowIndex = (UInt32)rIndex; foreach (var colValue in columnValueList) { if (!string.IsNullOrEmpty(colValue.CellUpdateValue)) { Cell cell = new Cell(); cell.CellReference = colValue.CellName + Convert.ToString(rIndex); cell.DataType = CellValues.String; InlineString inlinefString = new InlineString(); Text txt = new Text(); txt.Text = colValue.CellUpdateValue; inlinefString.AppendChild(txt); cell.AppendChild(inlinefString); r.AppendChild(cell); } } } catch (Exception ex) { throw ex; } return(r); }
private Cell CreateContentCell(string header, UInt32 index, string text, CellValues contentType) { Cell cell = new Cell { DataType = contentType, CellReference = header + index }; if (contentType != CellValues.Number) { InlineString istring = new InlineString(); Text t = new Text { Text = text }; istring.AppendChild(t); cell.AppendChild(istring); } else { cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(text); } return(cell); }
private static void overwriteTextOfTextCell(Cell cell, string newCellText) { Text t = new Text(); t.Text = newCellText; InlineString inlineString = new InlineString(); inlineString.AppendChild(t); cell.DataType = CellValues.InlineString; int count = cell.ChildElements.Count(); if (count > 0) { if (count > 1) { Console.WriteLine("WARNING! - Overwriting cell with {0:D} children", count); } //Console.WriteLine("replacing inlinstring child"); cell.ReplaceChild(inlineString, cell.GetFirstChild <InlineString>()); } else { cell.AppendChild(inlineString); } }
private Cell CreateTextCell(int columnIndex, int rowIndex, object cellValue, RunProperties runProperties = null) { Cell cell = new Cell { DataType = CellValues.InlineString, CellReference = GetColumnName(columnIndex) + rowIndex, }; Text text = new Text { Text = cellValue.ToString() }; RunSpreadsheet run = new RunSpreadsheet(); run.Append(text); if (runProperties != null) { run.RunProperties = runProperties; } InlineString inlineString = new InlineString(); inlineString.Append(run); cell.AppendChild(inlineString); return(cell); }
/// <summary> /// Writes data to a cell /// </summary> /// <param name="writer">this OpenXmlWriter writer instance</param> /// <param name="cellAddress">The cell address</param> /// <param name="cellValue">The cell value</param> /// <param name="dataType">The data type for the cell</param> public static void WriteCell(this OpenXmlWriter writer, string cellAddress, string cellValue, CellValues dataType) { // default to a standard cell value OpenXmlElement value = new CellValue(cellValue); bool testBool; long testLong; // fix up some values switch (dataType) { // we are handling all strings as inline for performance reasons case CellValues.SharedString: case CellValues.InlineString: dataType = CellValues.InlineString; value = new InlineString(new Text(cellValue)); break; case CellValues.Date: // write the value as a string to the sheet dataType = CellValues.String; break; case CellValues.Number: // this is a safety check as we sometimes get bad values such as N/A in columns if (!long.TryParse(cellValue, out testLong)) { // we default to writing it as a string to be safe dataType = CellValues.InlineString; value = new InlineString(new Text(cellValue)); } break; case CellValues.Boolean: // this is a safety check as we sometimes get bad values such as N/A in columns if (bool.TryParse(cellValue, out testBool)) { value = new CellValue(testBool ? "1" : "0"); } else { // we default to writing it as a string to be safe dataType = CellValues.InlineString; value = new InlineString(new Text(cellValue)); } break; } // write cell xml to the writer writer.WriteStartElement(new Cell() { DataType = dataType, CellReference = cellAddress }); writer.WriteElement(value); writer.WriteEndElement(); }
public static byte[] UpdateCells(MemoryStream doc, string title, List <string> headers, List <List <string> > rows) { // Open the document for editing. SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(doc, true); WorksheetPart worksheetPart = GetWorksheetPartByName(spreadSheet, "Fax-ArchiveReport"); if (worksheetPart != null) { //----------------------------------------------- title Cell cellTitle = GetCell(worksheetPart.Worksheet, ColumnsNames[0], 2); var inlineStringTitle = new InlineString(); inlineStringTitle.AppendChild(new Text { Text = title ?? string.Empty }); cellTitle.AppendChild(inlineStringTitle); cellTitle.DataType = new EnumValue <CellValues>(CellValues.InlineString); //----------------------------------------------- data uint rowIndex = 4; foreach (var row in rows) { uint rowCellIndex = 0; foreach (var rowCell in row) { Cell cell = GetCell(worksheetPart.Worksheet, ColumnsNames[rowCellIndex], rowIndex); var inlineStringRowCell = new InlineString(); inlineStringRowCell.AppendChild(new Text { Text = rowCell ?? string.Empty }); cell.AppendChild(inlineStringRowCell); cell.DataType = new EnumValue <CellValues>(CellValues.InlineString); rowCellIndex++; } rowIndex++; } //----------------------------------------------- worksheetPart.Worksheet.Save(); spreadSheet.Close(); var bytes = doc.ToArray(); doc.Dispose(); return(bytes); } return(null); }
public static Row CreateRowValues(int index, DataInSheet objToInsert) { Row row = new Row(); row.RowIndex = (UInt32)index; int i = 0; foreach (var property in objToInsert.GetType().GetProperties()) { Cell cell = new Cell(); cell.CellReference = headerColumns[i].ToString() + index; if (property.PropertyType.ToString().Equals("System.string", StringComparison.InvariantCultureIgnoreCase)) { var result = property.GetValue(objToInsert, null); if (result == null) { result = ""; } cell.DataType = CellValues.String; InlineString inlineString = new InlineString(); Text text = new Text(); text.Text = result.ToString(); inlineString.AppendChild(text); cell.AppendChild(inlineString); } if (property.PropertyType.ToString().Equals("System.int32", StringComparison.InvariantCultureIgnoreCase)) { var result = property.GetValue(objToInsert, null); if (result == null) { result = 0; } CellValue cellValue = new CellValue(); cellValue.Text = result.ToString(); cell.AppendChild(cellValue); } if (property.PropertyType.ToString().Equals("System.boolean", StringComparison.InvariantCultureIgnoreCase)) { var result = property.GetValue(objToInsert, null); if (result == null) { result = "False"; } cell.DataType = CellValues.InlineString; InlineString inlineString = new InlineString(); Text text = new Text(); text.Text = result.ToString(); inlineString.AppendChild(text); cell.AppendChild(inlineString); } row.AppendChild(cell); i = i + 1; } return(row); }
public TextCell(string header, string text, int index) { CellReference = header + index; InlineString = new InlineString { Text = new Text { Text = text } }; DataType = new EnumValue <CellValues>(CellValues.InlineString); }
public TextCell(string header, string text, int index) { DataType = CellValues.InlineString; CellReference = header + index; InlineString = new InlineString { Text = new Text { Text = text } }; }
public void OpenXmlSax() { using var xl = SpreadsheetDocument.Create(Stream, SpreadsheetDocumentType.Workbook); xl.CompressionOption = CompressionOption.SuperFast; var workbookPart = xl.AddWorkbookPart(); var wsp = workbookPart.AddNewPart<WorksheetPart>(); var oxw = OpenXmlWriter.Create(wsp); oxw.WriteStartElement(new DocumentFormat.OpenXml.Spreadsheet.Worksheet()); oxw.WriteStartElement(new SheetData()); var rowObject = new Row(); var cellAttributes = new[] { new OpenXmlAttribute("t", "", "inlineStr") }; var cell = new OpenXmlCell(); var inlineString = new InlineString(); for (var row = 0; row < NumberOfRows; ++row) { var rowAttributes = new[] { new OpenXmlAttribute("r", "", (row + 1).ToString()) }; oxw.WriteStartElement(rowObject, rowAttributes); var rowValues = Values[row]; for (var col = 0; col < rowValues.Count; ++col) { oxw.WriteStartElement(cell, cellAttributes); oxw.WriteStartElement(inlineString); oxw.WriteElement(new Text(rowValues[col])); oxw.WriteEndElement(); oxw.WriteEndElement(); } oxw.WriteEndElement(); } oxw.WriteEndElement(); oxw.WriteEndElement(); oxw.Close(); oxw = OpenXmlWriter.Create(workbookPart); oxw.WriteStartElement(new Workbook()); oxw.WriteStartElement(new Sheets()); oxw.WriteElement(new Sheet() { Name = "Sheet1", SheetId = 1, Id = workbookPart.GetIdOfPart(wsp) }); oxw.WriteEndElement(); oxw.WriteEndElement(); oxw.Close(); xl.Close(); }
//thaond11 private void UpdateCellTextInline(Cell cell, string cellValue) { InlineString inlineString = new InlineString(); Text cellValueText = new Text { Text = cellValue }; inlineString.AppendChild(cellValueText); cell.DataType = CellValues.InlineString; cell.AppendChild(inlineString); }
//thaond11 public static Cell AddValueToCell(Cell cell, string text) { cell.DataType = CellValues.InlineString; cell.RemoveAllChildren(); InlineString inlineString = new InlineString(); Text t = new Text(); t.Text = text; inlineString.AppendChild(t); cell.AppendChild(inlineString); return(cell); }
/// <summary> /// Converts the paragraph. /// </summary> /// <param name="pgh">The PGH.</param> /// <param name="ils">The ils.</param> /// <param name="FontName">Name of the font.</param> /// <param name="Size">The size.</param> /// <returns></returns> public static InlineString ConvertParagraph(System.Windows.Documents.Paragraph pgh, InlineString ils, string FontName, decimal Size) { if (ils == null) { ils = new InlineString(); } foreach (Inline ilSpan in pgh.Inlines) { if (ilSpan.GetType() == typeof(Span)) { Span sp = (Span)ilSpan; foreach (object obj in sp.Inlines) { if (obj.GetType() == typeof(System.Windows.Documents.Run)) { System.Windows.Documents.Run rn = (System.Windows.Documents.Run)obj; List <OpenXmlLeafElement> DecorationList = new List <OpenXmlLeafElement>(); FontName fn = new FontName { Val = FontName }; FontSize fs = new FontSize { Val = (double)Size }; //Font.FontFamilyNumbering = new FontFamilyNumbering { Val = 2 }; if (rn.FontStyle == FontStyles.Italic) { DecorationList.Add(new DocumentFormat.OpenXml.Spreadsheet.Italic()); } if (sp.TextDecorations.Contains(TextDecorations.Underline.First())) { DecorationList.Add(new DocumentFormat.OpenXml.Spreadsheet.Underline()); } if (rn.FontWeight == FontWeights.Bold) { DecorationList.Add(new DocumentFormat.OpenXml.Spreadsheet.Bold()); } ils.AppendChild(NewRunText(rn.Text, DecorationList, fn, fs)); } } } } return(ils); }
/// <summary> /// Converts the paragraph list. /// </summary> /// <param name="pghList">The PGH list.</param> /// <param name="FontName">Name of the font.</param> /// <param name="Size">The size.</param> /// <returns></returns> public static List <InlineString> ConvertParagraphList(BlockCollection pghList, string FontName, decimal Size) { List <InlineString> NewList = new List <InlineString>(); foreach (Paragraph pgh in pghList) { InlineString ils = new InlineString(); NewList.Add(ConvertParagraph(pgh, ils, FontName, Size)); } return(NewList); }
private static Cell CreateInlineStringCell(string text) { Cell c = new Cell(); c.DataType = CellValues.InlineString; InlineString inlineString = new InlineString(); Text t = new Text(); t.Text = text; inlineString.AppendChild(t); c.AppendChild(inlineString); return(c); }
private static Cell createTextCell(int columnIndex, int rowIndex, string cellValue) { Cell cell = new Cell(); cell.DataType = CellValues.InlineString; //cell.CellReference = getColumnName(columnIndex) + rowIndex; InlineString inlineString = new InlineString(); Text t = new Text(cellValue); inlineString.AppendChild(t); cell.AppendChild(inlineString); return cell; }
private Cell CreateTextCell(string header, UInt32 index, string text) { var cell = new Cell { DataType = CellValues.InlineString, CellReference = header + index }; var istring = new InlineString(); var t = new Text { Text = text }; istring.AppendChild(t); cell.AppendChild(istring); return cell; }
public static void InsertValuesInWorksheet(WorksheetPart worksheetPart, uint rowIdx, List<string> values) { var worksheet = worksheetPart.Worksheet; var sheetData = worksheet.GetFirstChild<SheetData>(); Row row = new Row(); values.ForEach(v => { Cell cell = new Cell() { DataType = CellValues.InlineString }; InlineString inlineString = new InlineString(); inlineString.Append(new Text() { Text = v }); cell.Append(inlineString); row.Append(cell); }); sheetData.Append(row); }
internal int DirectSaveToSharedStringTable(InlineString Data) { int index = 0; string sHash = SLTool.RemoveNamespaceDeclaration(Data.InnerXml); if (dictSharedStringHash.ContainsKey(sHash)) { index = dictSharedStringHash[sHash]; } else { index = listSharedString.Count; listSharedString.Add(sHash); dictSharedStringHash[sHash] = index; } return index; }
private void Initialize(string MajorFont, string MinorFont, List<System.Drawing.Color> ThemeColors, List<System.Drawing.Color> IndexedColors) { this.MajorFont = MajorFont; this.MinorFont = MinorFont; int i; this.listThemeColors = new List<System.Drawing.Color>(); for (i = 0; i < ThemeColors.Count; ++i) { this.listThemeColors.Add(ThemeColors[i]); } this.listIndexedColors = new List<System.Drawing.Color>(); for (i = 0; i < IndexedColors.Count; ++i) { this.listIndexedColors.Add(IndexedColors[i]); } istrReal = new InlineString(); }
private void button2_Click(object sender, EventArgs e) { string src = @"template/2.xlsx"; //OpenXML SDK 2.5 //REF: http://msdn.microsoft.com/en-us/library/office/cc850837.aspx string dst = src.Replace(Path.GetFileName(src), "Astro2_Sys WHCK Status - 0712-SA2.xlsx"); //另存目的檔 File.Copy(src, dst, true); using (var shtDoc = SpreadsheetDocument.Open(dst, true)) { //var sht = shtDoc.WorkbookPart.Workbook.Descendants<Sheet>().First(); var sht = shtDoc.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == "Astro 2 TestResult 9431").FirstOrDefault(); var shtPart = shtDoc.WorkbookPart.GetPartById(sht.Id) as WorksheetPart; //var cell = shtPart.Worksheet.Descendants<Row>().First().Descendants<Cell>().First(); // 3. 建立 Cell 物件,設定寫入位置,格式,資料 Cell cell = InsertCellInWorksheet("G", 8, shtPart); //REF: InlineString http://bit.ly/ZpUf18 var ins = new InlineString(); ins.AppendChild(new Text("Failed")); cell.AppendChild(ins); cell.DataType = new DocumentFormat.OpenXml.EnumValue<CellValues>(CellValues.InlineString); shtPart.Worksheet.Save(); shtDoc.WorkbookPart.Workbook.Save(); shtDoc.Close(); } }
/// <summary> /// Set the cell value given a cell reference. /// </summary> /// <param name="CellReference">The cell reference, such as "A1".</param> /// <param name="Data">The cell value data. Try the SLRstType class for easy InlineString generation.</param> /// <returns>False if the cell reference is invalid. True otherwise.</returns> public bool SetCellValue(string CellReference, InlineString Data) { int iRowIndex = -1; int iColumnIndex = -1; if (!SLTool.FormatCellReferenceToRowColumnIndex(CellReference, out iRowIndex, out iColumnIndex)) { return false; } return SetCellValue(iRowIndex, iColumnIndex, Data); }
/// <summary> /// Set the cell value given the row index and column index. /// </summary> /// <param name="RowIndex">The row index.</param> /// <param name="ColumnIndex">The column index.</param> /// <param name="Data">The cell value data. Try the SLRstType class for easy InlineString generation.</param> /// <returns>False if either the row index or column index (or both) are invalid. True otherwise.</returns> public bool SetCellValue(int RowIndex, int ColumnIndex, InlineString Data) { if (!SLTool.CheckRowColumnIndexLimit(RowIndex, ColumnIndex)) { return false; } SLCellPoint pt = new SLCellPoint(RowIndex, ColumnIndex); SLCell c; if (slws.Cells.ContainsKey(pt)) { c = slws.Cells[pt]; } else { c = new SLCell(); uint iStyleIndex = slws.GetExistingRowColumnStyle(RowIndex, ColumnIndex); if (iStyleIndex != 0) { c.StyleIndex = iStyleIndex; } } c.DataType = CellValues.SharedString; c.NumericValue = this.DirectSaveToSharedStringTable(Data); slws.Cells[pt] = c; return true; }
/// <summary> /// Using openxml /// </summary> private void ExportToExcel() { // Open the copied template workbook. using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(ExportFileLocation + ddlTables.SelectedItem.ToString() + ".xlsx", true)) { // Access the main Workbook part, which contains all references. WorkbookPart workbookPart = myWorkbook.WorkbookPart; // Get the first worksheet. //WorksheetPart worksheetPart = workbookPart.WorksheetParts.ElementAt(2); WorksheetPart worksheetPart = workbookPart.WorksheetParts.ElementAt(0); // The SheetData object will contain all the data. SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); // Begining Row pointer int index = 2; Row row = new Row(); row.RowIndex = (UInt32)1; #region Making headers for (int i = 0; i < dt.Columns.Count; i++) { // New Cell Cell cell = new Cell(); cell.DataType = CellValues.InlineString; // Column A1, 2, 3 ... and so on cell.CellReference = Convert.ToChar(65 + i).ToString() + "1"; // Create Text object Text t = new Text(); t.Text = dt.Columns[i].ColumnName; // Append Text to InlineString object InlineString inlineString = new InlineString(); inlineString.AppendChild(t); // Append InlineString to Cell cell.AppendChild(inlineString); // Append Cell to Row row.AppendChild(cell); } // Append Row to SheetData sheetData.AppendChild(row); #endregion // For each item in the database, add a Row to SheetData. foreach (DataRow dr in dt.Rows) { // New Row row = new Row(); row.RowIndex = (UInt32)index; for (int i = 0; i < dt.Columns.Count; i++) { // New Cell Cell cell = new Cell(); cell.DataType = CellValues.InlineString; // Column A1, 2, 3 ... and so on cell.CellReference = Convert.ToChar(65 + i).ToString() + index; // Create Text object Text t = new Text(); t.Text = dr[i].ToString(); // Append Text to InlineString object InlineString inlineString = new InlineString(); inlineString.AppendChild(t); // Append InlineString to Cell cell.AppendChild(inlineString); // Append Cell to Row row.AppendChild(cell); } // Append Row to SheetData sheetData.AppendChild(row); // increase row pointer index++; } // save worksheetPart.Worksheet.Save(); myWorkbook.Dispose(); } }
/// <summary> /// Form an SLRstType from DocumentFormat.OpenXml.Spreadsheet.InlineString class. /// </summary> /// <param name="RichText">A source DocumentFormat.OpenXml.Spreadsheet.InlineString class.</param> public void FromInlineString(InlineString RichText) { this.istrReal.InnerXml = RichText.InnerXml; }
private Cell CreateTextCell(string header, string text, int index) { // New Cell Cell cell = new Cell { DataType = CellValues.InlineString, CellReference = header + index }; // Create Text object Text t = new Text { Text = text }; // Append Text to InlineString object InlineString inlineString = new InlineString(); inlineString.AppendChild(t); // Append InlineString to Cell cell.AppendChild(inlineString); return cell; }
public void GenerateExcel(DataTable YoutdTName, string YourExcelfileName) { // Create cell reference array string[] CellReferenceArray = new string[] { "A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W" }; //Open your saved excel file that you have created using template file. using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(YourExcelfileName, true)) { // Get Workbook Part of Spread Sheet Document WorkbookPart objworkbook = spreadsheetDocument.WorkbookPart; // Get all sheets in spread sheet document IEnumerable<Sheet> sheetcollection = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>(); // Get relationship Id string relationshipId = sheetcollection.First().Id.Value; // Get sheet1 Part of Spread Sheet Document WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId); Worksheet worksheet = worksheetPart.Worksheet; // Get Data in Excel file SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); IEnumerable<Row> rowcollection = sheetData.Descendants<Row>().Skip(1); if (rowcollection.Count() == 0) { return; } // Create style sheet object that will be used for applying styling. // Stylesheet objstyleSheet = objworkbook.WorkbookStylesPart.Stylesheet; int i = 1; UInt32 index = 11; foreach (DataRow dr in YoutdTName.Rows) { i = 0; foreach (DataColumn col in YoutdTName.Columns) { if (i < 23) { Cell theCell = GetCell(worksheet, CellReferenceArray[i], index); if (theCell != null && string.IsNullOrEmpty(GetCellValue(objworkbook,theCell))) { //CellValue v1 = new CellValue(dr[col].ToString()); //theCell.CellValue = v1; theCell.DataType = CellValues.InlineString; theCell.RemoveAllChildren(); InlineString inline = new InlineString(); Text t = new Text(); t.Text = dr[col].ToString(); inline.AppendChild(t); theCell.AppendChild(inline); worksheetPart.Worksheet.Save(); } i += 1; } } index += 1; } } }
public static bool SetDataToExcel(string pathToExcelFile, string sheetName, DataTable data, string[] intro, string title) { try { Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass(); Microsoft.Office.Interop.Excel.Workbook wb; if (!System.IO.File.Exists(pathToExcelFile)) { //15/03/2011 Template ? System.IO.File.Copy(SystemHelper.GetConfigValue("appStartupPath") + "\\template\\newWorkbook.xlsx", pathToExcelFile); } wb = app.Workbooks.Open(pathToExcelFile, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Find sheetname int index = 1; for (index = 1; index <= wb.Sheets.Count; index++) { if (((Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets[index]).Name.ToLower().Trim() == sheetName.ToLower().Trim()) break; } if (index > wb.Sheets.Count) { wb.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing); } else { ((Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets[index]).Activate(); } Microsoft.Office.Interop.Excel.Worksheet activeSheet = (Microsoft.Office.Interop.Excel.Worksheet)wb.ActiveSheet; activeSheet.Name = sheetName; //activeSheet.Cells.FormatConditions = if (!System.IO.File.Exists(pathToExcelFile)) { //wb.SaveAs(pathToExcelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); wb.SaveAs(pathToExcelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } else { wb.Save(); } // exit excel, still now work so far wb.Close(true, Type.Missing, Type.Missing); app.Workbooks.Close(); app.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(wb); System.Runtime.InteropServices.Marshal.ReleaseComObject(app.Workbooks); while (System.Runtime.InteropServices.Marshal.ReleaseComObject(app) != 0) { }; //System.Diagnostics.Process.GetProcessById(app.Windows.Application.Hwnd).Close(); //System.Diagnostics.Process.GetProcessById(app.Windows.Application.Hwnd).Kill(); using (SpreadsheetDocument document = SpreadsheetDocument.Open(pathToExcelFile, true)) { IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName); if (sheets.Count() == 0) // the sheet with that name couldn't be found { return false; } WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id); SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); //sheetData.RemoveAllChildren<Row>(); //SharedStringTablePart shareStringTablePart = document.WorkbookPart.SharedStringTablePart; int lastRowIndex = sheetData.ChildElements.Count; int k = 0; //step in intro for (int i = lastRowIndex; i < data.Rows.Count + 4 + lastRowIndex + intro.Length; i++) // +1 for the header label, + 2 for spacing row, + 1 for title { DataRow dataRow = null; if (i > lastRowIndex + 3 + intro.Length) { dataRow = data.Rows[i - 4 - lastRowIndex - intro.Length]; } Row aRow = new Row(); aRow.RowIndex = (UInt32)i + 1; bool isRowEnd = false;//Fix the excel expand for (int j = 0; j < data.Columns.Count; j++) { if (isRowEnd) { break;//Fix the excel expand } Cell cell = new Cell(); cell.DataType = CellValues.InlineString; cell.CellReference = GetAlpha(j + 1) + (i + 1); InlineString inlineString = new InlineString(); Text t = new Text(); if (i <= lastRowIndex + intro.Length - 1)//Intro { if (j == 0) { t.Text = intro[k]; k++; cell.StyleIndex = (UInt32Value)3U; isRowEnd = true; } } else if (i == lastRowIndex + intro.Length + 1)//Title { if (j == 0) { t.Text = title; cell.StyleIndex = (UInt32Value)4U; isRowEnd = true; } } else if (i == lastRowIndex + 3 + intro.Length)//Header { t.Text = data.Columns[j].ToString(); cell.StyleIndex = (UInt32Value)1U; } else { if (i != intro.Length + lastRowIndex && i != intro.Length + lastRowIndex + 2)//Null spacing row t.Text = dataRow[j].ToString();//Data row } inlineString.AppendChild(t); cell.AppendChild(inlineString); aRow.AppendChild(cell); } sheetData.AppendChild(aRow); } System.Xml.XmlWriter test = System.Xml.XmlWriter.Create("Test.xml"); worksheetPart.Worksheet.WriteTo(test); test.Close(); worksheetPart.Worksheet.Save(); document.WorkbookPart.Workbook.Save(); document.Close(); } } catch (Exception e) { SystemHelper.LogEntry(string.Format("Error occurs on method {0} - Message {1}", "GetDataFromExcel", e.Message)); return false; } return true; }
Cell CreateTextCell(string header, string text, int index) { //Create a new inline string cell. Cell c = new Cell(); c.DataType = CellValues.InlineString; c.CellReference = header + index; //Add text to the text cell. InlineString inlineString = new InlineString(); Text t = new Text(); t.Text = text; inlineString.AppendChild(t); c.AppendChild(inlineString); return c; }
internal void FromHash(string Hash) { InlineString istr = new InlineString(); istr.InnerXml = Hash; this.FromInlineString(istr); }
/// <summary> /// Add cell into the passed row /// </summary> /// <param name="row">The row to add a cell to</param> /// <param name="rowIndex">The index of the row</param> /// <param name="value">The value for the cell</param> public void AppendCell(Row row, uint rowIndex, string value) { Cell cell = new Cell(); cell.DataType = CellValues.InlineString; Text t = new Text(); t.Text = value; //Append the Text InlineString inlineString = new InlineString(); inlineString.AppendChild(t); //Append to cell cell.AppendChild(inlineString); // Get the last cell's column string nextCol = "A"; Cell c = (Cell) row.LastChild; if (c != null) // if cells exist { int numIndex = c.CellReference.ToString().IndexOfAny(new char[] {'1', '2', '3', '4', '5', '6', '7', '8', '9'}); //Get the last column ref string lastCol = c.CellReference.ToString().Substring(0, numIndex); nextCol = IncrementColRef(lastCol); } cell.CellReference = nextCol + rowIndex; row.AppendChild(cell); }
private Cell createTextCell(int columnIndex, int rowIndex, object cellValue) { Cell cell = new Cell(); cell.DataType = CellValues.InlineString; cell.CellReference = getColumnName(columnIndex) + rowIndex; InlineString inlineString = new InlineString(); Text t = new Text(); t.Text = cellValue.ToString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); return cell; }
static void Main(string[] args) { if (args.Count() != 1) { Console.WriteLine("Usage: {0} <path>", Environment.GetCommandLineArgs()[0]); return; } try { foreach (string fileName in Directory.GetFiles(args[0], "*.xlsx")) { Console.WriteLine("Adding top row to worksheet \"Input\" for Excel file \"{0}\"...", fileName); using (SpreadsheetDocument ssd = SpreadsheetDocument.Open(fileName, true)) { WorkbookPart wbp = ssd.WorkbookPart; Sheet sheet = wbp.Workbook.Descendants<Sheet>().Where(s => s.Name == "Input").FirstOrDefault(); WorksheetPart wsp = (WorksheetPart)ssd.WorkbookPart.GetPartById(sheet.Id.Value); SheetData sd = wsp.Worksheet.GetFirstChild<SheetData>(); Row rr = sd.Descendants<Row>().Where(r => r.RowIndex == 2).FirstOrDefault(); Row nr = new Row() { RowIndex = 2 }; Cell a2 = new Cell() { CellReference = "A2", DataType = CellValues.InlineString }; { InlineString ils = new InlineString(); ils.Append(new Text() { Text = "TypeGuessRows" }); a2.Append(ils); } Cell b2 = new Cell() { CellReference = "B2", DataType = CellValues.InlineString }; { InlineString ils = new InlineString(); ils.Append(new Text() { Text = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" }); b2.Append(ils); } nr.Append(a2); nr.Append(b2); CalculationChainPart ccp = wbp.CalculationChainPart; if (ccp != null) { CalculationCell cc = ccp.CalculationChain.Descendants<CalculationCell>().Where(c => c.CellReference == "B2").FirstOrDefault(); if (cc != null) cc.Remove(); if (ccp.CalculationChain.Count() == 0) wbp.DeletePart(ccp); } foreach (Row rw in wsp.Worksheet.Descendants<Row>().Where(r => r.RowIndex.Value >= 2)) { uint nri = Convert.ToUInt32(rw.RowIndex.Value + 1); foreach (Cell cl in rw.Elements<Cell>()) { string cr = cl.CellReference.Value; cl.CellReference = new StringValue(cr.Replace(rw.RowIndex.Value.ToString(), nri.ToString())); } rw.RowIndex = new UInt32Value(nri); } sd.InsertBefore(nr, rr); wsp.Worksheet.Save(); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Excel.Application excel = new Excel.Application(); //Excel.Workbook workbook = excel.Workbooks.Open( // @"C:\DATA\NS_IMPORT\Network Standards - Managing Risk - Canada.xlsx", // 0, // false, // 5, // String.Empty, // String.Empty, // true, // Excel.XlPlatform.xlWindows, // "\t", // true, // false, // 0, // false, // true, // false); //Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.get_Item("Input"); //worksheet.Rows.Insert(2, 1); //worksheet.Rows[2][0].Value = "TYPESELECTOR"; //worksheet.Rows[2][1].Value = "0123456789"; //excel.SaveWorkspace(@"C:\DATA\NS_IMPORT\OUTPUT.xlsx"); } catch (Exception ex) { while (ex != null) { Console.WriteLine(ex.Message); ex = ex.InnerException; } } //Console.WriteLine("\nPress <any key> to continue."); //Console.ReadKey(true); }
/// <summary> /// Form a DocumentFormat.OpenXml.Spreadsheet.InlineString class from this SLRstType class. /// </summary> /// <returns>A DocumentFormat.OpenXml.Spreadsheet.InlineString class.</returns> public InlineString ToInlineString() { InlineString istr = new InlineString(); istr.InnerXml = SLTool.RemoveNamespaceDeclaration(this.istrReal.InnerXml); return istr; }
protected Row buildRowFromPhoneLog(int index, Models.PhoneLog log) { // New Row Row row = new Row(); row.RowIndex = (UInt32)index; // New Cell Cell cell = new Cell(); cell.DataType = CellValues.InlineString; // Column A1, 2, 3 ... and so on //cell.CellReference = "A" + index; Text t = new Text(); t.Text = log.Id.ToString(); InlineString inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.CallerName; // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.PhoneNumber; // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.CallType; // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.Message; // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.EmployeeEmail; // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.CallDate.Value.ToShortDateString(); // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); cell = new Cell(); cell.DataType = CellValues.InlineString; t = new Text(); t.Text = log.FollowedUp.Value.ToString(); // Append Text to InlineString object inlineString = new InlineString(); inlineString.AppendChild(t); cell.AppendChild(inlineString); row.AppendChild(cell); return row; }
public TextCell(string header, string text, int index) { DataType = CellValues.InlineString; CellReference = header + index; InlineString = new InlineString { Text = new Text { Text = text } }; }