Class Workbook
Represents an Excel workbook with methods for creating, modifying, and saving content.
public class Workbook : IDisposable
- Inheritance
-
Workbook
- Implements
- Inherited Members
Constructors
Workbook()
Default constructor to create a new workbook.
public Workbook()
Workbook(string)
Overloaded constructor to open an existing workbook from a file.
public Workbook(string filePath)
Parameters
filePath
string
Fields
spreadsheetDocument
protected SpreadsheetDocument spreadsheetDocument
Field Value
stylesPart
protected WorkbookStylesPart stylesPart
Field Value
workbookpart
protected WorkbookPart workbookpart
Field Value
worksheetPart
protected WorksheetPart worksheetPart
Field Value
Properties
BuiltinDocumentProperties
Get or set built-in document properties of the workbook.
public BuiltInDocumentProperties BuiltinDocumentProperties { get; set; }
Property Value
DefaultStyleId
Get the ID of the default style.
public uint DefaultStyleId { get; }
Property Value
Worksheets
public List<Worksheet> Worksheets { get; }
Property Value
Methods
AddSheet(string)
Adds a new worksheet to the workbook with the specified name.
public Worksheet AddSheet(string sheetName)
Parameters
sheetName
stringThe name of the worksheet to be added. The name must be unique within the workbook and comply with Excel's naming rules (e.g., no special characters).
Returns
Examples
The following code demonstrates how to add a new worksheet to a workbook:
Workbook workbook = new Workbook("example.xlsx");
Worksheet newSheet = workbook.AddSheet("Sheet1");
workbook.Save();
Remarks
This method performs the following actions:
- Creates a new WorksheetPart and initializes its SheetData.
- Registers the worksheet with the workbook and assigns it a unique ID.
- Adds the new worksheet to the internal Worksheets collection of the workbook.
- Appends the new worksheet as a Sheet element in the workbook's Sheets collection.
Exceptions
- ArgumentException
Thrown if the
sheetName
is null, empty, or duplicates an existing sheet name.
CopySheet(string, string)
Copies an existing worksheet within the workbook and creates a new worksheet with the specified name.
public bool CopySheet(string sourceSheetName, string newSheetName)
Parameters
sourceSheetName
stringThe name of the existing worksheet to be copied. This must match the name of an existing worksheet in the workbook.
newSheetName
stringThe name of the new worksheet to be created. The name must be unique within the workbook and comply with Excel's naming rules (e.g., no special characters or exceeding 31 characters).
Returns
- bool
true
if the worksheet is successfully copied; otherwise,false
.
Examples
The following code demonstrates how to copy an existing worksheet to a new worksheet:
Workbook workbook = new Workbook("example.xlsx");
bool success = workbook.CopySheet("SourceSheet", "CopiedSheet");
if (success)
{
Console.WriteLine("Worksheet copied successfully.");
}
else
{
Console.WriteLine("Source worksheet not found or copying failed.");
}
workbook.Save();
Remarks
This method performs the following actions:
- Locates the source worksheet using the
sourceSheetName
. - Clones the WorksheetPart of the source worksheet to create a new worksheet part.
- Assigns the cloned worksheet part to a new Sheet with the specified
newSheetName
. - Appends the new worksheet to the workbook's Sheets collection.
- Saves the changes to the workbook.
Exceptions
- ArgumentException
Thrown if
sourceSheetName
ornewSheetName
is null, empty, or violates Excel's naming conventions.
CreateStyle(string, double, string, HorizontalAlignment?, VerticalAlignment?)
Creates a custom style for a cell in the workbook with specified font settings, color, and optional text alignment (horizontal and vertical).
public uint CreateStyle(string fontName, double fontSize, string hexColor, HorizontalAlignment? horizontalAlignment = null, VerticalAlignment? verticalAlignment = null)
Parameters
fontName
stringThe name of the font to be used in the style (e.g., "Arial").
fontSize
doubleThe size of the font in points. Must be greater than zero.
hexColor
stringThe color of the text in hexadecimal format (e.g., "000000" for black or "FF0000" for red). Must be a valid hex color code.
horizontalAlignment
HorizontalAlignment?Optional. The horizontal alignment for the text within the cell. Acceptable values are defined in the HorizontalAlignment enumeration (e.g., Center or Left).
verticalAlignment
VerticalAlignment?Optional. The vertical alignment for the text within the cell. Acceptable values are defined in the VerticalAlignment enumeration (e.g., Center or Top).
Returns
- uint
A uint representing the unique index of the created style within the workbook's stylesheet. This index can be assigned to a cell to apply the style.
Remarks
This method leverages the underlying style utility to create and register a new style in the workbook's stylesheet. If no alignment is specified, default text alignment is applied.
Dispose()
This method releases unmanaged resources.
public void Dispose()
Dispose(bool)
Releases the unmanaged resources and optionally releases the managed resources.
protected virtual void Dispose(bool disposing)
Parameters
disposing
bool
GetHiddenSheets()
Retrieves a list of hidden or very hidden sheets from the workbook.
public List<Tuple<string, string>> GetHiddenSheets()
Returns
- List<Tuple<string, string>>
A list of tuples where each tuple contains the sheet ID and sheet name for hidden sheets.
Exceptions
- InvalidOperationException
Thrown when the workbook part is not initialized.
- ArgumentNullException
Thrown when a sheet's ID or Name is null.
RemoveSheet(string)
Removes a worksheet from the workbook by its name.
public bool RemoveSheet(string sheetName)
Parameters
sheetName
stringThe name of the worksheet to be removed. The name must match an existing worksheet in the workbook.
Returns
- bool
true
if the worksheet was successfully removed; otherwise,false
.
Examples
The following code demonstrates how to remove a worksheet from a workbook:
Workbook workbook = new Workbook("example.xlsx");
bool success = workbook.RemoveSheet("Sheet1");
if (success)
{
Console.WriteLine("Worksheet removed successfully.");
}
else
{
Console.WriteLine("Worksheet not found.");
}
workbook.Save();
Remarks
This method performs the following actions:
- Searches the workbook for a sheet with the specified name.
- Removes the corresponding Sheet element from the workbook's Sheets collection.
- Deletes the associated WorksheetPart from the workbook's WorkbookPart.
- Synchronizes the internal Worksheets collection to reflect the changes.
Exceptions
- ArgumentException
Thrown if
sheetName
is null, empty, or invalid.
RenameSheet(string, string)
Renames an existing worksheet within the workbook.
public bool RenameSheet(string existingSheetName, string newSheetName)
Parameters
existingSheetName
stringThe current name of the worksheet to be renamed. This must match the name of an existing worksheet in the workbook.
newSheetName
stringThe new name for the worksheet. The name must be unique within the workbook and comply with Excel's naming rules (e.g., no special characters or exceeding 31 characters).
Returns
- bool
true
if the worksheet is successfully renamed; otherwise,false
.
Examples
The following code demonstrates how to rename a worksheet in a workbook:
Workbook workbook = new Workbook("example.xlsx");
bool success = workbook.RenameSheet("OldSheetName", "NewSheetName");
if (success)
{
Console.WriteLine("Worksheet renamed successfully.");
}
else
{
Console.WriteLine("Worksheet not found or renaming failed.");
}
workbook.Save();
Remarks
This method searches the workbook for a worksheet with the specified existingSheetName
.
If found, it updates the sheet's name to newSheetName
and saves the changes.
The internal Worksheets collection is synchronized to reflect the updated name.
Exceptions
- ArgumentException
Thrown if
existingSheetName
ornewSheetName
is null, empty, or violates Excel's naming conventions.
ReorderSheets(string, int)
Reorders a sheet within the workbook to a new position.
public void ReorderSheets(string sheetName, int newPosition)
Parameters
sheetName
stringThe name of the sheet to be reordered.
newPosition
intThe new position (index) where the sheet should be moved.
Save()
Save the workbook using the original file path.
public void Save()
Save(Stream)
Save the workbook to a given stream.
public void Save(Stream stream)
Parameters
stream
Stream
Save(string)
Save the workbook to a specified file path.
public void Save(string filePath)
Parameters
filePath
string
SetSheetVisibility(string, SheetVisibility)
Sets the visibility of a sheet within the workbook.
public void SetSheetVisibility(string sheetName, SheetVisibility visibility)
Parameters
sheetName
stringThe name of the sheet whose visibility is to be set.
visibility
SheetVisibilityThe visibility state to be applied to the sheet (Visible, Hidden, or VeryHidden).
Exceptions
- ArgumentException
Thrown when the sheet is not found in the workbook.
UpdateDefaultStyle(string, double, string)
Update the default style of the workbook.
public void UpdateDefaultStyle(string newFontName, double newFontSize, string hexColor)