Is there a way of creating and inserting a bar chart in a Ms Word document using Aspose Words for Java? I can't find a way to do this. Thanks.
Aspose.Words for Java currently doesn't allow you to create the bar chart in Word documents. However, if you just want to add a static bar chart, you may try Aspose.Cells for Java to create bar chart and render it to image. After that, you can add this bar chart image in Word document using Aspose.Words for Java. Do you think this might help in your scenario? If it does then you can use the following code snippet to create and render the bar chart to image:
//Create a new Workbook.
Workbook workbook = new Workbook();
//Get the first worksheet.
Worksheet sheet = workbook.getWorksheets().get(0);
//Set the name of worksheet
sheet.setName("Data");
//Get the cells collection in the sheet.
Cells cells = workbook.getWorksheets().get(0).getCells();
//Put some values into a cells of the Data sheet.
cells.get("A1").setValue("Region");
cells.get("A2").setValue("France");
cells.get("A3").setValue("Germany");
cells.get("A4").setValue("England");
cells.get("A5").setValue("Sweden");
cells.get("A6").setValue("Italy");
cells.get("A7").setValue("Spain");
cells.get("A8").setValue("Portugal");
cells.get("B1").setValue("Sale");
cells.get("B2").setValue(70000);
cells.get("B3").setValue(55000);
cells.get("B4").setValue(30000);
cells.get("B5").setValue(40000);
cells.get("B6").setValue(35000);
cells.get("B7").setValue(32000);
cells.get("B8").setValue(10000);
//Create chart
int chartIndex = sheet.getCharts().add(ChartType.COLUMN, 12, 1, 33,
12);
Chart chart = sheet.getCharts().get(chartIndex);
//Set properties of chart title
chart.getTitle().setText("Sales By Region");
chart.getTitle().getTextFont().setBold(true);
chart.getTitle().getTextFont().setSize(12);
//Set properties of nseries
chart.getNSeries().add("Data!B2:B8", true);
chart.getNSeries().setCategoryData("Data!A2:A8");
//Set the fill colors for the series's data points (France -
Portugal(7 points))
ChartPointCollection chartPoints =
chart.getNSeries().get(0).getPoints();
ChartPoint point = chartPoints.get(0);
point.getArea().setForegroundColor(Color.getCyan());
point = chartPoints.get(1);
point.getArea().setForegroundColor(Color.getBlue());
point = chartPoints.get(2);
point.getArea().setForegroundColor(Color.getYellow());
point = chartPoints.get(3);
point.getArea().setForegroundColor(Color.getRed());
point = chartPoints.get(4);
point.getArea().setForegroundColor(Color.getBlack());
point = chartPoints.get(5);
point.getArea().setForegroundColor(Color.getGreen());
point = chartPoints.get(6);
point.getArea().setForegroundColor(Color.getMaroon());
//Set the legend invisible
chart.setShowLegend(false);
//Get the Chart mage
ImageOrPrintOptions imgOpts = new ImageOrPrintOptions();
imgOpts.setImageFormat(ImageFormat.getPng());
//Save the chart image file.
chart.toImage(new FileOutputStream("D:\Files\MyChartImage.png"),
imgOpts);
Disclosure: I work as developer evangelist at Aspose.
Related
I'm new to itext7
Recently, I'm generating custom report pdf by iText7.
There is one layout I want to approach.
Make the vertically text align in the middle of the cell.
To illustrate my purpose, the first screenshot demonstrate my progress.
The second screenshot is what I want.
Here is how I implement my approach.
//Init table
Table table = new Table(UnitValue.createPercentArray(new float[]{20, 20, 20, 20, 20})).setWidth(UnitValue.createPercentValue(100));
//Init cellHeader
Paragraph servicePara = new Paragraph("Date of Service");
servicePara.setBorder(new SolidBorder(new DeviceRgb(5, 10, 50), 1));
servicePara.setBackgroundColor(DeviceCmyk.YELLOW);
servicePara.setRotationAngle(Math.PI / 2);
Cell cell = new Cell();
cell.add(servicePara);
table.addHeaderCell(cell);
In the excel, here's what I expect, as shown below
enter image description here
In the excel, there is a data labels on the chart, the values displayed default to horizontal, I can set text direction to rotate all text 270 in the text options of format data labels. but, I don't know how to implement this in code with apache poi? Could anyone help?
Here is the code:
XSSFDrawing drawing = (XSSFDrawing)sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 4, 27, 5);
XSSFChart chart = drawing.createChart(anchor);
XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setTitle("Week");
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setTitle("Face Amount ($MM)");
leftAxis.setCrossBetween(AxisCrossBetween.BETWEEN);
leftAxis.setMaximum(10000);
XDDFDataSource<Double> xs = XDDFDataSourcesFactory.fromNumericCellRange((XSSFSheet) sheet,
new CellRangeAddress(299, 299, 0, NUM_OF_COLUMNS - 1));
XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange((XSSFSheet) sheet,
new CellRangeAddress(300, 300, 0, NUM_OF_COLUMNS - 1));
XDDFChartData data = chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);
XDDFChartData.Series series1 = data.addSeries(xs, ys);
series1.setTitle("2x", null);
chart.plot(data);
XDDFBarChartData bar = (XDDFBarChartData) data;
bar.setBarDirection(BarDirection.COL);
bar.setGapWidth(3);
bar.setBarGrouping(BarGrouping.STACKED);
//set data labels
XSSFChart xssfChart = (XSSFChart) chart;
CTPlotArea plotArea = xssfChart.getCTChart().getPlotArea();
CTBoolean ctBool = CTBoolean.Factory.newInstance();
ctBool.setVal(true);
plotArea.getBarChartArray(0).getSerArray(0).addNewDLbls().setShowVal(ctBool);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().addNewShowLeaderLines();
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowLeaderLines(ctBool);
ctBool.setVal(false);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowSerName(ctBool);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowPercent(ctBool);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowLegendKey(ctBool);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowCatName(ctBool);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowLeaderLines(ctBool);
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().setShowBubbleSize(ctBool);
As your code shows, you are setting the data labels using the underlying low level beans of apache poi.
But how can one working with those? There is no documentation about org.openxmlformats.schemas.drawingml.x2006.chart.* classes public available. So we need downloading the sources of ooxml-schemas from maven for example. Then we can use javadoc to create a API documentation. Now we can look how to create and use the classes.
But also we need the meanings of the XML elements and attributes, the classes are creating. For this one could study the Office Open XML specifications. But my preferred method is to create a simple *.xlsx file having the needed settings using Excel's GUI. Then unzip that *.xlsx file and have a look at the XML in the *.xml files stored in that ZIP archive. For the first chart this is /xl/charts/chart1.xml.
Doing this we will find:
<c:dLbls>
<c:txPr>
<a:bodyPr rot="-5400000"/>
<a:p><a:pPr><a:defRPr/></a:pPr></a:p>
</c:txPr>
...
</c:dLbls>
for data labels when text rotation is set.
That is a txPr (text properties) element in dLbls having a bodyPr (body properties) element having a rot attribute set. Value of the rot attribute is rotation angle * 60000. The -5400000 for example is -90.00 * 60000. Also there is a p (paragraph) element having a pPr (paragraph properties) element having a defRPr (default run properties) to set that the data label text runs have default properties.
Putting all together the code used in apache poi for this would be:
...
// text properties having rotation set
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().addNewTxPr()
.addNewBodyPr().setRot((int)(-90.00 * 60000));
// paragraph properties having default run properties set
plotArea.getBarChartArray(0).getSerArray(0).getDLbls().getTxPr()
.addNewP().addNewPPr().addNewDefRPr();
...
where plotArea is CTPlotArea as in your code. And the first series must have dLbls set using addNewDLbls as you done in your code.
I created a line chart and when I add the title to my chart it overlaps my data. How do I add the title above my chart? Also how can I adjust the font/style of the title text? I want to make the text a little smaller.
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
chart.setTitleText("This is my title");
// Use a category axis for the bottom axis.
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
ChartDataSource<Integer> test = DataSources.fromArray([2011,2012,2013,2014,2015,2016,2017] as Integer[]);
ChartDataSource<Integer> test2 = DataSources.fromArray([4805, 7351, 5333, 7183, 6230, 4050, 6963] as Integer[]);
LineChartData data = chart.getChartDataFactory().createLineChartData();
data.addSeries(test, test2);
chart.plot(data, bottomAxis, leftAxis);
So from this example what I looking for is extra padding/margin above the 8000 where my title would go.
So you don't want the title overlaying the plot area?
The problem is that apache poi was tested using Excel 2007. But after this version multiple default settings have been changed in later versions.
The setting of overlays for example had defaulted to false (do not overlay) in Excel 2007 if it was not explicit set. This was a good choice in my opinion. In later versions the default is true (do overlay) if it is not explicit set. That's nonsense in my opinion. But who cares my opinion.
So if we not want the title overlaying the plot area, we have to set this explicitly.
Styling the title font is possible only using the low level underlying objects. Using this we need add run properties to the title's first paragraph and first text run. Then we can set bold, italic and font size (unit 1/100 pt). And then we add type face for latin and complex script characters.
Example code using Java. (The code in the question seems to be Groovy, but it is not tagged as such and there is no answer to my question about this discrepancy.)
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
public class LineChartProblem {
public static void main(String[] args) throws IOException {
try (XSSFWorkbook wb = new XSSFWorkbook()) {
Sheet sheet = wb.createSheet("linechart");
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 10, 15);
Chart chart = drawing.createChart(anchor);
((XSSFChart)chart).setTitleText("This is my title");
//set "the title overlays the plot area" to false explicitly
((XSSFChart)chart).getCTChart().getTitle().addNewOverlay().setVal(false);
//set font style for title - low level
//add run properties to title's first paragraph and first text run. Set bold.
((XSSFChart)chart).getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray(0).addNewRPr().setB(true);
//set italic
((XSSFChart)chart).getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray(0).getRPr().setI(true);
//set font size 20pt
((XSSFChart)chart).getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray(0).getRPr().setSz(2000);
//add type face for latin and complex script characters
((XSSFChart)chart).getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray(0).getRPr().addNewLatin().setTypeface("Times New Roman");
((XSSFChart)chart).getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray(0).getRPr().addNewCs().setTypeface("Times New Roman");
// Use a category axis for the bottom axis.
ChartAxis bottomAxis = chart.getChartAxisFactory().createCategoryAxis(AxisPosition.BOTTOM);
ValueAxis leftAxis = chart.getChartAxisFactory().createValueAxis(AxisPosition.LEFT);
ChartDataSource<Integer> test = DataSources.fromArray(new Integer[]{2011,2012,2013,2014,2015,2016,2017});
ChartDataSource<Integer> test2 = DataSources.fromArray(new Integer[]{4805, 7351, 5333, 7183, 6230, 4050, 6963});
LineChartData data = chart.getChartDataFactory().createLineChartData();
data.addSeries(test, test2);
chart.plot(data, bottomAxis, leftAxis);
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("ooxml-line-chart.xlsx")) {
wb.write(fileOut);
}
}
}
}
I want to share diamond detail in table format(Plain text not HTML)
I have made this using this library but its prints the data properly using the system.out but while I sharing it, its format is changed:
Below is my code:
List<String> headersList = Arrays.asList("", "");
List<List<String>> rowsList = Arrays.asList(
Arrays.asList("Stone Id :", details[0]),
Arrays.asList("Lab", details[1]),
Arrays.asList("Shape", details[2]),
Arrays.asList("Carat", details[3]),
Arrays.asList("Clarity-Color", details[4]),
Arrays.asList("Cut-Pol-Sym-Flou", details[5]));
Board board = new Board(75);
Table table = new Table(board, 75, headersList, rowsList);
table.invalidate().setGridMode(Table.GRID_NON).setRowsList(rowsList);
List<Integer> colWidthsList = Arrays.asList(30, 14);
table.setColWidthsList(colWidthsList);
Block tableBlock = table.tableToBlocks();
board.setInitialBlock(tableBlock);
board.build();
String preview1 = board.getPreview();
System.out.print(preview1);
sharingIntent.putExtra(Intent.EXTRA_TEXT,preview1);
The console uses monospaced font which takes exactly same width for all characters. But your view isn't using it, so it looks messed up.
Use a monospaced font.
Or use a tabular format. Perhaps a ListView with each row having two text views side by side having fixed width.
I have a table that contains some data. I know that I can access of my first row like this,
Object nameOfFile = Main_Menu.jTable3.getValueAt(0, 0);
String nameOfFileToString = nameOfFile.toString();
My table is dynamic. Sometimes my row of the table is 100, sometimes is 200. How can I get the last row of my table even my table is dynamically change.
P.S : my table is connected with a jfreechart, so I need this for my update Y axis in jfreechart like this
Object nameOfFile = Main_Menu.jTable3.getValueAt(0, 0);
String nameOfFileToString = nameOfFile.toString();
// create the chart...
final JFreeChart chart = ChartFactory.createLineChart(
"Persentastion Of Similarity", // chart title
"", // domain axis label
nameOfFileToString, // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
for the help, thanks
You can use JTable.getModel().getRowCount() to get the number of rows; the rest is straightforward:
Object nameOfFile = Main_Menu.jTable3.getValueAt(jTable3.getModel().getRowCount()-1, 0);
// go on with your code
Thank you so much for all of you.
This code is rock
Object nameOfFile = Main_Menu.jTable3.getValueAt(jTable3.getModel().getRowCount()-1, 0);
Now, my application is looking fine. I haven't try getrowSorter but soon I will try.
Once again, thanks...