Get started with IronXL

Start using IronXL in your project today with a free trial.

First Step:
green arrow pointer


Set Cell Data Formats Example

The FormatString property can be accessed through both cells and ranges. Therefore, it is possible to set data formats for individual cells, columns, rows, and any selected range.

:path=/static-assets/excel/content-code-examples/how-to/set-cell-data-format.cs
using IronXL;
using IronXL.Formatting;
using System;

// Create a new workbook and obtain the default worksheet
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set and format a percentage value
// The value 123 is set in cell A1 and formatted as "12300.00%"
workSheet["A1"].Value = 123;
// Format the value as a percentage with two decimal places
workSheet["A1"].FormatString = BuiltinFormats.Percent2;

// Set and format a numeric value with four decimal places
// The value 123 is set in cell A2 and formatted as "123.0000"
workSheet["A2"].Value = 123;
// Using a custom format string to display four decimal places
workSheet["A2"].FormatString = "0.0000";

// Set and format a range of date-time values
// Assign date-time values to multiple cells
DateTime dateValue = new DateTime(2020, 1, 1, 12, 12, 12);
workSheet["A3"].Value = dateValue; // Set date-time value at cell A3
workSheet["A4"].Value = new DateTime(2022, 3, 3, 10, 10, 10); // Set date-time value at cell A4
workSheet["A5"].Value = new DateTime(2021, 2, 2, 11, 11, 11); // Set date-time value at cell A5

// Define a range of cells containing date-time values
IronXL.Range range = workSheet["A3:A5"];

// Format the entire range to display date-time in "MM/dd/yyyy h:mm:ss" format
range.FormatString = "MM/dd/yyyy h:mm:ss";

// Save the workbook as an Excel file
workBook.SaveAs("dataFormats.xlsx");

// Note: Ensure that you have the IronXL library referenced in your project.
Imports IronXL

Imports IronXL.Formatting

Imports System



' Create a new workbook and obtain the default worksheet

Private workBook As WorkBook = WorkBook.Create()

Private workSheet As WorkSheet = workBook.DefaultWorkSheet



' Set and format a percentage value

' The value 123 is set in cell A1 and formatted as "12300.00%"

Private workSheet("A1").Value = 123

' Format the value as a percentage with two decimal places

Private workSheet("A1").FormatString = BuiltinFormats.Percent2



' Set and format a numeric value with four decimal places

' The value 123 is set in cell A2 and formatted as "123.0000"

Private workSheet("A2").Value = 123

' Using a custom format string to display four decimal places

Private workSheet("A2").FormatString = "0.0000"



' Set and format a range of date-time values

' Assign date-time values to multiple cells

Private dateValue As New DateTime(2020, 1, 1, 12, 12, 12)

Private workSheet("A3").Value = dateValue ' Set date-time value at cell A3

Private workSheet("A4").Value = New DateTime(2022, 3, 3, 10, 10, 10) ' Set date-time value at cell A4

Private workSheet("A5").Value = New DateTime(2021, 2, 2, 11, 11, 11) ' Set date-time value at cell A5



' Define a range of cells containing date-time values

Private range As IronXL.Range = workSheet("A3:A5")



' Format the entire range to display date-time in "MM/dd/yyyy h:mm:ss" format

range.FormatString = "MM/dd/yyyy h:mm:ss"



' Save the workbook as an Excel file

workBook.SaveAs("dataFormats.xlsx")



' Note: Ensure that you have the IronXL library referenced in your project.
$vbLabelText   $csharpLabel
Data Format

Set Cell Value as String

When setting the value in IronXL, use StringValue instead of Value to directly assign the exact value to the cell without automatic conversion. This usage is like placing an apostrophe before the cell value in Excel.

:path=/static-assets/excel/content-code-examples/how-to/write-excel-net-assign-stringvalue.cs
// The code assigns a string value to a cell in a worksheet.
// Assuming workSheet is an object of a type that supports cell operations
// with StringValue, such as a library class for handling spreadsheet files.
// This may typically be part of a library like EPPlus, ClosedXML, or similar.

try
{
    // Assign the value "4402-12" as a string to cell A1 in the worksheet.
    workSheet["A1"].Value = "4402-12"; // Assuming 'Value' is the correct property to set in the library being used.
}
catch (Exception e)
{
    // Log or handle exception if the operation fails
    Console.WriteLine($"An error occurred while assigning the cell value: {e.Message}");
}

// Note: We assumed the presence of a try-catch block for error handling. 
// The specific method/property to set a cell's value may vary depending on 
// the library in use. Please refer to the library documentation for specifics.
' The code assigns a string value to a cell in a worksheet.

' Assuming workSheet is an object of a type that supports cell operations

' with StringValue, such as a library class for handling spreadsheet files.

' This may typically be part of a library like EPPlus, ClosedXML, or similar.



Try

	' Assign the value "4402-12" as a string to cell A1 in the worksheet.

	workSheet("A1").Value = "4402-12" ' Assuming 'Value' is the correct property to set in the library being used.

Catch e As Exception

	' Log or handle exception if the operation fails

	Console.WriteLine($"An error occurred while assigning the cell value: {e.Message}")

End Try



' Note: We assumed the presence of a try-catch block for error handling. 

' The specific method/property to set a cell's value may vary depending on 

' the library in use. Please refer to the library documentation for specifics.
$vbLabelText   $csharpLabel

Use Builtin Formats Example

The IronXL library offers a variety of predefined format strings that can be accessed through the IronXL.Formatting.BuiltinFormats class for formatting Excel cells. This allows you to customize how data is displayed in your Excel spreadsheets.

:path=/static-assets/excel/content-code-examples/how-to/set-cell-data-format-builtin-formats.cs
using IronXL; // Library for handling Excel files
using IronXL.Formatting; // Library for formatting Excel files

// Create a new workbook
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Access the default worksheet of the workbook
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the value of cell A1 to 123
workSheet["A1"].Value = 123;

// Apply the built-in Accounting format with zero decimal places to cell A1
workSheet["A1"].Style.NumberFormat = BuiltinFormats.Accounting0;

// Save the workbook to a file named "builtinDataFormats.xlsx"
workBook.SaveAs("builtinDataFormats.xlsx");
Imports IronXL ' Library for handling Excel files

Imports IronXL.Formatting ' Library for formatting Excel files



' Create a new workbook

Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)



' Access the default worksheet of the workbook

Private workSheet As WorkSheet = workBook.DefaultWorkSheet



' Set the value of cell A1 to 123

Private workSheet("A1").Value = 123



' Apply the built-in Accounting format with zero decimal places to cell A1

Private workSheet("A1").Style.NumberFormat = BuiltinFormats.Accounting0



' Save the workbook to a file named "builtinDataFormats.xlsx"

workBook.SaveAs("builtinDataFormats.xlsx")
$vbLabelText   $csharpLabel

Available Builtin Data Formats

For the Duration type, input values are represented in days. For example, 1 day is equal to 24 hours, and 1.05 days is equivalent to 25 hours and 12 minutes. Here are the available format types:

All Available Data Formats

Description

  • General: The default format that displays numbers as they are without any specific formatting.
  • Duration1: Displays duration values in minutes and seconds, like "mm:ss." Number input into the Value property will be considered as days.
  • Duration2: Displays duration values in hours, minutes, and seconds, like "[h]:mm:ss."
  • Duration3: Displays duration values in minutes, seconds, and milliseconds, like "mm:ss.0."
  • Accounting0: Formats accounting values without decimal digits, using parentheses for negative values, like "#,##0_);(#,##0)."
  • Accounting0Red: Formats accounting values without decimal digits, using red color for negative values, like "#,##0_);Red."
  • Accounting2: Formats accounting values with two decimal digits, using parentheses for negative values, like "#,##0.00;(#,##0.00)."
  • Accounting2Red: Formats accounting values with two decimal digits, using red color for negative values, like "#,##0.00_);Red."
  • Time1: Formats time values in 12-hour clock format with AM/PM, like "h:mm AM/PM."
  • Time2: Formats time values in 12-hour clock format with seconds and AM/PM, like "h:mm:ss AM/PM."
  • Time3: Formats time values in 24-hour clock format without seconds, like "h:mm."
  • Time4: Formats time values in 24-hour clock format with seconds, like "h:mm:ss."
  • ShortDate: Formats date values in a short format, like "m/d/yy."
  • ShortDateAndTime: Formats date and time values in a short format, like "m/d/yy h:mm."
  • LongDate1: Formats date values in a long format with month, day, and year, like "d-mmm-yy."
  • LongDate2: Formats date values in a long format with day and abbreviated month, like "d-mmm."
  • LongDate3: Formats date values in a long format with abbreviated month and year, like "mmm-yy."
  • Fraction1: Formats fractional values with one digit, like "# ?/?."
  • Fraction2: Formats fractional values with two digits, like "# ??/??."
  • Scientific1: Formats numbers in scientific notation with one digit after the dot, like "##0.0E+0."
  • Scientific2: Formats numbers in scientific notation with two digits after the dot, like "0.00E+00."
  • Percent: Formats percentage values without decimal digits, like "0%."
  • Percent2: Formats percentage values with two decimal digits, like "0.00%."
  • Currency0: Formats currency values without decimal digits, using parentheses for negative values, like "$#,##0_);($#,##0)."
  • Currency0Red: Formats currency values without decimal digits, using red color for negative values, like "$#,##0_);Red."
  • Currency2: Formats currency values with two decimal digits, using parentheses for negative values, like "$#,##0.00;($#,##0.00)."
  • Currency2Red: Formats currency values with two decimal digits, using red color for negative values, like "$#,##0.00_);Red."
  • Thousands0: Formats numbers with thousands separator and no decimal digits, like "#,##0."
  • Thousands2: Formats numbers with thousands separator and two decimal digits, like "#,##0.00."
  • Number0: Formats numbers without decimal digits, like "0."
  • Number2: Formats numbers with two decimal digits, like "0.00."
  • Text: Formats text values as plain text, like "@" (no specific formatting applied).

Frequently Asked Questions

What is the purpose of setting cell data formats in Excel?

Setting cell data formats in Excel allows you to control how numbers, dates, times, and other data are displayed, enhancing readability and ensuring data accuracy. It enables presenting information in specific formats like percentages or currencies and customizing decimal places and display options.

How can IronXL help in setting cell data formats without using Interop?

IronXL simplifies the process of creating, formatting, and manipulating Excel files programmatically in C#. It allows setting data formats or number formats without using Interop, making it a valuable tool for data handling and presentation tasks in C# applications.

How do you set a custom data format for a cell using IronXL?

To set a custom data format for a cell using IronXL, load an Excel workbook, access the desired worksheet, and set the FormatString property of the cell to the desired format. For example, to format a number as a percentage with two decimal places: sheet["A1"].FormatString = "0.00%".

What are BuiltinFormats in IronXL?

BuiltinFormats in IronXL are predefined format strings that can be used to format Excel cells. They offer a variety of formats such as accounting, time, date, scientific, and percentage formats, which simplify the customization of data display in Excel spreadsheets.

How do you preserve leading zeros in a cell using IronXL?

To preserve leading zeros in a cell using IronXL, use the StringValue property instead of Value when setting the cell's value. This approach prevents automatic conversion, allowing the leading zeros to be retained, similar to placing an apostrophe before the cell value in Excel.

Can you use IronXL to format cells with accounting styles?

Yes, IronXL can format cells with accounting styles using the BuiltinFormats class. For instance, you can set a cell to an accounting format with two decimal places using: sheet["C3"].FormatString = IronXL.Formatting.BuiltinFormats.Accounting2.

What are some examples of duration formats available in IronXL?

IronXL offers several duration formats, such as Duration1 for minutes and seconds ("mm:ss"), Duration2 for hours, minutes, and seconds ("[h]:mm:ss"), and Duration3 for minutes, seconds, and milliseconds ("mm:ss.0").

How can you set a cell to display currency values with red color for negatives using IronXL?

To display currency values with red color for negatives, use the BuiltinFormats class and set the FormatString property to a currency format like Currency0Red or Currency2Red. For example: sheet["B4"].FormatString = IronXL.Formatting.BuiltinFormats.Currency2Red.

What is the difference between Number0 and Number2 formats in IronXL?

The Number0 format displays numbers without decimal digits ("0"), while the Number2 format displays numbers with two decimal digits ("0.00"). These formats help in customizing the precision of numerical data in Excel sheets.

How do you save changes in an Excel workbook after formatting cells using IronXL?

After formatting cells in an Excel workbook using IronXL, save the changes by calling the SaveAs method on the WorkBook object, specifying the file name and format to save the updated workbook.

Chaknith related to Description
Software Engineer
Chaknith is the Sherlock Holmes of developers. It first occurred to him he might have a future in software engineering, when he was doing code challenges for fun. His focus is on IronXL and IronBarcode, but he takes pride in helping customers with every product. Chaknith leverages his knowledge from talking directly with customers, to help further improve the products themselves. His anecdotal feedback goes beyond Jira tickets and supports product development, documentation and marketing, to improve customer’s overall experience.When he isn’t in the office, he can be found learning about machine learning, coding and hiking.