Skip to content

Commit f687a69

Browse files
committed
clean up docs\spreadsheet\how-to-insert-a-new-worksheet-into-a-spreadsheet.md
1 parent 048995d commit f687a69

File tree

5 files changed

+134
-86
lines changed

5 files changed

+134
-86
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
## Getting a SpreadsheetDocument Object
2+
3+
In the Open XML SDK, the <xref:DocumentFormat.OpenXml.Packaging.SpreadsheetDocument> class represents an
4+
Excel document package. To open and work with an Excel document, you
5+
create an instance of the `SpreadsheetDocument` class from the document.
6+
After you create the instance from the document, you can then obtain
7+
access to the main workbook part that contains the worksheets. The text
8+
in the document is represented in the package as XML using `SpreadsheetML` markup.
9+
10+
To create the class instance from the document that you call one of the
11+
<xref:DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open*> methods. Several are provided, each
12+
with a different signature. The sample code in this topic uses the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open?view=openxml-3.0.1#documentformat-openxml-packaging-spreadsheetdocument-open(system-string-system-boolean)) method with a
13+
signature that requires two parameters. The first parameter takes a full
14+
path string that represents the document that you want to open. The
15+
second parameter is either `true` or `false` and represents whether you want the file to
16+
be opened for editing. Any changes that you make to the document will
17+
not be saved if this parameter is `false`.

docs/spreadsheet/how-to-insert-a-new-worksheet-into-a-spreadsheet.md

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,23 +20,8 @@ This topic shows how to use the classes in the Open XML SDK for
2020
Office to insert a new worksheet into a spreadsheet document
2121
programmatically.
2222

23-
## Getting a SpreadsheetDocument Object
24-
25-
In the Open XML SDK, the <xref:DocumentFormat.OpenXml.Packaging.SpreadsheetDocument> class represents an
26-
Excel document package. To open and work with an Excel document, you
27-
create an instance of the `SpreadsheetDocument` class from the document.
28-
After you create the instance from the document, you can then obtain
29-
access to the main workbook part that contains the worksheets. The text
30-
in the document is represented in the package as XML using `SpreadsheetML` markup.
31-
32-
To create the class instance from the document that you call one of the
33-
<xref:DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open*> methods. Several are provided, each
34-
with a different signature. The sample code in this topic uses the [Open(String, Boolean)](/dotnet/api/documentformat.openxml.packaging.spreadsheetdocument.open?view=openxml-3.0.1#documentformat-openxml-packaging-spreadsheetdocument-open(system-string-system-boolean)) method with a
35-
signature that requires two parameters. The first parameter takes a full
36-
path string that represents the document that you want to open. The
37-
second parameter is either `true` or `false` and represents whether you want the file to
38-
be opened for editing. Any changes that you make to the document will
39-
not be saved if this parameter is `false`.
23+
[!include[Open Spreadsheet](../includes/spreadsheet/open-spreadsheet.md)]
24+
4025

4126
The code that calls the `Open` method is
4227
shown in the following `using` statement.

docs/spreadsheet/how-to-merge-two-adjacent-cells-in-a-spreadsheet.md

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ ms.suite: office
1111
ms.author: o365devx
1212
author: o365devx
1313
ms.topic: conceptual
14-
ms.date: 12/12/2023
14+
ms.date: 01/10/2025
1515
ms.localizationpriority: high
1616
---
1717
# Merge two adjacent cells in a spreadsheet document
@@ -22,11 +22,52 @@ programmatically.
2222

2323
--------------------------------------------------------------------------------
2424

25+
[!include[Open Spreadsheet](../includes/spreadsheet/open-spreadsheet.md)]
26+
27+
------------------------------------------------------
28+
2529
[!include[Structure](../includes/spreadsheet/structure.md)]
2630

2731

2832
--------------------------------------------------------------------------------
29-
## Sample Code
33+
34+
## How the Sample Code Works
35+
36+
After you have opened the spreadsheet file for editing, the code
37+
verifies that the specified cells exist, and if they do not exist, it
38+
creates them by calling the `CreateSpreadsheetCellIfNotExist` method and append
39+
it to the appropriate <xref:DocumentFormat.OpenXml.Spreadsheet.Row> object.
40+
41+
### [C#](#tab/cs-1)
42+
[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet1)]
43+
44+
### [Visual Basic](#tab/vb-1)
45+
[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet1)]
46+
***
47+
48+
In order to get a column name, the code creates a new regular expression
49+
to match the column name portion of the cell name. This regular
50+
expression matches any combination of uppercase or lowercase letters.
51+
For more information about regular expressions, see [Regular Expression Language Elements](/dotnet/standard/base-types/regular-expressions). The
52+
code gets the column name by calling the [Regex.Match](/dotnet/api/system.text.regularexpressions.regex.match#overloads).
53+
54+
### [C#](#tab/cs-2)
55+
[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet2)]
56+
57+
### [Visual Basic](#tab/vb-2)
58+
[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet2)]
59+
***
60+
61+
To get the row index, the code creates a new regular expression to match the row index portion of the cell name. This regular expression matches any combination of decimal digits. The following code creates a regular expression to match the row index portion of the cell name, comprised of decimal digits.
62+
63+
### [C#](#tab/cs-3)
64+
[!code-csharp[](../../samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs#snippet3)]
65+
66+
### [Visual Basic](#tab/vb-3)
67+
[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet3)]
68+
***
69+
70+
## Sample Code
3071

3172
The following code merges two adjacent cells in a <xref:DocumentFormat.OpenXml.Spreadsheet.Row> document package. When
3273
merging two cells, only the content from one of the cells is preserved.
@@ -41,8 +82,9 @@ The following is the complete sample code in both C\# and Visual Basic.
4182

4283
### [Visual Basic](#tab/vb)
4384
[!code-vb[](../../samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb#snippet0)]
85+
***
4486

4587
--------------------------------------------------------------------------------
46-
## See also
88+
## See also
4789

4890
- [Open XML SDK class library reference](/office/open-xml/open-xml-sdk)

samples/spreadsheet/merge_two_adjacent_cells/cs/Program.cs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
// <Snippet0>
21
using DocumentFormat.OpenXml;
32
using DocumentFormat.OpenXml.Packaging;
43
using DocumentFormat.OpenXml.Spreadsheet;
@@ -7,10 +6,12 @@
76
using System.Linq;
87
using System.Text.RegularExpressions;
98

9+
MergeTwoCells(args[0], args[1], args[2], args[3]);
1010

1111
// Given a document name, a worksheet name, and the names of two adjacent cells, merges the two cells.
1212
// When two cells are merged, only the content from one cell is preserved:
1313
// the upper-left cell for left-to-right languages or the upper-right cell for right-to-left languages.
14+
// <Snippet0>
1415
static void MergeTwoCells(string docName, string sheetName, string cell1Name, string cell2Name)
1516
{
1617
// Open the document for editing.
@@ -77,10 +78,10 @@ static void MergeTwoCells(string docName, string sheetName, string cell1Name, st
7778
// Create the merged cell and append it to the MergeCells collection.
7879
MergeCell mergeCell = new MergeCell() { Reference = new StringValue(cell1Name + ":" + cell2Name) };
7980
mergeCells.Append(mergeCell);
80-
81-
worksheet.Save();
8281
}
8382
}
83+
84+
// <Snippet1>
8485
// Given a Worksheet and a cell name, verifies that the specified cell exists.
8586
// If it does not exist, creates a new cell.
8687
static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName)
@@ -98,8 +99,6 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName
9899
Cell cell = new Cell() { CellReference = new StringValue(cellName) };
99100
row.Append(cell);
100101
worksheet.Descendants<SheetData>().First().Append(row);
101-
102-
worksheet.Save();
103102
}
104103
else
105104
{
@@ -112,11 +111,10 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName
112111
{
113112
Cell cell = new Cell() { CellReference = new StringValue(cellName) };
114113
row.Append(cell);
115-
116-
worksheet.Save();
117114
}
118115
}
119116
}
117+
// </Snippet1>
120118

121119
// Given a SpreadsheetDocument and a worksheet name, get the specified worksheet.
122120
static Worksheet? GetWorksheet(SpreadsheetDocument document, string worksheetName)
@@ -130,6 +128,7 @@ static void CreateSpreadsheetCellIfNotExist(Worksheet worksheet, string cellName
130128
return worksheetPart?.Worksheet;
131129
}
132130

131+
// <Snippet2>
133132
// Given a cell name, parses the specified cell to get the column name.
134133
static string GetColumnName(string cellName)
135134
{
@@ -139,6 +138,9 @@ static string GetColumnName(string cellName)
139138

140139
return match.Value;
141140
}
141+
// </Snippet2>
142+
143+
// <Snippet3>
142144
// Given a cell name, parses the specified cell to get the row index.
143145
static uint GetRowIndex(string cellName)
144146
{
@@ -148,6 +150,5 @@ static uint GetRowIndex(string cellName)
148150

149151
return uint.Parse(match.Value);
150152
}
153+
// </Snippet3>
151154
// </Snippet0>
152-
153-
MergeTwoCells(args[0], args[1], args[2], args[3]);

samples/spreadsheet/merge_two_adjacent_cells/vb/Program.vb

Lines changed: 60 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
' <Snippet0>
21
Imports System.Text.RegularExpressions
32
Imports DocumentFormat.OpenXml
43
Imports DocumentFormat.OpenXml.Packaging
@@ -12,13 +11,12 @@ Module Program
1211
' Given a document name, a worksheet name, and the names of two adjacent cells, merges the two cells.
1312
' When two cells are merged, only the content from one cell is preserved:
1413
' the upper-left cell for left-to-right languages or the upper-right cell for right-to-left languages.
15-
Private Sub MergeTwoCells(ByVal docName As String, ByVal sheetName As String, ByVal cell1Name As String, ByVal cell2Name As String)
14+
' <Snippet0>
15+
Sub MergeTwoCells(docName As String, sheetName As String, cell1Name As String, cell2Name As String)
1616
' Open the document for editing.
17-
Dim document As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True)
18-
19-
Using (document)
17+
Using document As SpreadsheetDocument = SpreadsheetDocument.Open(docName, True)
2018
Dim worksheet As Worksheet = GetWorksheet(document, sheetName)
21-
If ((worksheet Is Nothing) OrElse (String.IsNullOrEmpty(cell1Name) OrElse String.IsNullOrEmpty(cell2Name))) Then
19+
If worksheet Is Nothing OrElse String.IsNullOrEmpty(cell1Name) OrElse String.IsNullOrEmpty(cell2Name) Then
2220
Return
2321
End If
2422

@@ -27,103 +25,108 @@ Module Program
2725
CreateSpreadsheetCellIfNotExist(worksheet, cell2Name)
2826

2927
Dim mergeCells As MergeCells
30-
If (worksheet.Elements(Of MergeCells)().Count() > 0) Then
31-
mergeCells = worksheet.Elements(Of MergeCells).First()
28+
If worksheet.Elements(Of MergeCells)().Count() > 0 Then
29+
mergeCells = worksheet.Elements(Of MergeCells)().First()
3230
Else
3331
mergeCells = New MergeCells()
3432

3533
' Insert a MergeCells object into the specified position.
36-
If (worksheet.Elements(Of CustomSheetView)().Count() > 0) Then
34+
If worksheet.Elements(Of CustomSheetView)().Count() > 0 Then
3735
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of CustomSheetView)().First())
38-
ElseIf (worksheet.Elements(Of DataConsolidate)().Count() > 0) Then
36+
ElseIf worksheet.Elements(Of DataConsolidate)().Count() > 0 Then
3937
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of DataConsolidate)().First())
40-
ElseIf (worksheet.Elements(Of SortState)().Count() > 0) Then
38+
ElseIf worksheet.Elements(Of SortState)().Count() > 0 Then
4139
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of SortState)().First())
42-
ElseIf (worksheet.Elements(Of AutoFilter)().Count() > 0) Then
40+
ElseIf worksheet.Elements(Of AutoFilter)().Count() > 0 Then
4341
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of AutoFilter)().First())
44-
ElseIf (worksheet.Elements(Of Scenarios)().Count() > 0) Then
42+
ElseIf worksheet.Elements(Of Scenarios)().Count() > 0 Then
4543
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of Scenarios)().First())
46-
ElseIf (worksheet.Elements(Of ProtectedRanges)().Count() > 0) Then
44+
ElseIf worksheet.Elements(Of ProtectedRanges)().Count() > 0 Then
4745
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of ProtectedRanges)().First())
48-
ElseIf (worksheet.Elements(Of SheetProtection)().Count() > 0) Then
46+
ElseIf worksheet.Elements(Of SheetProtection)().Count() > 0 Then
4947
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of SheetProtection)().First())
50-
ElseIf (worksheet.Elements(Of SheetCalculationProperties)().Count() > 0) Then
48+
ElseIf worksheet.Elements(Of SheetCalculationProperties)().Count() > 0 Then
5149
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of SheetCalculationProperties)().First())
5250
Else
5351
worksheet.InsertAfter(mergeCells, worksheet.Elements(Of SheetData)().First())
5452
End If
5553
End If
5654

5755
' Create the merged cell and append it to the MergeCells collection.
58-
Dim mergeCell As MergeCell = New MergeCell()
59-
mergeCell.Reference = New StringValue((cell1Name + (":" + cell2Name)))
56+
Dim mergeCell As New MergeCell() With {
57+
.Reference = New StringValue(cell1Name & ":" & cell2Name)
58+
}
6059
mergeCells.Append(mergeCell)
61-
62-
worksheet.Save()
6360
End Using
6461
End Sub
6562

66-
' Given a SpreadsheetDocument and a worksheet name, get the specified worksheet.
67-
Private Function GetWorksheet(ByVal document As SpreadsheetDocument, ByVal worksheetName As String) As Worksheet
68-
Dim sheets As IEnumerable(Of Sheet) = document.WorkbookPart.Workbook.Descendants(Of Sheet)().Where(Function(s) s.Name = worksheetName)
69-
If (sheets.Count = 0) Then
70-
' The specified worksheet does not exist.
71-
Return Nothing
72-
End If
73-
Dim worksheetPart As WorksheetPart = CType(document.WorkbookPart.GetPartById(sheets.First.Id), WorksheetPart)
74-
75-
Return worksheetPart.Worksheet
76-
End Function
77-
63+
' <Snippet1>
7864
' Given a Worksheet and a cell name, verifies that the specified cell exists.
79-
' If it does not exist, creates a new cell.
80-
Private Sub CreateSpreadsheetCellIfNotExist(ByVal worksheet As Worksheet, ByVal cellName As String)
65+
' If it does not exist, creates a new cell.
66+
Sub CreateSpreadsheetCellIfNotExist(worksheet As Worksheet, cellName As String)
8167
Dim columnName As String = GetColumnName(cellName)
8268
Dim rowIndex As UInteger = GetRowIndex(cellName)
8369

84-
Dim rows As IEnumerable(Of Row) = worksheet.Descendants(Of Row)().Where(Function(r) r.RowIndex.Value = rowIndex.ToString())
85-
86-
' If the worksheet does not contain the specified row, create the specified row.
87-
' Create the specified cell in that row, and insert the row into the worksheet.
88-
If (rows.Count = 0) Then
89-
Dim row As Row = New Row()
90-
row.RowIndex = New UInt32Value(rowIndex)
91-
92-
Dim cell As Cell = New Cell()
93-
cell.CellReference = New StringValue(cellName)
94-
70+
Dim rows As IEnumerable(Of Row) = worksheet.Descendants(Of Row)().Where(Function(r) r.RowIndex?.Value = rowIndex)
71+
72+
' If the Worksheet does not contain the specified row, create the specified row.
73+
' Create the specified cell in that row, and insert the row into the Worksheet.
74+
If rows.Count() = 0 Then
75+
Dim row As New Row() With {
76+
.RowIndex = New UInt32Value(rowIndex)
77+
}
78+
Dim cell As New Cell() With {
79+
.CellReference = New StringValue(cellName)
80+
}
9581
row.Append(cell)
9682
worksheet.Descendants(Of SheetData)().First().Append(row)
97-
worksheet.Save()
9883
Else
9984
Dim row As Row = rows.First()
100-
Dim cells As IEnumerable(Of Cell) = row.Elements(Of Cell)().Where(Function(c) c.CellReference.Value = cellName)
10185

102-
' If the row does not contain the specified cell, create the specified cell.
103-
If (cells.Count = 0) Then
104-
Dim cell As Cell = New Cell
105-
cell.CellReference = New StringValue(cellName)
86+
Dim cells As IEnumerable(Of Cell) = row.Elements(Of Cell)().Where(Function(c) c.CellReference?.Value = cellName)
10687

88+
' If the row does not contain the specified cell, create the specified cell.
89+
If cells.Count() = 0 Then
90+
Dim cell As New Cell() With {
91+
.CellReference = New StringValue(cellName)
92+
}
10793
row.Append(cell)
108-
worksheet.Save()
10994
End If
11095
End If
11196
End Sub
97+
' </Snippet1>
98+
99+
' Given a SpreadsheetDocument and a worksheet name, get the specified worksheet.
100+
Function GetWorksheet(document As SpreadsheetDocument, worksheetName As String) As Worksheet
101+
Dim workbookPart As WorkbookPart = If(document.WorkbookPart, document.AddWorkbookPart())
102+
Dim sheets As IEnumerable(Of Sheet) = workbookPart.Workbook.Descendants(Of Sheet)().Where(Function(s) s.Name = worksheetName)
103+
104+
Dim id As String = sheets.First().Id
105+
Dim worksheetPart As WorksheetPart = If(id IsNot Nothing, CType(workbookPart.GetPartById(id), WorksheetPart), Nothing)
112106

107+
Return If(worksheetPart IsNot Nothing, worksheetPart.Worksheet, Nothing)
108+
End Function
109+
110+
' <Snippet2>
113111
' Given a cell name, parses the specified cell to get the column name.
114-
Private Function GetColumnName(ByVal cellName As String) As String
112+
Function GetColumnName(cellName As String) As String
115113
' Create a regular expression to match the column name portion of the cell name.
116-
Dim regex As Regex = New Regex("[A-Za-z]+")
114+
Dim regex As New Regex("[A-Za-z]+")
117115
Dim match As Match = regex.Match(cellName)
116+
118117
Return match.Value
119118
End Function
119+
' </Snippet2>
120120

121+
' <Snippet3>
121122
' Given a cell name, parses the specified cell to get the row index.
122-
Private Function GetRowIndex(ByVal cellName As String) As UInteger
123+
Function GetRowIndex(cellName As String) As UInteger
123124
' Create a regular expression to match the row index portion the cell name.
124-
Dim regex As Regex = New Regex("\d+")
125+
Dim regex As New Regex("\d+")
125126
Dim match As Match = regex.Match(cellName)
127+
126128
Return UInteger.Parse(match.Value)
127129
End Function
130+
' </Snippet3>
131+
' </Snippet0>
128132
End Module
129-
' </Snippet0>

0 commit comments

Comments
 (0)