Cómo establecer formatos de datos de celda en Excel

How to Set Cell Data Formats

This article was translated from English: Does it need improvement?
Translated
View the article in English

Data formatting and number formatting in Excel allow you to control how numbers, dates, times, and other data are displayed in cells, enhancing readability and ensuring data accuracy. With data formats, you can present information in specific formats like percentages or currencies. Similarly, number formats let you customize decimal places and display options.

Quickstart: Apply Built-In Format to a Single Cell in One Line

This sample shows how easy it is to create a new Excel workbook and apply a built-in format to a specific cell using IronXL’s API. You’ll be up and running in seconds, with no Interop dependencies—just set “FormatString” and save.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    IronXL.WorkBook book = IronXL.WorkBook.Create(); book.DefaultWorkSheet["B2"].FormatString = IronXL.Formatting.BuiltinFormats.Currency2;
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    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;
using System.Linq;

// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Set the data format to 12300.00%
workSheet["A1"].Value = 123;
workSheet["A1"].FormatString = BuiltinFormats.Percent2;

// Set the data format to 123.0000
workSheet["A2"].Value = 123;
workSheet["A2"].FormatString = "0.0000";

// Set data display format to range
DateTime dateValue = new DateTime(2020, 1, 1, 12, 12, 12);
workSheet["A3"].Value = dateValue;
workSheet["A4"].Value = new DateTime(2022, 3, 3, 10, 10, 10);
workSheet["A5"].Value = new DateTime(2021, 2, 2, 11, 11, 11);

IronXL.Range range = workSheet["A3:A5"];

// Set the data format to 1/1/2020 12:12:12
range.FormatString = "MM/dd/yy h:mm:ss";

workBook.SaveAs("dataFormats.xlsx");
Imports IronXL
Imports IronXL.Formatting
Imports System
Imports System.Linq

' Create a new workbook
Private workBook As WorkBook = WorkBook.Create()
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Set the data format to 12300.00%
Private workSheet("A1").Value = 123
Private workSheet("A1").FormatString = BuiltinFormats.Percent2

' Set the data format to 123.0000
Private workSheet("A2").Value = 123
Private workSheet("A2").FormatString = "0.0000"

' Set data display format to range
Private dateValue As New DateTime(2020, 1, 1, 12, 12, 12)
Private workSheet("A3").Value = dateValue
Private workSheet("A4").Value = New DateTime(2022, 3, 3, 10, 10, 10)
Private workSheet("A5").Value = New DateTime(2021, 2, 2, 11, 11, 11)

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

' Set the data format to 1/1/2020 12:12:12
range.FormatString = "MM/dd/yy h:mm:ss"

workBook.SaveAs("dataFormats.xlsx")
$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
// Assign value as string
workSheet["A1"].StringValue = "4402-12";
' Assign value as string
workSheet("A1").StringValue = "4402-12"
$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;
using IronXL.Formatting;

// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Use builtin formats
workSheet["A1"].Value = 123;
workSheet["A1"].FormatString = BuiltinFormats.Accounting0;

workBook.SaveAs("builtinDataFormats.xlsx");
Imports IronXL
Imports IronXL.Formatting

' Create a new workbook
Private workBook As WorkBook = WorkBook.Create()
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Use builtin formats
Private workSheet("A1").Value = 123
Private workSheet("A1").FormatString = BuiltinFormats.Accounting0

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).

Preguntas Frecuentes

¿Cómo puedo establecer formatos de datos de celdas en Excel utilizando C#?

Puede establecer formatos de datos de celdas en Excel usando IronXL accediendo a una hoja de trabajo y configurando la propiedad FormatString de una celda. Esto permite la personalización de cómo se muestran los datos, como números, fechas y horas, sin usar Interop.

¿Cuáles son los beneficios de usar una biblioteca C# para formateo de datos de Excel?

Usar una biblioteca C# como IronXL para formateo de datos de Excel le permite controlar programáticamente la apariencia de los datos, mejorar la legibilidad, asegurar la precisión de los datos y evitar las complejidades de usar Interop. Simplifica tareas como establecer formatos numéricos, fechas y formatos personalizados.

¿Cómo aplico un formato numérico personalizado a una celda en Excel con C#?

Para aplicar un formato numérico personalizado a una celda usando IronXL, cargue su libro de Excel, acceda a la hoja de trabajo y configure la propiedad FormatString de la celda al formato personalizado deseado. Por ejemplo, para mostrar un número como porcentaje, use sheet['A1'].FormatString = '0.00%'.

¿Puedo preservar ceros a la izquierda en celdas de Excel usando una biblioteca C#?

Sí, con IronXL, puede preservar ceros a la izquierda usando la propiedad StringValue al configurar el valor de una celda. Este enfoque evita la conversión automática y retiene los ceros a la izquierda en la celda.

¿Cómo formateo celdas de Excel con estilos contables usando C#?

Para formatear celdas de Excel con estilos contables usando IronXL, utilice la clase BuiltinFormats. Por ejemplo, puede aplicar un formato contable con dos decimales con sheet['C3'].FormatString = IronXL.Formatting.BuiltinFormats.Accounting2.

¿Cuáles son algunos formatos de datos predefinidos disponibles en una biblioteca C# para Excel?

IronXL proporciona formatos de datos predefinidos como contabilidad, duración, tiempo, fecha, fracción, científico, porcentaje, moneda y número. Estos formatos integrados simplifican la personalización de la presentación de datos en hojas de cálculo de Excel.

¿Cómo puedo mostrar valores monetarios negativos en rojo en Excel usando C#?

Para mostrar valores monetarios negativos en rojo usando IronXL, configure la propiedad FormatString a un formato monetario que incluya rojo para negativos, como Currency0Red o Currency2Red. Por ejemplo: sheet['B4'].FormatString = IronXL.Formatting.BuiltinFormats.Currency2Red.

¿Cuál es la diferencia entre los formatos Number0 y Number2 en IronXL?

En IronXL, el formato Number0 muestra números sin dígitos decimales, mientras que el formato Number2 muestra números con dos dígitos decimales. Estos formatos ayudan a personalizar la precisión de los datos numéricos en hojas de Excel.

¿Cómo guardo los cambios en un libro de Excel después de formatearlo usando C#?

Para guardar cambios en un libro de Excel después de formatearlo con IronXL, use el método SaveAs en el objeto WorkBook. Especifique el nombre de archivo y formato deseado para guardar el libro actualizado.

¿Cuáles son algunos consejos de solución de problemas para establecer formatos de datos en Excel usando una biblioteca C#?

Al establecer formatos de datos en Excel usando IronXL, asegúrese de que la biblioteca esté correctamente integrada, verifique que las cadenas de formato utilizadas sean precisas y revise por cualquier excepción durante el proceso de guardado del libro. También considere usar la propiedad StringValue para una entrada de datos precisa.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 1,686,155 | Versión: 2025.11 recién lanzado