Formato del gráfico

Configurar la apariencia del gráfico

En Tipos de gráficos, dimos una breve introducción a los tipos de gráficos y objetos de gráficos ofrecidos por Aspose.Cells.

En este artículo, discutimos cómo personalizar la apariencia de los gráficos configurando una serie de propiedades diferentes:

Configurando el área del gráfico

Hay diferentes tipos de áreas en un gráfico y Aspose.Cells proporciona la flexibilidad de modificar la apariencia de cada área. Los desarrolladores pueden aplicar diferentes configuraciones de formato en un área cambiando su color de primer plano, color de fondo y formato de relleno, etc.

En el ejemplo dado a continuación, hemos aplicado diferentes configuraciones de formato en diferentes tipos de áreas de un gráfico. Estas áreas incluyen:

Después de ejecutar el código de ejemplo, se agregará un gráfico de columnas a la hoja de trabajo como se muestra a continuación:

Un gráfico de columnas con áreas rellenas

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingChartArea.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook();
WorksheetCollection worksheets = workbook.getWorksheets();
// Obtaining the reference of the newly added worksheet by passing its
// sheet index
Worksheet worksheet = worksheets.get(0);
Cells cells = worksheet.getCells();
// Adding a sample value to "A1" cell
cells.get("A1").setValue(50);
// Adding a sample value to "A2" cell
cells.get("A2").setValue(100);
// Adding a sample value to "A3" cell
cells.get("A3").setValue(150);
// Adding a sample value to "B1" cell
cells.get("B1").setValue(60);
// Adding a sample value to "B2" cell
cells.get("B2").setValue(32);
// Adding a sample value to "B3" cell
cells.get("B3").setValue(50);
// Adding a chart to the worksheet
ChartCollection charts = worksheet.getCharts();
// Accessing the instance of the newly added chart
int chartIndex = charts.add(ChartType.COLUMN, 5, 0, 15, 7);
Chart chart = charts.get(chartIndex);
// Adding NSeries (chart data source) to the chart ranging from "A1"
// cell
SeriesCollection nSeries = chart.getNSeries();
nSeries.add("A1:B3", true);
// Setting the foreground color of the plot area
ChartFrame plotArea = chart.getPlotArea();
Area area = plotArea.getArea();
area.setForegroundColor(Color.getBlue());
// Setting the foreground color of the chart area
ChartArea chartArea = chart.getChartArea();
area = chartArea.getArea();
area.setForegroundColor(Color.getYellow());
// Setting the foreground color of the 1st NSeries area
Series aSeries = nSeries.get(0);
area = aSeries.getArea();
area.setForegroundColor(Color.getRed());
// Setting the foreground color of the area of the 1st NSeries point
ChartPointCollection chartPoints = aSeries.getPoints();
ChartPoint point = chartPoints.get(0);
point.getArea().setForegroundColor(Color.getCyan());
// Save the Excel file
workbook.save(dataDir + "SettingChartArea_out.xls");
// Print message
System.out.println("ChartArea is settled successfully.");

Configurando las líneas del gráfico

Los desarrolladores también pueden aplicar diferentes tipos de estilos en las líneas o marcadores de datos del SeriesCollection como se muestra a continuación en el ejemplo. Al ejecutar el código de ejemplo, se agrega un gráfico de columnas a la hoja de trabajo como se muestra a continuación:

Gráfico de columnas después de aplicar estilos de línea

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingChartLines.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "book1.xls");
WorksheetCollection worksheets = workbook.getWorksheets();
// Obtaining the reference of the newly added worksheet by passing its
// sheet index
Worksheet worksheet = worksheets.get(0);
Cells cells = worksheet.getCells();
// Adding a chart to the worksheet
ChartCollection charts = worksheet.getCharts();
Chart chart = charts.get(0);
// Adding NSeries (chart data source) to the chart ranging from "A1"
// cell
SeriesCollection nSeries = chart.getNSeries();
nSeries.add("A1:B3", true);
Series aSeries = nSeries.get(0);
Line line = aSeries.getSeriesLines();
line.setStyle(LineType.DOT);
// Applying a triangular marker style on the data markers of an NSeries
aSeries.getMarker().setMarkerStyle(ChartMarkerType.TRIANGLE);
// Setting the weight of all lines in an NSeries to medium
aSeries = nSeries.get(1);
line = aSeries.getSeriesLines();
line.setWeight(WeightType.MEDIUM_LINE);
// Save the Excel file
workbook.save(dataDir + "SettingChartLines_out.xls");
// Print message
System.out.println("ChartArea is settled successfully.");

Aplicando temas de Microsoft Excel 2007/2010 a gráficos

Los desarrolladores pueden aplicar diferentes temas y colores de Microsoft Excel al SeriesCollection u otros objetos de gráficos como se muestra en el ejemplo a continuación.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ApplyingThemes.class) + "charts/";
// Instantiate the workbook to open the file that contains a chart
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Get the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Get the first chart in the sheet
Chart chart = worksheet.getCharts().get(0);
// Specify the FilFormat's type to Solid Fill of the first series
chart.getNSeries().get(0).getArea().getFillFormat().setFillType(FillType.SOLID);
// Get the CellsColor of SolidFill
CellsColor cc = chart.getNSeries().get(0).getArea().getFillFormat().getSolidFill().getCellsColor();
// Create a theme in Accent style
cc.setThemeColor(new ThemeColor(ThemeColorType.ACCENT_6, 0.6));
// Apply the them to the series
chart.getNSeries().get(0).getArea().getFillFormat().getSolidFill().setCellsColor(cc);
// Save the Excel file
workbook.save(dataDir + "AThemes_out.xlsx");

Configuración de los Títulos de Gráficos o Ejes

Puedes usar Microsoft Excel para establecer los títulos de un gráfico y sus ejes en un entorno WYSIWYG como se muestra a continuación.

Configuración de títulos de un gráfico y sus ejes utilizando Microsoft Excel

todo:image_alt_text

Aspose.Cells también permite a los desarrolladores establecer los títulos de un gráfico y sus ejes en tiempo de ejecución. Todos los gráficos y sus ejes contienen un método Title.setText que se puede usar para establecer sus títulos como se muestra en el siguiente ejemplo. Después de ejecutar el código de ejemplo, se agregará un gráfico de columnas a la hoja de cálculo como se muestra a continuación:

Gráfico de columnas después de establecer los títulos

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingTitlesAxes.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "book1.xls");
WorksheetCollection worksheets = workbook.getWorksheets();
// Obtaining the reference of the newly added worksheet by passing its
// sheet index
Worksheet worksheet = worksheets.get(0);
Cells cells = worksheet.getCells();
// Adding a chart to the worksheet
ChartCollection charts = worksheet.getCharts();
// Accessing the instance of the newly added chart
int chartIndex = charts.add(ChartType.COLUMN, 5, 0, 15, 7);
Chart chart = charts.get(chartIndex);
// Setting the title of a chart
Title title = chart.getTitle();
title.setText("ASPOSE");
// Setting the font color of the chart title to blue
Font font = title.getFont();
font.setColor(Color.getBlue());
// Setting the title of category axis of the chart
Axis categoryAxis = chart.getCategoryAxis();
title = categoryAxis.getTitle();
title.setText("Category");
// Setting the title of value axis of the chart
Axis valueAxis = chart.getValueAxis();
title = valueAxis.getTitle();
title.setText("Value");
// Adding NSeries (chart data source) to the chart ranging from "A1"
// cell
SeriesCollection nSeries = chart.getNSeries();
nSeries.add("A1:B3", true);
// Setting the foreground color of the plot area
ChartFrame plotArea = chart.getPlotArea();
Area area = plotArea.getArea();
area.setForegroundColor(Color.getBlue());
// Setting the foreground color of the chart area
ChartArea chartArea = chart.getChartArea();
area = chartArea.getArea();
area.setForegroundColor(Color.getYellow());
// Setting the foreground color of the 1st NSeries area
Series aSeries = nSeries.get(0);
area = aSeries.getArea();
area.setForegroundColor(Color.getRed());
// Setting the foreground color of the area of the 1st NSeries point
ChartPointCollection chartPoints = aSeries.getPoints();
ChartPoint point = chartPoints.get(0);
point.getArea().setForegroundColor(Color.getCyan());
// Save the Excel file
workbook.save(dataDir + "SettingTitlesAxes_out.xls");
// Print message
System.out.println("Chart Title is changed successfully.");

Configuración de Líneas de Rejilla Principales

Ocultar líneas de cuadrícula principales

Los desarrolladores pueden controlar la visibilidad de las líneas de rejilla principales mediante el uso del método setVisible del objeto Line. Después de ocultar las líneas de rejilla principales, un gráfico de columnas agregado a la hoja de cálculo tendrá el siguiente aspecto:

Un gráfico de columnas con líneas de rejilla principales ocultas

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Hiding the major gridlines of value axis
Axis valueAxis = chart.getValueAxis();
Line majorGridLines = valueAxis.getMajorGridLines();
majorGridLines.setVisible(false);

Cambiando la configuración de las líneas de cuadrícula principales

Los desarrolladores no solo pueden controlar la visibilidad de las líneas de rejilla principales, sino también otras propiedades como su color, etc. Después de establecer el color de las líneas de rejilla principales, un gráfico de columnas agregado a la hoja de cálculo tendrá el siguiente aspecto:

Gráfico de columnas con líneas de rejilla principales coloreadas

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Setting the color of major gridlines of value axis to silver
Axis categoryAxis = chart.getCategoryAxis();
categoryAxis.getMajorGridLines().setColor(Color.getSilver());

Configuración de Bordes para Paredes Delanteras y Laterales

Desde el lanzamiento de Microsoft Excel 2007, las paredes de un gráfico 3D se han dividido en dos partes: pared lateral y pared trasera, por lo que tenemos que usar dos objetos Walls para representarlas por separado y puedes acceder a ellas mediante Chart.getBackWall() y Chart.getSideWall().

El ejemplo a continuación muestra cómo establecer el borde de la pared lateral utilizando diferentes atributos.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Get the side wall border line
Line sideLine = chart.getSideWall().getBorder();
// Make it visible
sideLine.setVisible(true);
// Set the solid line
sideLine.setStyle(LineType.SOLID);
// Set the line width
sideLine.setWeight(10);
// Set the color
sideLine.setColor(Color.getBlack());

Cambiar la Posición y el Tamaño del Gráfico

A veces, quieres cambiar la posición o tamaño del gráfico nuevo o existente dentro de la hoja de cálculo. Aspose.Cells proporciona la propiedad Chart.getChartObject() para lograr esto. Puedes usar sus subpropiedades para cambiar el tamaño del gráfico con una nueva altura y ancho o reposicionarlo con nuevas coordenadas X y Y.

Modificación de la Posición y el Tamaño del Gráfico

Para cambiar la posición (coordenadas X, Y) y el tamaño (altura, ancho) del gráfico, usa estas propiedades:

  1. Chart.getChartObject().get/setWidth()
  2. Chart.getChartObject().get/setHeight()
  3. Chart.getChartObject().get/setX()
  4. Chart.getChartObject().get/setY()

El siguiente ejemplo explica el uso de las propiedades anteriores. Carga el libro de trabajo existente que contiene un gráfico en su primera hoja de trabajo. Luego redimensiona y reposiciona el gráfico y guarda el libro de trabajo.

Antes de la ejecución del código de ejemplo, el archivo fuente se ve así:

Tamaño y posición del gráfico antes de la ejecución del código de ejemplo

todo:image_alt_text

Después de la ejecución, el archivo de salida se ve así:

Tamaño y posición del gráfico después de la ejecución del código de ejemplo

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ChangeChartPositionAndSize.class) + "charts/";
String filePath = dataDir + "book1.xls";
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.getWorksheets().get(0);
// Load the chart from source worksheet
Chart chart = worksheet.getCharts().get(0);
// Resize the chart
chart.getChartObject().setWidth(400);
chart.getChartObject().setHeight(300);
// Reposition the chart
chart.getChartObject().setX(250);
chart.getChartObject().setY(150);
// Output the file
workbook.save(dataDir + "ChangeChartPositionAndSize_out.xls");
// Print message
System.out.println("Position and Size of Chart is changed successfully.");

Manipulación de gráficos de diseñador

Hay momentos en los que es posible que necesite manipular o modificar los gráficos en sus archivos de plantilla de diseñador. Aspose.Cells da soporte total para manipular gráficos de diseñador con sus contenidos y elementos. Los datos, contenidos del gráfico, imagen de fondo y formato se pueden conservar con precisión.

Manipulación de gráficos de diseñador en los archivos de plantilla

Para manipular gráficos de diseñador en un archivo de plantilla, utilice todas las llamadas a la API relacionadas con el gráfico. Por ejemplo, use la propiedad Worksheet.getCharts para obtener la colección de gráficos existente en el archivo de plantilla.

Creación de un gráfico

El siguiente ejemplo muestra cómo crear un gráfico circular. Más adelante manipularemos este gráfico. El siguiente resultado es generado por el código.

El gráfico circular de entrada

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CreateChart.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);
// Adding some sample value to cells
Cells cells = sheet.getCells();
Cell cell = cells.get("A1");
cell.setValue(50);
cell = cells.get("A2");
cell.setValue(100);
cell = cells.get("A3");
cell.setValue(150);
cell = cells.get("B1");
cell.setValue(4);
cell = cells.get("B2");
cell.setValue(20);
cell = cells.get("B3");
cell.setValue(50);
ChartCollection charts = sheet.getCharts();
// Adding a chart to the worksheet
int chartIndex = charts.add(ChartType.PYRAMID, 5, 0, 15, 5);
Chart chart = charts.get(chartIndex);
// Adding NSeries (chart data source) to the chart ranging from "A1"
// cell to "B3"
SeriesCollection serieses = chart.getNSeries();
serieses.add("A1:B3", true);
// Saving the Excel file
workbook.save(dataDir + "CreateChart_out.xls");
// Print message
System.out.println("Workbook with chart is successfully created.");

Manipulación del gráfico

El siguiente ejemplo muestra cómo manipular el gráfico existente. En este ejemplo, modificamos el gráfico creado previamente. El siguiente resultado es generado por el código. Tenga en cuenta que el color del título del gráfico ha cambiado de azul a negro y ‘Inglaterra 30000’ se ha cambiado a ‘Reino Unido, 30K’.

El gráfico circular ha sido modificado

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ModifyPieChart.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "ModifyCharts.xlsx");
// Obtaining the reference of the first worksheet
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(1);
// Load the chart from source worksheet
Chart chart = sheet.getCharts().get(0);
DataLabels datalabels = chart.getNSeries().get(0).getPoints().get(0).getDataLabels();
datalabels.setText("aspose");
// Saving the Excel file
workbook.save(dataDir + "ModifyPieChart_out.xls");
// Print message
System.out.println("Pie chart is successfully modified.");

Manipulación de un gráfico de líneas en la plantilla de diseñador

En este ejemplo, manipularemos un gráfico de líneas. Agregaremos algunas series de datos al gráfico existente y cambiaremos sus colores de línea.

Primero, echa un vistazo al gráfico de líneas del diseñador.

El gráfico de líneas de entrada

todo:image_alt_text

Ahora manipulamos el gráfico de líneas (que se encuentra en el archivo linechart.xls) usando el siguiente código. La siguiente salida es generada por el código.

El gráfico de líneas manipulado

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ModifyLineChart.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Obtaining the reference of the first worksheet
WorksheetCollection worksheets = workbook.getWorksheets();
Worksheet sheet = worksheets.get(0);
// Load the chart from source worksheet
Chart chart = sheet.getCharts().get(0);
// Adding NSeries (chart data source) to the chart ranging from "A1"
// cell to "B3"
SeriesCollection serieses = chart.getNSeries();
serieses.add("{20,40,90}", true);
serieses.add("{110,70,220}", true);
// Saving the Excel file
workbook.save(dataDir + "ModifyLineChart_out.xls");
// Print message
System.out.println("Line chart is successfully modified.");

Usando Sparklines

Microsoft Excel 2010 puede analizar la información de más maneras que nunca. Permite a los usuarios realizar un seguimiento y resaltar tendencias importantes de datos con nuevas herramientas de análisis y visualización de datos. Las sparklines son mini gráficos que se pueden colocar dentro de las celdas para que puedas ver los datos y el gráfico en la misma tabla. Cuando se usan sparklines de manera adecuada, el análisis de datos es más rápido y preciso. También proporcionan una vista simple de la información, evitando hojas de cálculo sobrecargadas con una gran cantidad de gráficos ocupados.

Aspose.Cells proporciona una API para manipular sparklines en hojas de cálculo.

Sparklines en Microsoft Excel

Para insertar sparklines en Microsoft Excel 2010:

  1. Selecciona las celdas donde quieres que aparezcan las sparklines. Para que sean fáciles de ver, selecciona las celdas al lado de los datos.
  2. Haz clic en Insertar en la cinta y luego elige columna en el grupo de Sparklines.

todo:image_alt_text

  1. Selecciona o ingresa el rango de celdas en la hoja de cálculo que contenga los datos fuente. Los gráficos aparecen.

Las sparklines te ayudan a ver tendencias, por ejemplo, el récord de victorias o derrotas de una liga de softbol. Las sparklines incluso pueden resumir toda la temporada de cada equipo en la liga.

todo:image_alt_text

Sparklines usando Aspose.Cells

Los desarrolladores pueden crear, eliminar o leer sparklines (en el archivo de plantilla) usando la API proporcionada por Aspose.Cells. Al agregar gráficos personalizados para un rango de datos dado, los desarrolladores tienen la libertad de agregar diferentes tipos de pequeños gráficos a áreas de celdas seleccionadas.

El siguiente ejemplo demuestra la función de Sparklines. El ejemplo muestra cómo:

  1. Abrir un archivo de plantilla simple.
  2. Leer la información de sparklines para una hoja de cálculo.
  3. Agregar nuevas miniaturas para un rango de datos dado a un área de celdas.
  4. Guardar el archivo de Excel en disco.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(UsingSparklines.class) + "charts/";
// Instantiating a Workbook object
Workbook workbook = new Workbook();
WorksheetCollection worksheets = workbook.getWorksheets();
// Obtaining the reference of the first worksheet
Worksheet worksheet = worksheets.get(0);
Cells cells = worksheet.getCells();
System.out.println("Sparkline count: " + worksheet.getSparklineGroupCollection().getCount());
for (int i = 0; i < worksheet.getSparklineGroupCollection().getCount(); i++) {
SparklineGroup g = worksheet.getSparklineGroupCollection().get(i);
System.out.println("sparkline group: type:" + g.getType());
for (int j = 0; j < g.getSparklineCollection().getCount(); i++) {
Sparkline gg = g.getSparklineCollection().get(i);
System.out.println("sparkline: row:" + gg.getRow() + ", col:" + gg.getColumn() + ", dataRange:"
+ gg.getDataRange());
}
}
// Add Sparklines
// Define the CellArea D2:D10
CellArea ca = new CellArea();
ca.StartColumn = 4;
ca.EndColumn = 4;
ca.StartRow = 1;
ca.EndRow = 7;
int idx = worksheet.getSparklineGroupCollection().add(SparklineType.COLUMN, "Sheet1!B2:D8", false, ca);
SparklineGroup group = worksheet.getSparklineGroupCollection().get(idx);
// Create CellsColor
CellsColor clr = workbook.createCellsColor();
clr.setColor(Color.getChocolate());
group.setSeriesColor(clr);
workbook.save(dataDir + "UsingSparklines_out.xls");
// Print message
System.out.println("Workbook with chart is created successfully.");

Aplicación de formato 3D al gráfico

Es posible que necesite estilos de gráficos en 3D para obtener solo los resultados necesarios para su escenario. Las API de Aspose.Cells proporcionan la API relevante para aplicar el formato 3D de Microsoft Excel 2007, como se demuestra en este artículo.

Estableciendo formato 3D al gráfico

A continuación se proporciona un ejemplo completo para demostrar cómo crear un gráfico y aplicar el formato 3D de Microsoft Excel 2007. Después de ejecutar el código de ejemplo anterior, se agregará un gráfico de columnas (con efectos 3D) a la hoja de cálculo como se muestra a continuación.

Un gráfico de columnas con formato 3D

todo:image_alt_text

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(Applying3DFormat.class) + "charts/";
// Instantiate a new Workbook
Workbook book = new Workbook();
// Add a Data Worksheet
Worksheet dataSheet = book.getWorksheets().add("DataSheet");
// Add Chart Worksheet
Worksheet sheet = book.getWorksheets().add("MyChart");
// Put some values into the cells in the data worksheet
dataSheet.getCells().get("B1").putValue(1);
dataSheet.getCells().get("B2").putValue(2);
dataSheet.getCells().get("B3").putValue(3);
dataSheet.getCells().get("A1").putValue("A");
dataSheet.getCells().get("A2").putValue("B");
dataSheet.getCells().get("A3").putValue("C");
// Define the Chart Collection
ChartCollection charts = sheet.getCharts();
// Add a Column chart to the Chart Worksheet
int chartSheetIdx = charts.add(ChartType.COLUMN, 5, 0, 25, 15);
// Get the newly added Chart
Chart chart = book.getWorksheets().get(2).getCharts().get(0);
// Set the background/foreground color for PlotArea/ChartArea
chart.getPlotArea().getArea().setBackgroundColor(Color.getWhite());
chart.getChartArea().getArea().setBackgroundColor(Color.getWhite());
chart.getPlotArea().getArea().setForegroundColor(Color.getWhite());
chart.getChartArea().getArea().setForegroundColor(Color.getWhite());
// Hide the Legend
chart.setShowLegend(false);
// Add Data Series for the Chart
chart.getNSeries().add("DataSheet!B1:B3", true);
// Specify the Category Data
chart.getNSeries().setCategoryData("DataSheet!A1:A3");
// Get the Data Series
Series ser = chart.getNSeries().get(0);
// Apply the 3D formatting
ShapePropertyCollection spPr = ser.getShapeProperties();
Format3D fmt3d = spPr.getFormat3D();
// Specify Bevel with its height/width
Bevel bevel = fmt3d.getTopBevel();
bevel.setType(BevelPresetType.CIRCLE);
bevel.setHeight(5);
bevel.setWidth(9);
// Specify Surface material type
fmt3d.setSurfaceMaterialType(PresetMaterialType.WARM_MATTE);
// Specify surface lighting type
fmt3d.setSurfaceLightingType(LightRigType.THREE_POINT);
// Specify lighting angle
fmt3d.setLightingAngle(20);
// Specify Series background/foreground and line color
ser.getArea().setBackgroundColor(Color.getMaroon());
ser.getArea().setForegroundColor(Color.getMaroon());
ser.getBorder().setColor(Color.getMaroon());
// Save the Excel file
book.save(dataDir + "A3DFormat_out.xls");
// Print message
System.out.println("3D format is applied successfully.");

Temas avanzados