The DevExpress Spreadsheet Document API is a non-visual library that allows you to generate, import, export, modify, and print Microsoft Excel workbooks in code.
[!IMPORTANT]
You need a license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this library in production code.
This example demonstrates how to use the Spreadsheet Document API to execute the following actions:
- Apply filters to a worksheet range (a dynamic filter, the “Top 10” filter, number, text, and date filters)
- Save a worksheet in HTML format
- Group and ungroup worksheet rows and columns
- Outline worksheet data automatically
- Create subtotals for a cell range
- Insert a picture into a worksheet and modify an embedded picture
- Protect and unprotect a workbook or a worksheet
- Protect specific worksheet ranges
- Sort data in a range
- Manage tables and table styles
- Search for specific data in a worksheet
The application form contains the list of supported operations. A user can select an operation and click the Run button to view the resulting spreadsheet document in Microsoft Excel.
Files to Look At
Documentation
- Filter Data
- Custom XML parts
- Validate Data in Spreadsheet Cells
- Export a Document to HTML
- Group Data
- Pictures
- Protection
- Search
- Sorting
- Tables
More Examples
Does this example address your development requirements/objectives?
(you will be redirected to DevExpress.com to submit your response)
Example Code
C#using DevExpress.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace SpreadsheetDocServerAPIPart2
{
public static class AutoFilterActions
{
public static Action<Workbook> ApplyFilterAction = ApplyFilter;
public static Action<Workbook> FilterAndSortBySingleColumnAction = FilterAndSortBySingleColumn;
public static Action<Workbook> FilterAndSortByMultipleColumnsAction = FilterAndSortByMultipleColumns;
public static Action<Workbook> FilterNumericByConditionAction = FilterNumericByCondition;
public static Action<Workbook> FilterTextByConditionAction = FilterTextByCondition;
public static Action<Workbook> FilterByValueAction = FilterByValue;
public static Action<Workbook> FilterByMultipleValuesAction = FilterByMultipleValues;
public static Action<Workbook> FilterDatesByConditionAction = FilterDatesByCondition;
public static Action<Workbook> FilterMixedDataTypesByValuesAction = FilterMixedDataTypesByValues;
public static Action<Workbook> Top10FilterValueAction = Top10FilterValue;
public static Action<Workbook> DynamicFilterValueAction = DynamicFilterValue;
public static Action<Workbook> FilterAndSortByColorAction = FilterAndSortByColor;
public static Action<Workbook> FilterByBackgroundColorAction = FilterByBackgroundColor;
public static Action<Workbook> FilterByFillColorAction = FilterByFillColor;
public static Action<Workbook> FilterByFontColorAction = FilterByFontColor;
public static Action<Workbook> ReapplyFilterValueAction = ReapplyFilterValue;
public static Action<Workbook> ClearFilterAction = ClearFilter;
public static Action<Workbook> DisableFilterAction = DisableFilter;
static void ApplyFilter(Workbook workbook)
{
#region #ApplyFilter
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
#endregion #ApplyFilter
}
static void FilterAndSortBySingleColumn(Workbook workbook)
{
#region #FilterAndSortBySingleColumn
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Sort data in the "B2:E23" range
// in descending order by column "A".
worksheet.AutoFilter.SortState.Sort(0, true);
#endregion #FilterAndSortBySingleColumn
}
static void FilterAndSortByMultipleColumns(Workbook workbook)
{
#region #FilterAndSortByMultipleColumns
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Sort data in the "B2:E23" range
// in descending order by columns "A" and "C".
List<SortCondition> sortConditions = new List<SortCondition>();
Color color = worksheet["D12"].Font.Color;
sortConditions.Add(new SortCondition(0, true));
sortConditions.Add(new SortCondition(2, color, false));
worksheet.AutoFilter.SortState.Sort(sortConditions);
#endregion #FilterAndSortByMultipleColumns
}
static void FilterNumericByCondition(Workbook workbook)
{
#region #FilterNumbersByCondition
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Sales" column that are in a range from 5000$ to 8000$.
AutoFilterColumn sales = worksheet.AutoFilter.Columns[2];
sales.ApplyCustomFilter(5000, FilterComparisonOperator.GreaterThanOrEqual, 8000, FilterComparisonOperator.LessThanOrEqual, true);
#endregion #FilterNumbersByCondition
}
static void FilterTextByCondition(Workbook workbook)
{
#region #FilterTextByCondition
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Product" column that contain "Gi" and include empty cells.
AutoFilterColumn products = worksheet.AutoFilter.Columns[1];
products.ApplyCustomFilter("*Gi*", FilterComparisonOperator.Equal, FilterValue.FilterByBlank, FilterComparisonOperator.Equal, false);
#endregion #FilterTextByCondition
}
static void FilterByValue(Workbook workbook)
{
#region #FilterBySingleValue
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter data in the "Product" column by a specific value.
worksheet.AutoFilter.Columns[1].ApplyFilterCriteria("Mozzarella di Giovanni");
#endregion #FilterBySingleValue
}
static void FilterByMultipleValues(Workbook workbook)
{
#region #FilterByMultipleValues
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter data in the "Product" column by an array of values.
worksheet.AutoFilter.Columns[1].ApplyFilterCriteria(new CellValue[] { "Mozzarella di Giovanni", "Gorgonzola Telino" });
#endregion #FilterByMultipleValues
}
static void FilterDatesByCondition(Workbook workbook)
{
#region #FilterDatesByCondition
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Reported Date" column
// to display dates that are between June 1, 2014 and February 1, 2015.
worksheet.AutoFilter.Columns[3].ApplyCustomFilter
(new DateTime(2014, 6, 1), FilterComparisonOperator.GreaterThanOrEqual,
new DateTime(2015, 2, 1), FilterComparisonOperator.LessThanOrEqual, true);
#endregion #FilterDatesByCondition
}
static void FilterMixedDataTypesByValues(Workbook workbook)
{
#region #FilterMixedDataByValues
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Create date grouping item to filter January 2015 dates.
IList<DateGrouping> groupings = new List<DateGrouping>();
DateGrouping dateGroupingJan2015 = new DateGrouping(new DateTime(2015, 1, 1), DateTimeGroupingType.Month);
groupings.Add(dateGroupingJan2015);
// Filter data in the "Reported Date" column
// to display values reported in January 2015.
worksheet.AutoFilter.Columns[3].ApplyFilterCriteria("gennaio 2015", groupings);
#endregion #FilterMixedDataByValues
}
static void Top10FilterValue(Workbook workbook)
{
#region #TopTenFilter
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Apply a filter to the "Sales" column to display the top ten values.
worksheet.AutoFilter.Columns[2].ApplyTop10Filter(Top10Type.Top10Items, 10);
#endregion #TopTenFilter
}
static void DynamicFilterValue(Workbook workbook)
{
#region #DynamicFilter
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Apply a dynamic filter to the "Sales" column
// to display only values that are above the average.
worksheet.AutoFilter.Columns[2].ApplyDynamicFilter(DynamicFilterType.AboveAverage);
// Apply a dynamic filter to the "Reported Date" column
// to display values reported this year.
worksheet.AutoFilter.Columns[3].ApplyDynamicFilter(DynamicFilterType.ThisYear);
#endregion #DynamicFilter
}
static void FilterAndSortByColor(Workbook workbook)
{
#region #FilterAndSortByColor
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Sort data in the "B2:E23" range
// in descending order by column "D".
Color color = worksheet["D12"].Font.Color;
worksheet.AutoFilter.SortState.Sort(2, color, false);
#endregion #FilterAndSortByColor
}
static void FilterByBackgroundColor(Workbook workbook)
{
#region #FilterByBackgroundColor
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Products" column by background color.
AutoFilterColumn products = worksheet.AutoFilter.Columns[1];
products.ApplyFillColorFilter(worksheet["C12"].FillColor);
#endregion #FilterByBackgroundColor
}
static void FilterByFillColor(Workbook workbook)
{
#region #FilterByFillColor
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Products" column by fill color.
AutoFilterColumn products = worksheet.AutoFilter.Columns[1];
products.ApplyFillFilter(worksheet["C10"].Fill);
#endregion #FilterByFillColor
}
static void FilterByFontColor(Workbook workbook)
{
#region #FilterByFontColor
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Sales" column by font color.
AutoFilterColumn products = worksheet.AutoFilter.Columns[2];
products.ApplyFontColorFilter(worksheet["D10"].Font.Color);
#endregion #FilterByFontColor
}
static void ReapplyFilterValue(Workbook workbook)
{
#region #ReapplyFilter
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Sales" column that are greater than 5000$.
worksheet.AutoFilter.Columns[2].ApplyCustomFilter(5000, FilterComparisonOperator.GreaterThan);
// Change data and reapply the filter.
worksheet["D3"].Value = 5000;
worksheet.AutoFilter.ReApply();
#endregion #ReapplyFilter
}
static void ClearFilter(Workbook workbook)
{
#region #ClearFilter
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Filter values in the "Sales" column that are greater than 5000$.
worksheet.AutoFilter.Columns[2].ApplyCustomFilter(5000, FilterComparisonOperator.GreaterThan);
// Clear the filter.
worksheet.AutoFilter.Clear();
#endregion #ClearFilter
}
static void DisableFilter(Workbook workbook)
{
#region #DisableFilter
Worksheet worksheet = workbook.Worksheets["Regional sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Enable filtering for the "B2:E23" cell range.
CellRange range = worksheet["B2:E23"];
worksheet.AutoFilter.Apply(range);
// Disable filtering for the entire worksheet.
worksheet.AutoFilter.Disable();
#endregion #DisableFilter
}
}
}
C#using DevExpress.Spreadsheet;
using DevExpress.XtraCharts;
using System;
using System.Xml;
namespace SpreadsheetDocServerAPIPart2
{
class CustomXmlPartActions
{
public static Action<Workbook> StoreCustomXmlPartAction = StoreCustomXmlPart;
public static Action<Workbook> ObtainCustomXmlPartAction = ObtainCustomXmlPart;
public static Action<Workbook> ModifyCustomXmlPartAction = ModifyCustomXmlPart;
static void StoreCustomXmlPart(Workbook workbook)
{
#region #StoreCustomXmlPart
workbook.Worksheets[0].Cells["A1"].Value = "Custom Xml Test";
// Add an empty custom XML part.
ICustomXmlPart part = workbook.CustomXmlParts.Add();
XmlElement elem = part.CustomXmlPartDocument.CreateElement("Person");
elem.InnerText = "Stephen Edwards";
part.CustomXmlPartDocument.AppendChild(elem);
// Add an XML part created from string.
string xmlString = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<whitepaper>
<contact>
<firstname>Roger</firstname>
<lastname>Edwards</lastname>
<phone>832-433-0025</phone>
<address>1657 Wines Lane Houston, TX 77099</address>
</contact>
<date>2016-05-18</date>
</whitepaper>";
workbook.CustomXmlParts.Add(xmlString);
// Add an XML part loaded from a file.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("..\\..\\..\\Documents\\fishes.xml");
workbook.CustomXmlParts.Add(xmlDoc);
workbook.SaveDocument("..\\..\\..\\Documents\\CustomXmlTest.xlsx");
System.IO.File.Copy("..\\..\\..\\Documents\\CustomXmlTest.xlsx", "..\\..\\..\\Documents\\CustomXmlTest.xlsx.zip", true);
System.Diagnostics.Process.Start("..\\..\\..\\Documents\\CustomXmlTest.xlsx.zip");
#endregion #StoreCustomXmlPart
}
static void ObtainCustomXmlPart(IWorkbook workbook)
{
#region #ObtainCustomXmlPart
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\CustomXml.xlsx");
// Access a custom XML file stored in the document.
XmlDocument xmlDoc = workbook.CustomXmlParts[0].CustomXmlPartDocument;
// Retrieve a hyperlink from the XML file and display it in the document.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
string xPathString = "//Fish[Category='Cod']/ScientificClassification/Reference";
XmlNode xmlNode = xmlDoc.DocumentElement.SelectSingleNode(xPathString, nsmgr);
string hLink = xmlNode.InnerText;
workbook.Worksheets[0].Hyperlinks.Add(workbook.Worksheets[0].Cells["A2"], hLink, true);
#endregion #ObtainCustomXmlPart
}
static void ModifyCustomXmlPart(IWorkbook workbook)
{
#region #ModifyCustomXmlPart
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\CustomXml.xlsx");
// Access a custom XML file stored in the document.
XmlDocument xmlDoc = workbook.CustomXmlParts[1].CustomXmlPartDocument;
// Retrieve XML nodes that match a specific expression.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
string xPathString = "//whitepaper/contact[firstname='Roger']/firstname";
XmlNodeList xmlNodes = xmlDoc.DocumentElement.SelectNodes(xPathString, nsmgr);
// Modify XML nodes and display them in the document.
foreach (XmlNode node in xmlNodes) node.InnerText = "Stephen";
workbook.SaveDocument("..\\..\\..\\Documents\\CustomXmlRogerStephen.xlsx");
workbook.Worksheets[0].Cells["A2"].Value = xmlDoc.FirstChild.FirstChild.FirstChild.InnerText;
#endregion #ModifyCustomXmlPart
}
}
}
C#using System;
using DevExpress.Spreadsheet;
using System.Drawing;
using System.Linq;
using DevExpress.XtraCharts;
using DevExpress.XtraExport.Helpers;
namespace SpreadsheetDocServerAPIPart2
{
public static class DataValidationActions {
public static Action<Workbook> AddDataValidationAction = AddDataValidation;
public static Action<Workbook> ChangeCriteriaAction = ChangeCriteria;
public static Action<Workbook> UseUnionRangeAction = UseUnionRange;
public static Action<Workbook> ShowInputMessageAction = ShowInputMessage;
public static Action<Workbook> ShowErrorMessageAction = ShowErrorMessage;
public static Action<Workbook> GetDataValidationAction = GetDataValidation;
public static Action<Workbook> ValidateCellValueAction = ValidateCellValue;
public static Action<Workbook> RemoveDataValidationAction = RemoveDataValidation;
public static Action<Workbook> RemoveAllDataValidationsAction = RemoveAllDataValidations;
static void AddDataValidation(IWorkbook workbook) {
#region #AddDataValidation
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Specify the "C1" cell value.
worksheet["C1"].SetValue(DateTime.Now);
worksheet["C1"].NumberFormat = "mmm/d/yyyy h:mm";
// Restrict data entry to a whole number from 10 to 20.
worksheet.DataValidations.Add(worksheet["B1"],
DataValidationType.WholeNumber, DataValidationOperator.Between, 10, 20);
// Restrict data entry to a number within limits.
DataValidation validation = worksheet.DataValidations.Add(worksheet["F4:F11"], DataValidationType.Decimal, DataValidationOperator.Between, 10, 40);
// Restrict data entry based on a formula.
worksheet.DataValidations.Add(worksheet["B4:B11"], DataValidationType.Custom, "=AND(ISNUMBER(B4),LEN(B4)=5)");
// Restrict data entry to 3 symbols.
worksheet.DataValidations.Add(worksheet["D4:D11"], DataValidationType.TextLength, DataValidationOperator.Equal, 3);
// Restrict data entry to values in a drop-down list specified in code.
// Note that the list in code uses comma to separate entries,
// but the list in UI displays a culture-specific list separator.
worksheet.DataValidations.Add(worksheet["A4:A11"], DataValidationType.List, "PASS, FAIL");
// Restrict data entry to values in a drop-down list obtained from a worksheet.
worksheet.DataValidations.Add(worksheet["E4:E11"], DataValidationType.List, ValueObject.FromRange(worksheet["H4:H9"].GetRangeWithAbsoluteReference()));
// Restrict data entry to a time before the specified time.
worksheet.DataValidations.Add(worksheet["C1"], DataValidationType.Time, DataValidationOperator.LessThanOrEqual, DateTime.Now);
// Highlight data validation ranges.
worksheet["H4:H9"].FillColor = Color.LightGray;
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3, 0xFFDFC4, 0xFFDAE9};
for (int i = 0; i < worksheet.DataValidations.Count; i++){
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #AddDataValidation
}
static void ChangeCriteria(IWorkbook workbook) {
#region #ChangeCriteria
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Restrict data entry to a number within limits.
DataValidation validation = worksheet.DataValidations.Add
(worksheet["F4:F11"], DataValidationType.Decimal, DataValidationOperator.Between, 10, 40);
// Change the validation operator and criteria.
// The "F4:F11" range's cell values are valid
// if they are greater than or equal 20.
validation.Operator = DataValidationOperator.GreaterThanOrEqual;
validation.Criteria = 20;
validation.Criteria2 = ValueObject.Empty;
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #ChangeCriteria
}
static void UseUnionRange(IWorkbook workbook) {
#region #UseUnionRange
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Create a union range.
CellRange range = worksheet.Range.Union(worksheet["F4:F5"], worksheet["F6:F11"]);
// Restrict data entry to a number within limits.
worksheet.DataValidations.Add(range, DataValidationType.Decimal, DataValidationOperator.Between, 10, 40);
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #UseUnionRange
}
static void ShowInputMessage(IWorkbook workbook) {
#region #ShowInputMessage
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Restrict data entry to a 5-digit number.
DataValidation validation = worksheet.DataValidations.Add(worksheet["B4:B11"], DataValidationType.Custom, "=AND(ISNUMBER(B4),LEN(B4)=5)");
// Show input message.
validation.InputTitle = "Employee Id";
validation.InputMessage = "Please enter 5-digit number";
validation.ShowInputMessage = true;
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #ShowInputMessage
}
static void ShowErrorMessage(IWorkbook workbook) {
#region #ShowErrorMessage
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Restrict data entry to a 5-digit number.
DataValidation validation = worksheet.DataValidations.Add(worksheet["B4:B11"], DataValidationType.Custom, "=AND(ISNUMBER(B4),LEN(B4)=5)");
// Show error message.
validation.ErrorTitle = "Wrong Employee Id";
validation.ErrorMessage = "The value you entered is not valid. Use 5-digit number for the employee ID.";
validation.ErrorStyle = DataValidationErrorStyle.Information;
validation.ShowErrorMessage = true;
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #ShowErrorMessage
}
static void GetDataValidation(IWorkbook workbook)
{
#region #GetDataValidation
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Add data validations.
worksheet.DataValidations.Add(worksheet["D4:D11"], DataValidationType.TextLength, DataValidationOperator.Equal, 3);
worksheet.DataValidations.Add(worksheet["E4:E11"], DataValidationType.List, ValueObject.FromRange(worksheet["H4:H9"].GetRangeWithAbsoluteReference()));
// Get data validation entry associated with the "E4" cell.
worksheet.DataValidations.GetDataValidation(worksheet.Cells["E4"]).Criteria = ValueObject.FromRange(worksheet["H4:H5"]);
// Get data validation entries for the "D4:E11" range.
var myValidation = worksheet.DataValidations.GetDataValidations(worksheet["D4:E11"])
.Where(d => d.ValidationType == DataValidationType.TextLength).SingleOrDefault();
if (myValidation != null) myValidation.Criteria = 4;
// Get data validation entries that meet a specific criteria.
foreach (var d in worksheet.DataValidations.GetDataValidations(DataValidationType.TextLength, DataValidationOperator.Equal, 4, ValueObject.Empty))
{
// Change the validation operator.
// The "D4:D11" range's cell values are valid
// if they contain text with more than 4 characters.
d.Operator = DataValidationOperator.GreaterThan;
}
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #GetDataValidation
}
static void ValidateCellValue(IWorkbook workbook)
{
#region #ValidateCellValue
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Add data validations.
worksheet.DataValidations.Add(worksheet["D4:D11"], DataValidationType.TextLength, DataValidationOperator.Equal, 3);
// Check whether the cell value meets a validation criteria.
bool isValid = worksheet.DataValidations.Validate(worksheet.Cells["D4"], worksheet.Cells["J4"].Value);
if (isValid) { worksheet["D4"].CopyFrom(worksheet["J4"]); }
#endregion #ValidateCellValue
}
static void RemoveDataValidation(IWorkbook workbook) {
#region #RemoveDataValidation
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Add data validations.
worksheet.DataValidations.Add(worksheet["D4:D11"], DataValidationType.TextLength, DataValidationOperator.Equal, 3);
worksheet.DataValidations.Add(worksheet["E4:E11"], DataValidationType.List, ValueObject.FromRange(worksheet["H4:H9"].GetRangeWithAbsoluteReference()));
// Remove a data validation by its index.
worksheet.DataValidations.RemoveAt(1);
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #RemoveDataValidation
}
static void RemoveAllDataValidations(IWorkbook workbook) {
#region #RemoveAllDataValidations
// Load a document from a file.
workbook.LoadDocument("..\\..\\..\\Documents\\DataValidation.xlsx");
// Access a worksheet.
Worksheet worksheet = workbook.Worksheets[0];
// Add data validations.
worksheet.DataValidations.Add(worksheet["D4:D11"], DataValidationType.TextLength, DataValidationOperator.Equal, 3);
worksheet.DataValidations.Add(worksheet["E4:E11"], DataValidationType.List, ValueObject.FromRange(worksheet["H4:H9"].GetRangeWithAbsoluteReference()));
// Remove all data validations.
worksheet.DataValidations.Clear();
// Highlight data validation ranges.
int[] MyColorScheme = new int[] { 0xFFC4C4, 0xFFD9D9, 0xFFF6F6, 0xFFECEC, 0xE9D3D3 };
for (int i = 0; i < worksheet.DataValidations.Count; i++)
{
worksheet.DataValidations[i].Range.FillColor = Color.FromArgb(MyColorScheme[i]);
}
#endregion #RemoveAllDataValidations
}
}
}
C#using DevExpress.Spreadsheet;
using DevExpress.XtraSpreadsheet.Export;
using System;
using System.IO;
namespace SpreadsheetDocServerAPIPart2
{
public static class ExportActions
{
public static Action<Workbook> ExportDocToHTMLAction = ExportDocToHTML;
private static void ExportDocToHTML(Workbook workbook)
{
#region #ExportToHTML
Worksheet worksheet = workbook.Worksheets["Grouping"];
workbook.Worksheets.ActiveWorksheet = worksheet;
HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions();
// Specify the cell range you want to save as HTML.
options.SheetIndex = worksheet.Index;
options.Range = "B2:G7";
// Export data to HTML format.
using (FileStream htmlStream = new FileStream("OutputWorksheet.html", FileMode.Create))
{
workbook.ExportToHtml(htmlStream, options);
}
System.Diagnostics.Process.Start("OutputWorksheet.html");
#endregion #ExportToHTML
}
}
}
C#using DevExpress.Spreadsheet;
using System;
using System.Collections.Generic;
namespace SpreadsheetDocServerAPIPart2
{
public static class GroupAndOutlineActions
{
public static Action<Workbook> GroupRowsAction = GroupRows;
public static Action<Workbook> GroupColumnsAction = GroupColumns;
public static Action<Workbook> UngroupRowsAction = UngroupRows;
public static Action<Workbook> UngroupColumnsAction = UngroupColumns;
public static Action<Workbook> AutoOutlineAction = AutoOutline;
public static Action<Workbook> SubtotalAction = Subtotal;
static void GroupRows(IWorkbook workbook)
{
#region #GroupRows
Worksheet worksheet = workbook.Worksheets["Grouping"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Group rows 3 through 6 and collapse the group.
worksheet.Rows.Group(2, 5, true);
// Group rows 9 through 12 and expand the group.
worksheet.Rows.Group(8, 11, false);
// Group rows 2 through 13 to create the outer group.
worksheet.Rows.Group(1, 12, false);
#endregion #GroupRows
}
static void GroupColumns(IWorkbook workbook)
{
#region #GroupColumns
Worksheet worksheet = workbook.Worksheets["Grouping"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Group columns "C" through "F" and expand the group.
worksheet.Columns.Group(2, 5, false);
#endregion #GroupColumns
}
static void UngroupRows(IWorkbook workbook)
{
#region #UngroupRows
Worksheet worksheet = workbook.Worksheets["Grouping and Outline"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Ungroup rows 3 through 6 and display collapsed data.
worksheet.Rows.UnGroup(2, 5, true);
// Ungroup rows 9 through 12.
worksheet.Rows.UnGroup(8, 11, false);
// Remove the outer row group.
worksheet.Rows.UnGroup(1, 12, false);
#endregion #UngroupRows
}
static void UngroupColumns(IWorkbook workbook)
{
#region #UngroupColumns
Worksheet worksheet = workbook.Worksheets["Grouping and Outline"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Ungroup columns "C" through "F".
worksheet.Columns.UnGroup(2, 5, false);
#endregion #UngroupColumns
}
static void AutoOutline(IWorkbook workbook)
{
#region #AutoOutline
Worksheet worksheet = workbook.Worksheets["Grouping"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Outline data automatically based on the summary formulas.
worksheet.AutoOutline();
#endregion #AutoOutline
}
static void Subtotal(IWorkbook workbook)
{
#region #Subtotal
Worksheet worksheet = workbook.Worksheets["Regional Sales"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Obtain the target cell range.
CellRange dataRange = worksheet["B3:E23"];
// Calculate subtotals for column "D".
List<int> subtotalColumnsList = new List<int>();
subtotalColumnsList.Add(3);
// Insert subtotals by each change in column "B"
// and calculate the SUM fuction for the related rows in column "D".
worksheet.Subtotal(dataRange, 1, subtotalColumnsList, 9, "Total");
#endregion #Subtotal
}
}
}
C#using DevExpress.Spreadsheet;
using System;
using System.IO;
namespace SpreadsheetDocServerAPIPart2
{
public static class PictureActions
{
public static Action<Workbook> InsertPictureAction = InsertPicture;
public static Action<Workbook> ModifyPictureAction = ModifyPicture;
public static Action<Workbook> PlacePictureInCellAction = PlacePictureInCell;
static void InsertPicture(Workbook workbook)
{
#region #InsertPicture
workbook.BeginUpdate();
// Set the measurement unit to Millimeter.
workbook.Unit = DevExpress.Office.DocumentUnit.Millimeter;
try
{
Worksheet worksheet = workbook.Worksheets[0];
// Insert a picture from a file so that its top left corner is in the "A1" cell.
// Default picture names are Picture 1.. Picture NN.
worksheet.Pictures.AddPicture("Pictures\\x-docserver.png", worksheet.Cells["A1"]);
// Insert a picture at 70 mm from the left, 40 mm from the top,
// resize it to a width of 85 mm and a height of 25 mm, and lock the aspect ratio.
worksheet.Pictures.AddPicture("Pictures\\x-docserver.png", 70, 40, 85, 25, true);
// Insert a picture.
worksheet.Pictures.AddPicture("Pictures\\x-docserver.png", 0, 0);
// Find the last inserted picture by its name.
Picture picShape = worksheet.Pictures.GetPicturesByName("Picture 3")[0];
// Remove the last inserted picture.
picShape.Delete();
}
finally
{
workbook.EndUpdate();
}
#endregion #InsertPicture
}
static void ModifyPicture(Workbook workbook)
{
#region #ModifyPicture
// Set the measurement unit to Millimeter.
workbook.Unit = DevExpress.Office.DocumentUnit.Millimeter;
workbook.BeginUpdate();
try
{
Worksheet worksheet = workbook.Worksheets[0];
// Insert a picture from a file.
Picture pic = worksheet.Pictures.AddPicture("Pictures\\x-docserver.png", worksheet.Cells["A1"]);
// Specify the picture name and draw a border.
pic.Name = "Logo";
pic.AlternativeText = "Spreadsheet Logo";
pic.BorderWidth = 1;
pic.BorderColor = DevExpress.Utils.DXColor.Black;
// Move a picture.
pic.Move(20, 30);
// Specify picture behavior.
pic.Placement = Placement.MoveAndSize;
worksheet.Rows[5].Height += 10;
worksheet.Columns["D"].Width += 10;
// Specify the rotation angle.
pic.Rotation = 30;
// Add a hyperlink.
pic.InsertHyperlink("https://www.devexpress.com/products/net/office-file-api/", true);
}
finally
{
workbook.EndUpdate();
}
#endregion #ModifyPicture
}
static void PlacePictureInCell(Workbook workbook)
{
Worksheet worksheet = workbook.Worksheets[0];
byte[] imageBytes = File.ReadAllBytes("Pictures\\x-docserver.png");
MemoryStream imageStream = new MemoryStream(imageBytes);
workbook.BeginUpdate();
try
{
// Insert cell images from a stream
worksheet.Cells["A2"].Value = imageStream;
// Specify image information
if (worksheet.Cells["A2"].Value.IsCellImage)
{
worksheet.Cells["A2"].ImageInfo.Decorative = true;
worksheet.Cells["A2"].ImageInfo.AlternativeText = "Image AltText";
}
}
finally
{
workbook.EndUpdate();
}
}
}
}
C#using DevExpress.Spreadsheet;
using System;
using System.Drawing;
namespace SpreadsheetDocServerAPIPart2
{
public static class ProtectionActions
{
public static Action<Workbook> ProtectWorkbookAction = ProtectWorkbook;
public static Action<Workbook> UnprotectWorkbookAction = UnprotectWorkbook;
public static Action<Workbook> ProtectWorksheetAction = ProtectWorksheet;
public static Action<Workbook> UnprotectWorksheetAction = UnprotectWorksheet;
public static Action<Workbook> ProtectRangeAction = ProtectRange;
static void ProtectWorkbook(Workbook workbook)
{
#region #ProtectWorkbook
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Protect workbook structure with a password.
if (!workbook.IsProtected)
workbook.Protect("password", true, false);
// Add a note.
worksheet["B2"].Value = "Workbook structure is protected with a password. \n You cannot add, move or delete worksheets until protection is removed.";
worksheet.Visible = true;
#endregion #ProtectWorkbook
}
static void UnprotectWorkbook(Workbook workbook)
{
#region #UnprotectWorkbook
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Unprotect the workbook.
if (workbook.IsProtected)
workbook.Unprotect("password");
// Add a note.
worksheet["B2"].Value = "Workbook is unprotected. Workheets can be added, moved or deleted.";
worksheet.Visible = true;
#endregion #UnprotectWorkbook
}
static void ProtectWorksheet(Workbook workbook)
{
#region #ProtectWorksheet
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Protect the worksheet with a password.
if (!worksheet.IsProtected)
worksheet.Protect("password", WorksheetProtectionPermissions.Default);
// Add a note.
worksheet["B2"].Value = "Worksheet is protected with a password. \n You cannot edit or format cells until protection is removed." +
"\nTo remove protection, on the Review tab, in the Changes group," +
"\nclick \"Unprotect Sheet\" and enter \"password\".";
worksheet.Visible = true;
#endregion #ProtectWorksheet
}
static void UnprotectWorksheet(Workbook workbook)
{
#region #UnprotectWorksheet
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Unprotect the worksheet.
if (worksheet.IsProtected)
worksheet.Unprotect("password");
// Add a note.
worksheet["B2"].Value = "Worksheet is unprotected. You can edit and format cells.";
worksheet.Visible = true;
#endregion
}
static void ProtectRange(Workbook workbook)
{
#region #ProtectRange
Worksheet worksheet = workbook.Worksheets["ProtectionSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
worksheet["B2:J5"].Borders.SetOutsideBorders(Color.Red, BorderLineStyle.Thin);
// Specify user permission to edit a range in a protected worksheet.
ProtectedRange protectedRange = worksheet.ProtectedRanges.Add("My Range", worksheet["B2:J5"]);
EditRangePermission permission = new EditRangePermission();
permission.UserName = Environment.UserName;
permission.DomainName = Environment.UserDomainName;
permission.Deny = false;
protectedRange.SecurityDescriptor = protectedRange.CreateSecurityDescriptor(new EditRangePermission[] { permission });
protectedRange.SetPassword("123");
// Protect the worksheet with a password.
if (!worksheet.IsProtected)
worksheet.Protect("password", WorksheetProtectionPermissions.Default);
// Add a note.
worksheet["B2"].Value = "This cell range is protected with a password. \n You cannot edit or format it until protection is removed." +
"\nTo remove protection, double-click the range and enter \"123\".";
worksheet.Visible = true;
#endregion #ProtectRange
}
}
}
C#using DevExpress.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace SpreadsheetDocServerAPIPart2
{
public static class SearchActions
{
public static Action<Workbook> SimpleSearchValueAction = SimpleSearchValue;
public static Action<Workbook> AdvancedSearchValueAction = AdvancedSearchValue;
static void SimpleSearchValue(Workbook workbook)
{
#region #SimpleSearch
workbook.Calculate();
Worksheet worksheet = workbook.Worksheets["ExpenseReport"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Find and highlight cells that contain the word "holiday".
IEnumerable<Cell> searchResult = worksheet.Search("holiday");
foreach (Cell cell in searchResult)
cell.Fill.BackgroundColor = Color.LightGreen;
#endregion #SimpleSearch
}
static void AdvancedSearchValue(Workbook workbook)
{
#region #AdvancedSearch
workbook.Calculate();
Worksheet worksheet = workbook.Worksheets["ExpenseReport"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Specify the search term.
string searchString = DateTime.Today.ToString("d");
// Specify search options.
SearchOptions options = new SearchOptions();
options.SearchBy = SearchBy.Columns;
options.SearchIn = SearchIn.Values;
options.MatchEntireCellContents = true;
// Find and highlight all cells that contain today's date.
IEnumerable<Cell> searchResult = worksheet.Search(searchString, options);
foreach (Cell cell in searchResult)
cell.Fill.BackgroundColor = Color.LightGreen;
#endregion #AdvancedSearch
}
}
}
C#using DevExpress.Spreadsheet;
using System;
using System.Collections.Generic;
namespace SpreadsheetDocServerAPIPart2
{
public static class SortActions
{
public static Action<Workbook> SimpleSortAction = SimpleSort;
public static Action<Workbook> DescendingOrderAction = DescendingOrder;
public static Action<Workbook> SortBySpecifiedColumnAction = SortBySpecifiedColumn;
public static Action<Workbook> SortByMultipleColumnsAction = SortByMultipleColumns;
public static Action<Workbook> SortByFillColorAction = SortByFillColor;
public static Action<Workbook> SortByFontColorAction = SortByFontColor;
static void SimpleSort(Workbook workbook)
{
#region #SimpleSort
Worksheet worksheet = workbook.Worksheets[0];
// Fill in the range.
worksheet.Cells["A2"].Value = "Donald Dozier Bradley";
worksheet.Cells["A3"].Value = "Tony Charles Mccallum-Geteer";
worksheet.Cells["A4"].Value = "Calvin Liu";
worksheet.Cells["A5"].Value = "Anita A Boyd";
worksheet.Cells["A6"].Value = "Angela R. Scott";
worksheet.Cells["A7"].Value = "D Fox";
// Sort the "A2:A7" range in ascending order.
CellRange range = worksheet.Range["A2:A7"];
worksheet.Sort(range);
// Create a heading.
CellRange header = worksheet.Range["A1"];
header[0].Value = "Ascending order";
header.ColumnWidthInCharacters = 30;
header.Style = workbook.Styles["Heading 1"];
#endregion #SimpleSort
}
static void DescendingOrder(Workbook workbook)
{
#region #DescendingOrder
Worksheet worksheet = workbook.Worksheets[0];
// Fill in the range.
worksheet.Cells["A2"].Value = "Donald Dozier Bradley";
worksheet.Cells["A3"].Value = "Tony Charles Mccallum-Geteer";
worksheet.Cells["A4"].Value = "Calvin Liu";
worksheet.Cells["A5"].Value = "Anita A Boyd";
worksheet.Cells["A6"].Value = "Angela R. Scott";
worksheet.Cells["A7"].Value = "D Fox";
// Sort the "A2:A7" range in descending order.
CellRange range = worksheet.Range["A2:A7"];
worksheet.Sort(range, false);
// Create a heading.
CellRange header = worksheet.Range["A1"];
header[0].Value = "Descending order";
header.ColumnWidthInCharacters = 30;
header.Style = workbook.Styles["Heading 1"];
#endregion #DescendingOrder
}
static void SortBySpecifiedColumn(Workbook workbook)
{
#region #SortBySpecifiedColumn
Worksheet worksheet = workbook.Worksheets["SortSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Sort the "A3:F22" range by column "D" in ascending order.
CellRange range = worksheet.Range["A3:F22"];
worksheet.Sort(range, 3, true);
#endregion #SortBySpecifiedColumn
}
static void SortByMultipleColumns(Workbook workbook)
{
#region #SortByMultipleColumns
Worksheet worksheet = workbook.Worksheets["SortSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Create sorting fields.
List<SortFieldBase> fields = new List<SortFieldBase>();
// Create the first sorting field.
SortField sortField1 = new SortField();
// Sort a cell range by column "A" in ascending order.
sortField1.ColumnOffset = 0;
sortField1.Comparer = worksheet.Comparers.Ascending;
fields.Add(sortField1);
// Create the second sorting field.
SortField sortField2 = new SortField();
// Sort a cell range by column "B" in ascending order.
sortField2.ColumnOffset = 1;
sortField2.Comparer = worksheet.Comparers.Ascending;
fields.Add(sortField2);
// Sort the "A3:F22" cell range by sorting fields.
CellRange range = worksheet.Range["A3:F22"];
worksheet.Sort(range, fields);
#endregion #SortByMultipleColumns
}
static void SortByFillColor(Workbook workbook)
{
#region #SortByFillColor
Worksheet worksheet = workbook.Worksheets["SortSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Sort the "A3:F22" range by column "A" in ascending order.
CellRange range = worksheet.Range["A3:F22"];
worksheet.Sort(range, 0, worksheet["A3"].Fill);
#endregion #SortByFillColor
}
static void SortByFontColor(Workbook workbook)
{
#region #SortByFontColor
Worksheet worksheet = workbook.Worksheets["SortSample"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Sort the "A3:F22" range by column "F" in ascending order.
CellRange range = worksheet.Range["A3:F22"];
worksheet.Sort(range,5, worksheet["F12"].Font.Color);
#endregion #SortByFontColor
}
}
}
C#using DevExpress.Spreadsheet;
using System;
using System.Drawing;
namespace SpreadsheetDocServerAPIPart2
{
public static class TableActions
{
public static Action<Workbook> CreateTableAction = CreateTable;
public static Action<Workbook> TableRangesAction = TableRanges;
public static Action<Workbook> FormatTableAction = FormatTable;
public static Action<Workbook> CustomTableStyleAction = CustomTableStyle;
public static Action<Workbook> DuplicateTableStyleAction = DuplicateTableStyle;
static void CreateTable(Workbook workbook)
{
#region #CreateTable
Worksheet worksheet = workbook.Worksheets[0];
// Insert a table in a worksheet.
Table table = worksheet.Tables.Add(worksheet["A1:F12"], false);
// Apply a built-in table style to the table.
table.Style = workbook.TableStyles[BuiltInTableStyleId.TableStyleMedium20];
#endregion #CreateTable
}
static void TableRanges(Workbook workbook)
{
#region #TableRanges
Worksheet worksheet = workbook.Worksheets["TableRanges"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Access a table.
Table table = worksheet.Tables[0];
// Obtain table columns.
TableColumn productColumn = table.Columns[0];
TableColumn priceColumn = table.Columns[1];
TableColumn quantityColumn = table.Columns[2];
TableColumn discountColumn = table.Columns[3];
// Add a new column to the end of the table .
TableColumn amountColumn = table.Columns.Add();
// Specify the column name.
amountColumn.Name = "Amount";
// Specify the formula to calculate the amount for each product
// and display the result in the "Amount" column.
amountColumn.Formula = "=[Price]*[Quantity]*(1-[Discount])";
// Display the total row for the table.
table.ShowTotals = true;
// Use the SUM function to calculate the total value for the "Amount" column.
discountColumn.TotalRowLabel = "Total:";
amountColumn.TotalRowFunction = TotalRowFunction.Sum;
// Specify the number format for each column.
priceColumn.DataRange.NumberFormat = "$#,##0.00";
discountColumn.DataRange.NumberFormat = "0.0%";
amountColumn.Range.NumberFormat = "$#,##0.00;$#,##0.00;\"\";@";
// Specify horizontal alignment for the header and total rows.
table.HeaderRowRange.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
table.TotalRowRange.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
// Specify horizontal alignment
// for all columns except the first column.
for (int i = 1; i < table.Columns.Count; i++)
{
table.Columns[i].DataRange.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
}
// Set the width of table columns.
table.Range.ColumnWidthInCharacters = 10;
worksheet.Visible = true;
#endregion #TableRanges
}
static void FormatTable(Workbook workbook)
{
#region #FormatTable
Worksheet worksheet = workbook.Worksheets["FormatTable"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Access a table.
Table table = worksheet.Tables[0];
// Access the workbook's collection of table styles.
TableStyleCollection tableStyles = workbook.TableStyles;
// Access the built-in table style by its name.
TableStyle tableStyle = tableStyles[BuiltInTableStyleId.TableStyleMedium16];
// Apply the style to the table.
table.Style = tableStyle;
// Show header and total rows.
table.ShowHeaders = true;
table.ShowTotals = true;
// Enable banded column formatting for the table.
table.ShowTableStyleRowStripes = false;
table.ShowTableStyleColumnStripes = true;
// Format the first column in the table.
table.ShowTableStyleFirstColumn = true;
worksheet.Visible = true;
#endregion #FormatTable
}
static void CustomTableStyle(Workbook workbook)
{
#region #CustomTableStyle
Worksheet worksheet = workbook.Worksheets["Custom Table Style"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Access a table.
Table table = worksheet.Tables[0];
String styleName = "testTableStyle";
// If a style with the specified name exists in the collection,
// apply this style to the table.
if (workbook.TableStyles.Contains(styleName))
{
table.Style = workbook.TableStyles[styleName];
}
else
{
// Add a new table style under the "testTableStyle" name
// to the table style collection.
TableStyle customTableStyle = workbook.TableStyles.Add("testTableStyle");
// Modify table style formatting.
// Specify format characteristics for different table elements.
customTableStyle.BeginUpdate();
try
{
customTableStyle.TableStyleElements[TableStyleElementType.WholeTable].Font.Color = Color.FromArgb(107, 107, 107);
// Format the header row.
TableStyleElement headerRowStyle = customTableStyle.TableStyleElements[TableStyleElementType.HeaderRow];
headerRowStyle.Fill.BackgroundColor = Color.FromArgb(64, 66, 166);
headerRowStyle.Font.Color = Color.White;
headerRowStyle.Font.Bold = true;
// Format the total row.
TableStyleElement totalRowStyle = customTableStyle.TableStyleElements[TableStyleElementType.TotalRow];
totalRowStyle.Fill.BackgroundColor = Color.FromArgb(115, 193, 211);
totalRowStyle.Font.Color = Color.White;
totalRowStyle.Font.Bold = true;
// Specify banded row formatting for the table.
TableStyleElement secondRowStripeStyle = customTableStyle.TableStyleElements[TableStyleElementType.SecondRowStripe];
secondRowStripeStyle.Fill.BackgroundColor = Color.FromArgb(234, 234, 234);
secondRowStripeStyle.StripeSize = 1;
}
finally
{
customTableStyle.EndUpdate();
}
// Apply the custom style to the table.
table.Style = customTableStyle;
}
worksheet.Visible = true;
#endregion #CustomTableStyle
}
static void DuplicateTableStyle(Workbook workbook)
{
#region #DuplicateTableStyle
Worksheet worksheet = workbook.Worksheets["Duplicate Table Style"];
workbook.Worksheets.ActiveWorksheet = worksheet;
// Access table.
Table table1 = worksheet.Tables[0];
Table table2 = worksheet.Tables[1];
// Obtain the built-in table style.
TableStyle sourceTableStyle = workbook.TableStyles[BuiltInTableStyleId.TableStyleMedium17];
// Duplicate the table style.
TableStyle newTableStyle = sourceTableStyle.Duplicate();
// Modify the duplicated table style's formatting.
newTableStyle.TableStyleElements[TableStyleElementType.HeaderRow].Fill.BackgroundColor = Color.FromArgb(0xA7, 0xEA, 0x52);
// Apply styles to tables.
table1.Style = sourceTableStyle;
table2.Style = newTableStyle;
worksheet.Visible = true;
#endregion #DuplicateTableStyle
}
}
}