Configuración de números
Configuración de formatos de visualización de Numbers y fechas
Una característica muy fuerte de Microsoft Excel es que permite a los usuarios configurar los formatos de visualización de valores numéricos y fechas. Sabemos que los datos numéricos se pueden utilizar para representar diferentes valores, incluidos valores decimales, monetarios, porcentuales, fraccionarios o contables, etc. Todos estos valores numéricos se muestran en diferentes formatos según el tipo de información que representan. Del mismo modo, existen muchos formatos en los que se puede mostrar una fecha o una hora. Aspose.Cells admite esta funcionalidad y permite a los desarrolladores configurar cualquier formato de visualización para un número o una fecha.
Configuración de formatos de visualización en Microsoft Excel
Para establecer formatos de visualización en Microsoft Excel:
- Haga clic derecho en cualquier celda.
- SeleccioneFormato Cells. Aparecerá un cuadro de diálogo que se utiliza para configurar los formatos de visualización de cualquier tipo de valor.
En el lado izquierdo del cuadro de diálogo, hay muchas categorías de valores comoGeneral, Número, Divisa, Contabilidad, Fecha, Hora, **Porcentaje,**etc. Aspose.Cells admite todos estos formatos de visualización.
Aspose.Cells proporciona una clase,Libro de trabajo que representa un archivo de Excel Microsoft. ÉlLibro de trabajo la clase contiene unHojas de trabajo colección que permite el acceso a cada hoja de trabajo en el archivo de Excel. Una hoja de trabajo está representada por elHoja de cálculo clase. ÉlHoja de cálculo la clase proporciona unCells recopilación. Cada artículo en elCells colección representa un objeto de laCellclase.
Aspose.Cells proporcionaObtenerEstilo yEstablecerEstilo métodos para elCell clase. Estos métodos se utilizan para obtener y establecer el formato de una celda. ÉlEstiloLa clase proporciona algunas propiedades útiles para manejar los formatos de visualización de números y fechas.
Uso de formatos numéricos integrados
Aspose.Cells ofrece algunos formatos de números incorporados para configurar los formatos de visualización de los números y las fechas. Estos formatos numéricos integrados se pueden aplicar utilizando elNúmero propiedad de laEstilo objeto. Todos los formatos de números incorporados reciben valores numéricos únicos. Los desarrolladores pueden asignar cualquier valor numérico deseado alNúmero propiedad de laEstiloobjeto para aplicar el formato de visualización. Este enfoque es rápido. Los formatos de números incorporados admitidos por Aspose.Cells se enumeran a continuación.
Valor | Escribe | cadena de formato |
---|---|---|
0 | General | General |
1 | Decimal | 0 |
2 | Decimal | 0.00 |
3 | Decimal | # ,##0 |
4 | Decimal | # ,##0.00 |
5 | Divisa | $#,##0;$-#,##0 |
6 | Divisa | $#,##0;[Rojo]$-#,##0 |
7 | Divisa | $#,##0.00;$-#,##0.00 |
8 | Divisa | $#,##0.00;[Rojo]$-#,##0.00 |
9 | Porcentaje | 0% |
10 | Porcentaje | 0.00% |
11 | Científico | 0.00E+00 |
12 | Fracción | # ?/? |
13 | Fracción | # / |
14 | Fecha | m/d/aa |
15 | Fecha | d-mmm-aaa |
16 | Fecha | d-mmm |
17 | Fecha | mmm-aaa |
18 | Hora | h:mm AM/PM |
19 | Hora | h:mm:ss AM/PM |
20 | Hora | mmm |
21 | Hora | h: mm: ss |
22 | Hora | m/d/aa h:mm |
37 | Divisa | # ,##0;-#,##0 |
38 | Divisa | # ,##0;[Rojo]-#,##0 |
39 | Divisa | # ,##0.00;-#,##0.00 |
40 | Divisa | # ,##0.00;[Rojo]-#,##0.00 |
41 | Contabilidad | _ * #,##0_ ;_ * “_ ;_ @_ |
42 | Contabilidad | _ $* #,##0_ ;_ $* “_ ;_ @_ |
43 | Contabilidad | _ * #,##0.00_ ;_ * “??_ ;_ @_ |
44 | Contabilidad | _ $* #,##0.00_ ;_ $* “??_ ;_ @_ |
45 | Hora | mm: ss |
46 | Hora | h :mm:ss |
47 | Hora | mm:ss.0 |
48 | Científico | ## 0.0E+00 |
49 | Texto | @ |
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Obtaining the reference of first worksheet | |
Worksheet worksheet = workbook.Worksheets[0]; | |
// Adding the current system date to "A1" cell | |
worksheet.Cells["A1"].PutValue(DateTime.Now); | |
// Getting the Style of the A1 Cell | |
Style style = worksheet.Cells["A1"].GetStyle(); | |
// Setting the display format to number 15 to show date as "d-mmm-yy" | |
style.Number = 15; | |
// Applying the style to the A1 cell | |
worksheet.Cells["A1"].SetStyle(style); | |
// Adding a numeric value to "A2" cell | |
worksheet.Cells["A2"].PutValue(20); | |
// Getting the Style of the A2 Cell | |
style = worksheet.Cells["A2"].GetStyle(); | |
// Setting the display format to number 9 to show value as percentage | |
style.Number = 9; | |
// Applying the style to the A2 cell | |
worksheet.Cells["A2"].SetStyle(style); | |
// Adding a numeric value to "A3" cell | |
worksheet.Cells["A3"].PutValue(2546); | |
// Getting the Style of the A3 Cell | |
style = worksheet.Cells["A3"].GetStyle(); | |
// Setting the display format to number 6 to show value as currency | |
style.Number = 6; | |
// Applying the style to the A3 cell | |
worksheet.Cells["A3"].SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Uso de formatos de números personalizados
Para definir su propia cadena de formato personalizado para configurar el formato de visualización, utilice elEstilo objetosDisfrazpropiedad. Este enfoque no es tan rápido como el uso de formatos preestablecidos, pero es más flexible.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// The path to the documents directory. | |
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); | |
// Create directory if it is not already present. | |
bool IsExists = System.IO.Directory.Exists(dataDir); | |
if (!IsExists) | |
System.IO.Directory.CreateDirectory(dataDir); | |
// Instantiating a Workbook object | |
Workbook workbook = new Workbook(); | |
// Adding a new worksheet to the Excel object | |
int i = workbook.Worksheets.Add(); | |
// Obtaining the reference of the newly added worksheet by passing its sheet index | |
Worksheet worksheet = workbook.Worksheets[i]; | |
// Adding the current system date to "A1" cell | |
worksheet.Cells["A1"].PutValue(DateTime.Now); | |
// Getting the style of A1 cell | |
Style style = worksheet.Cells["A1"].GetStyle(); | |
// Setting the custom display format to show date as "d-mmm-yy" | |
style.Custom = "d-mmm-yy"; | |
// Applying the style to A1 cell | |
worksheet.Cells["A1"].SetStyle(style); | |
// Adding a numeric value to "A2" cell | |
worksheet.Cells["A2"].PutValue(20); | |
// Getting the style of A2 cell | |
style = worksheet.Cells["A2"].GetStyle(); | |
// Setting the custom display format to show value as percentage | |
style.Custom = "0.0%"; | |
// Applying the style to A2 cell | |
worksheet.Cells["A2"].SetStyle(style); | |
// Adding a numeric value to "A3" cell | |
worksheet.Cells["A3"].PutValue(2546); | |
// Getting the style of A3 cell | |
style = worksheet.Cells["A3"].GetStyle(); | |
// Setting the custom display format to show value as currency | |
style.Custom = "£#,##0;[Red]$-#,##0"; | |
// Applying the style to A3 cell | |
worksheet.Cells["A3"].SetStyle(style); | |
// Saving the Excel file | |
workbook.Save(dataDir + "book1.out.xls", SaveFormat.Excel97To2003); |
Temas avanzados
- Compruebe el formato de número personalizado al configurar el estilo. Propiedad personalizada
- Lista de formatos de números admitidos
- Render Formato de fecha personalizado Patrón g y ge mm dd
- Especificar separadores de grupos y decimales de números personalizados para el libro de trabajo
- Especificación del formato de patrón personalizado de DBNum