From 4483308d6636fc6159313f7a2c5e128cd15ef5af Mon Sep 17 00:00:00 2001 From: Michael Bowen Date: Tue, 12 Dec 2023 12:45:49 -0800 Subject: [PATCH] closes #274 --- ...nsert-text-into-a-cell-in-a-spreadsheet.md | 364 +----------------- .../insert_textto_a_cell/cs/Program.cs | 17 +- .../insert_textto_a_cell/vb/Program.vb | 14 +- 3 files changed, 37 insertions(+), 358 deletions(-) diff --git a/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md b/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md index bc18c31a..c86e7e9e 100644 --- a/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md +++ b/docs/spreadsheet/how-to-insert-text-into-a-cell-in-a-spreadsheet.md @@ -11,7 +11,7 @@ ms.suite: office ms.author: o365devx author: o365devx ms.topic: conceptual -ms.date: 11/01/2017 +ms.date: 12/12/2023 ms.localizationpriority: high --- # Insert text into a cell in a spreadsheet document @@ -20,55 +20,7 @@ This topic shows how to use the classes in the Open XML SDK for Office to insert text into a cell in a new worksheet in a spreadsheet document programmatically. - - -------------------------------------------------------------------------------- -## Getting a SpreadsheetDocument Object -In the Open XML SDK, the [SpreadsheetDocument](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.aspx) class represents an -Excel document package. To open and work with an Excel document, you -create an instance of the **SpreadsheetDocument** class from the document. -After you create the instance from the document, you can then obtain -access to the main workbook part that contains the worksheets. The text -in the document is represented in the package as XML using **SpreadsheetML** markup. - -To create the class instance from the document that you call one of the -[Open()](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.open.aspx) overload methods. Several are -provided, each with a different signature. The sample code in this topic -uses the [Open(String, Boolean)](https://msdn.microsoft.com/library/office/cc562356.aspx) method with a -signature that requires two parameters. The first parameter takes a full -path string that represents the document that you want to open. The -second parameter is either **true** or **false** and represents whether you want the file to -be opened for editing. Any changes that you make to the document will -not be saved if this parameter is **false**. - -The code that calls the **Open** method is -shown in the following **using** statement. - -### [C#](#tab/cs-0) -```csharp - // Open the document for editing. - using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) - { - // Insert other code here. - } -``` - -### [Visual Basic](#tab/vb-0) -```vb - ' Open the document for editing. - Using spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - ' Insert other code here. - End Using -``` -*** - - -The **using** statement provides a recommended -alternative to the typical .Open, .Save, .Close sequence. It ensures -that the **Dispose** method (internal method -used by the Open XML SDK to clean up resources) is automatically called -when the closing brace is reached. The block that follows the **using** statement establishes a scope for the -object that is created or named in the **using** statement, in this case *spreadSheet*. [!include[Structure](../includes/spreadsheet/structure.md)] @@ -79,82 +31,10 @@ inserts a new [Cell](https://msdn.microsoft.com/library/office/documentformat.op inserts the specified text into that cell. ### [C#](#tab/cs-1) -```csharp - // Given a document name and text, - // inserts a new worksheet and writes the text to cell "A1" of the new worksheet. - public static void InsertText(string docName, string text) - { - // Open the document for editing. - using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Open(docName, true)) - { - // Get the SharedStringTablePart. If it does not exist, create a new one. - SharedStringTablePart shareStringPart; - if (spreadSheet.WorkbookPart.GetPartsOfType().Count() > 0) - { - shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType().First(); - } - else - { - shareStringPart = spreadSheet.WorkbookPart.AddNewPart(); - } - - // Insert the text into the SharedStringTablePart. - int index = InsertSharedStringItem(text, shareStringPart); - - // Insert a new worksheet. - WorksheetPart worksheetPart = InsertWorksheet(spreadSheet.WorkbookPart); - - // Insert cell A1 into the new worksheet. - Cell cell = InsertCellInWorksheet("A", 1, worksheetPart); - - // Set the value of cell A1. - cell.CellValue = new CellValue(index.ToString()); - cell.DataType = new EnumValue(CellValues.SharedString); - - // Save the new worksheet. - worksheetPart.Worksheet.Save(); - } - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet1)] ### [Visual Basic](#tab/vb-1) -```vb - ' Given a document name and text, - ' inserts a new worksheet and writes the text to cell "A1" of the new worksheet. - Public Function InsertText(ByVal docName As String, ByVal text As String) - ' Open the document for editing. - Dim spreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True) - - Imports (spreadSheet) - ' Get the SharedStringTablePart. If it does not exist, create a new one. - Dim shareStringPart As SharedStringTablePart - - If (spreadSheet.WorkbookPart.GetPartsOfType(Of SharedStringTablePart).Count() > 0) Then - shareStringPart = spreadSheet.WorkbookPart.GetPartsOfType(Of SharedStringTablePart).First() - Else - shareStringPart = spreadSheet.WorkbookPart.AddNewPart(Of SharedStringTablePart)() - End If - - ' Insert the text into the SharedStringTablePart. - Dim index As Integer = InsertSharedStringItem(text, shareStringPart) - - ' Insert a new worksheet. - Dim worksheetPart As WorksheetPart = InsertWorksheet(spreadSheet.WorkbookPart) - - ' Insert cell A1 into the new worksheet. - Dim cell As Cell = InsertCellInWorksheet("A", 1, worksheetPart) - - ' Set the value of cell A1. - cell.CellValue = New CellValue(index.ToString) - cell.DataType = New EnumValue(Of CellValues)(CellValues.SharedString) - - ' Save the new worksheet. - worksheetPart.Worksheet.Save() - - Return 0 - End Imports - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet1)] *** @@ -170,65 +50,10 @@ The following code verifies if the specified text exists in the **SharedStringTa it does not exist. ### [C#](#tab/cs-2) -```csharp - // Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text - // and inserts it into the SharedStringTablePart. If the item already exists, returns its index. - private static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart) - { - // If the part does not contain a SharedStringTable, create one. - if (shareStringPart.SharedStringTable == null) - { - shareStringPart.SharedStringTable = new SharedStringTable(); - } - - int i = 0; - - // Iterate through all the items in the SharedStringTable. If the text already exists, return its index. - foreach (SharedStringItem item in shareStringPart.SharedStringTable.Elements()) - { - if (item.InnerText == text) - { - return i; - } - - i++; - } - - // The text does not exist in the part. Create the SharedStringItem and return its index. - shareStringPart.SharedStringTable.AppendChild(new SharedStringItem(new DocumentFormat.OpenXml.Spreadsheet.Text(text))); - shareStringPart.SharedStringTable.Save(); - - return i; - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet2)] ### [Visual Basic](#tab/vb-2) -```vb - ' Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text - ' and inserts it into the SharedStringTablePart. If the item already exists, returns its index. - Private Function InsertSharedStringItem(ByVal text As String, ByVal shareStringPart As SharedStringTablePart) As Integer - ' If the part does not contain a SharedStringTable, create one. - If (shareStringPart.SharedStringTable Is Nothing) Then - shareStringPart.SharedStringTable = New SharedStringTable - End If - - Dim i As Integer = 0 - - ' Iterate through all the items in the SharedStringTable. If the text already exists, return its index. - For Each item As SharedStringItem In shareStringPart.SharedStringTable.Elements(Of SharedStringItem)() - If (item.InnerText = text) Then - Return i - End If - i = (i + 1) - Next - - ' The text does not exist in the part. Create the SharedStringItem and return its index. - shareStringPart.SharedStringTable.AppendChild(New SharedStringItem(New DocumentFormat.OpenXml.Spreadsheet.Text(text))) - shareStringPart.SharedStringTable.Save() - - Return i - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet2)] *** @@ -245,66 +70,10 @@ object by adding a new **WorksheetPart** object to the [WorkbookPart](https://msdn.microsoft.com/library/office/documentformat.openxml.packaging.spreadsheetdocument.workbookpart.aspx) object. ### [C#](#tab/cs-3) -```csharp - // Given a WorkbookPart, inserts a new worksheet. - private static WorksheetPart InsertWorksheet(WorkbookPart workbookPart) - { - // Add a new worksheet part to the workbook. - WorksheetPart newWorksheetPart = workbookPart.AddNewPart(); - newWorksheetPart.Worksheet = new Worksheet(new SheetData()); - newWorksheetPart.Worksheet.Save(); - - Sheets sheets = workbookPart.Workbook.GetFirstChild(); - string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart); - - // Get a unique ID for the new sheet. - uint sheetId = 1; - if (sheets.Elements().Count() > 0) - { - sheetId = sheets.Elements().Select(s => s.SheetId.Value).Max() + 1; - } - - string sheetName = "Sheet" + sheetId; - - // Append the new worksheet and associate it with the workbook. - Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName }; - sheets.Append(sheet); - workbookPart.Workbook.Save(); - - return newWorksheetPart; - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet3)] ### [Visual Basic](#tab/vb-3) -```vb - ' Given a WorkbookPart, inserts a new worksheet. - Private Function InsertWorksheet(ByVal workbookPart As WorkbookPart) As WorksheetPart - ' Add a new worksheet part to the workbook. - Dim newWorksheetPart As WorksheetPart = workbookPart.AddNewPart(Of WorksheetPart)() - newWorksheetPart.Worksheet = New Worksheet(New SheetData) - newWorksheetPart.Worksheet.Save() - Dim sheets As Sheets = workbookPart.Workbook.GetFirstChild(Of Sheets)() - Dim relationshipId As String = workbookPart.GetIdOfPart(newWorksheetPart) - - ' Get a unique ID for the new sheet. - Dim sheetId As UInteger = 1 - If (sheets.Elements(Of Sheet).Count() > 0) Then - sheetId = sheets.Elements(Of Sheet).Select(Function(s) s.SheetId.Value).Max() + 1 - End If - - Dim sheetName As String = ("Sheet" + sheetId.ToString()) - - ' Add the new worksheet and associate it with the workbook. - Dim sheet As Sheet = New Sheet - sheet.Id = relationshipId - sheet.SheetId = sheetId - sheet.Name = sheetName - sheets.Append(sheet) - workbookPart.Workbook.Save() - - Return newWorksheetPart - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet3)] *** @@ -319,137 +88,26 @@ In the following code, insert a new **Cell** object into a **Worksheet** object. ### [C#](#tab/cs-4) -```csharp - // Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. - // If the cell already exists, returns it. - private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart) - { - Worksheet worksheet = worksheetPart.Worksheet; - SheetData sheetData = worksheet.GetFirstChild(); - string cellReference = columnName + rowIndex; - - // If the worksheet does not contain a row with the specified row index, insert one. - Row row; - if (sheetData.Elements().Where(r => r.RowIndex == rowIndex).Count() != 0) - { - row = sheetData.Elements().Where(r => r.RowIndex == rowIndex).First(); - } - else - { - row = new Row() { RowIndex = rowIndex }; - sheetData.Append(row); - } - - // If there is not a cell with the specified column name, insert one. - if (row.Elements().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0) - { - return row.Elements().Where(c => c.CellReference.Value == cellReference).First(); - } - else - { - // Cells must be in sequential order according to CellReference. Determine where to insert the new cell. - Cell refCell = null; - foreach (Cell cell in row.Elements()) - { - if (cell.CellReference.Value.Length == cellReference.Length) - { - if (string.Compare(cell.CellReference.Value, cellReference, true) > 0) - { - refCell = cell; - break; - } - } - } - - Cell newCell = new Cell() { CellReference = cellReference }; - row.InsertBefore(newCell, refCell); - - worksheet.Save(); - return newCell; - } - } -``` +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet4)] ### [Visual Basic](#tab/vb-4) -```vb - ' Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. - ' If the cell already exists, return it. - Private Function InsertCellInWorksheet(ByVal columnName As String, ByVal rowIndex As UInteger, ByVal worksheetPart As WorksheetPart) As Cell - Dim worksheet As Worksheet = worksheetPart.Worksheet - Dim sheetData As SheetData = worksheet.GetFirstChild(Of SheetData)() - Dim cellReference As String = (columnName + rowIndex.ToString()) - - ' If the worksheet does not contain a row with the specified row index, insert one. - Dim row As Row - If (sheetData.Elements(Of Row).Where(Function(r) r.RowIndex.Value = rowIndex).Count() <> 0) Then - row = sheetData.Elements(Of Row).Where(Function(r) r.RowIndex.Value = rowIndex).First() - Else - row = New Row() - row.RowIndex = rowIndex - sheetData.Append(row) - End If - - ' If there is not a cell with the specified column name, insert one. - If (row.Elements(Of Cell).Where(Function(c) c.CellReference.Value = columnName + rowIndex.ToString()).Count() > 0) Then - Return row.Elements(Of Cell).Where(Function(c) c.CellReference.Value = cellReference).First() - Else - ' Cells must be in sequential order according to CellReference. Determine where to insert the new cell. - Dim refCell As Cell = Nothing - For Each cell As Cell In row.Elements(Of Cell)() - If (String.Compare(cell.CellReference.Value, cellReference, True) > 0) Then - refCell = cell - Exit For - End If - Next - - Dim newCell As Cell = New Cell - newCell.CellReference = cellReference - - row.InsertBefore(newCell, refCell) - worksheet.Save() - - Return newCell - End If - End Function -``` +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet4)] *** -------------------------------------------------------------------------------- ## Sample Code -The following code sample is used to insert a new worksheet and write -the text to the cell "A1" of the new worksheet for a specific -spreadsheet document named "Sheet8.xlsx." To call the **InsertText** method you can use the following code -as an example. - -### [C#](#tab/cs-5) -```csharp - InsertText(@"C:\Users\Public\Documents\Sheet8.xlsx", "Inserted Text"); -``` - -### [Visual Basic](#tab/vb-5) -```vb - InsertText("C:\Users\Public\Documents\Sheet8.xlsx", "Inserted Text") -``` -*** - The following is the complete sample code in both C\# and Visual Basic. ### [C#](#tab/cs) -[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs)] +[!code-csharp[](../../samples/spreadsheet/insert_textto_a_cell/cs/Program.cs#snippet0)] ### [Visual Basic](#tab/vb) -[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb)] +[!code-vb[](../../samples/spreadsheet/insert_textto_a_cell/vb/Program.vb#snippet0)] -------------------------------------------------------------------------------- ## See also [Open XML SDK class library reference](/office/open-xml/open-xml-sdk) - -[Language-Integrated Query (LINQ)](https://msdn.microsoft.com/library/bb397926.aspx) - -[Lambda Expressions](https://msdn.microsoft.com/library/bb531253.aspx) - -[Lambda Expressions (C\# Programming Guide)](https://msdn.microsoft.com/library/bb397687.aspx) diff --git a/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs b/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs index d847e946..d745ff90 100644 --- a/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs +++ b/samples/spreadsheet/insert_textto_a_cell/cs/Program.cs @@ -1,14 +1,12 @@ - +// using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System.Linq; -InsertText(args[0], args[1]); - +// // Given a document name and text, // inserts a new work sheet and writes the text to cell "A1" of the new worksheet. - static void InsertText(string docName, string text) { // Open the document for editing. @@ -44,7 +42,9 @@ static void InsertText(string docName, string text) worksheetPart.Worksheet.Save(); } } +// +// // Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text // and inserts it into the SharedStringTablePart. If the item already exists, returns its index. static int InsertSharedStringItem(string text, SharedStringTablePart shareStringPart) @@ -74,7 +74,9 @@ static int InsertSharedStringItem(string text, SharedStringTablePart shareString return i; } +// +// // Given a WorkbookPart, inserts a new worksheet. static WorksheetPart InsertWorksheet(WorkbookPart workbookPart) { @@ -110,7 +112,10 @@ static WorksheetPart InsertWorksheet(WorkbookPart workbookPart) return newWorksheetPart; } +// + +// // Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. // If the cell already exists, returns it. static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart) @@ -158,3 +163,7 @@ static Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPar return newCell; } } +// +// + +InsertText(args[0], args[1]); \ No newline at end of file diff --git a/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb b/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb index 6ec4d2cc..819035d3 100644 --- a/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb +++ b/samples/spreadsheet/insert_textto_a_cell/vb/Program.vb @@ -1,3 +1,4 @@ +' Imports DocumentFormat.OpenXml Imports DocumentFormat.OpenXml.Packaging Imports DocumentFormat.OpenXml.Spreadsheet @@ -6,8 +7,10 @@ Imports DocumentFormat.OpenXml.Spreadsheet Module MyModule Sub Main(args As String()) + InsertText(args(0), args(1)) End Sub + ' ' Given a document name and text, ' inserts a new worksheet and writes the text to cell "A1" of the new worksheet. Public Function InsertText(ByVal docName As String, ByVal text As String) @@ -43,7 +46,9 @@ Module MyModule Return 0 End Using End Function + ' + ' ' Given text and a SharedStringTablePart, creates a SharedStringItem with the specified text ' and inserts it into the SharedStringTablePart. If the item already exists, returns its index. Private Function InsertSharedStringItem(ByVal text As String, ByVal shareStringPart As SharedStringTablePart) As Integer @@ -68,7 +73,9 @@ Module MyModule Return i End Function + ' + ' ' Given a WorkbookPart, inserts a new worksheet. Private Function InsertWorksheet(ByVal workbookPart As WorkbookPart) As WorksheetPart ' Add a new worksheet part to the workbook. @@ -96,7 +103,9 @@ Module MyModule Return newWorksheetPart End Function + ' + ' ' Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet. ' If the cell already exists, return it. Private Function InsertCellInWorksheet(ByVal columnName As String, ByVal rowIndex As UInteger, ByVal worksheetPart As WorksheetPart) As Cell @@ -136,4 +145,7 @@ Module MyModule Return newCell End If End Function -End Module \ No newline at end of file + ' + +End Module +'