Cambiar la Alineación de las Celdas y Mantener el Formato Existente
Escenarios de uso posibles
A veces, quieres cambiar la alineación de varias celdas pero también mantener el formato existente. Aspose.Cells para Python via .NET te permite hacerlo usando la propiedad StyleFlag.alignments. Si la configuras en true, se realizarán cambios en la alineación; de lo contrario, no. Ten en cuenta que se pasa el objeto StyleFlag como parámetro al método Range.apply_style() que realmente 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
from aspose.cells import SaveFormat, StyleFlag, TextAlignmentType, Workbook | |
# 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. | |
wb = Workbook(sourceDir + "sampleChangeCellsAlignmentAndKeepExistingFormatting.xlsx") | |
# Access first worksheet. | |
ws = wb.worksheets[0] | |
# Create cells range. | |
rng = ws.cells.create_range("B2:D7") | |
# Create style object. | |
st = wb.create_style() | |
# Set the horizontal and vertical alignment to center. | |
st.horizontal_alignment = TextAlignmentType.CENTER | |
st.vertical_alignment = TextAlignmentType.CENTER | |
# Create style flag object. | |
flag = 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.apply_style(st, flag) | |
# Save the workbook in XLSX format. | |
wb.save(outputDir + "outputChangeCellsAlignmentAndKeepExistingFormatting.xlsx", SaveFormat.XLSX) |