Cambiar la Alineación de las Celdas y Mantener el Formato Existente
Escenarios de uso posibles
A veces, desea cambiar la alineación de múltiples celdas pero también desea conservar el formato existente. Aspose.Cells le permite hacerlo usando la propiedad StyleFlag.Alignments. Si la establece en true, los cambios en la alineación tendrán lugar, de lo contrario no. Tenga en cuenta que el objeto StyleFlag se pasa como parámetro al método Range.ApplyStyle() que en realidad aplica el formato a un rango de celdas.
Cambiar la alineación de las celdas y mantener el formato existente
El siguiente código de ejemplo carga el archivo de Excel de muestra, crea el rango y centra la alineación horizontal y verticalmente y mantiene intacto el formato existente. La siguiente captura de pantalla compara el archivo de Excel de muestra y el archivo de Excel de salida y muestra que todo el formato existente de las celdas es el mismo, excepto que las celdas ahora están centradas horizontal y verticalmente.
Código de muestra
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET | |
// Load sample Excel file containing cells with formatting. | |
Workbook wb = new Workbook(sourceDir + "sampleChangeCellsAlignmentAndKeepExistingFormatting.xlsx"); | |
// Access first worksheet. | |
Worksheet ws = wb.Worksheets[0]; | |
// Create cells range. | |
Range rng = ws.Cells.CreateRange("B2:D7"); | |
// Create style object. | |
Style st = wb.CreateStyle(); | |
// Set the horizontal and vertical alignment to center. | |
st.HorizontalAlignment = TextAlignmentType.Center; | |
st.VerticalAlignment = TextAlignmentType.Center; | |
// Create style flag object. | |
StyleFlag flag = new StyleFlag(); | |
// Set style flag alignments true. It is most crucial statement. | |
// Because if it will be false, no changes will take place. | |
flag.Alignments = true; | |
// Apply style to range of cells. | |
rng.ApplyStyle(st, flag); | |
// Save the workbook in XLSX format. | |
wb.Save(outputDir + "outputChangeCellsAlignmentAndKeepExistingFormatting.xlsx", SaveFormat.Xlsx); |