Wednesday, 30 December 2020

Create and Refresh a Pivot Table in Excel using Java

A Pivot Table is usually used to sort, count and total the data that includes the total figures, average, maximum, minimum and so on. By using it, users can group and summarize large amounts of data in a concise, tabular format for easier reporting and analysis. This article will demonstrate how to create a pivot table in an Excel worksheet using Java codes and refresh it after changing the data source.

Dependency

A free API used in this tutorial is called Free Spire.XLS for Java. Before typing codes, we need to download it from the website and then insert Spire.Xls,jar into IDEA or directly reference it using the following Maven configurations:

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

Create a Pivot Table

Free Spire.XLS for Java supports creating a pivot table according to the data source in an Excel

worksheet. Here are some steps to do it.

Step 1. Load an Excel document as a sample and get its first worksheet.

Step 2. Select the data source range.

Step 3. Create a pivot table and set its title and location.

Step 4. Separately add data to the row field, column field and value field.

Step 5. Set the PivotTable style and save the resulting file.

import com.spire.xls.*;
public class CreatePivotTable {
public static void main(String[] args) {
//Load an Excel sample
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Select the data source range
CellRange dataRange = sheet.getCellRange("A1:C17");
PivotCache cache = workbook.getPivotCaches().add(dataRange);

//Add a PivotTable to the worksheet and set the title and location of it
PivotTable pt = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("D4"), cache);

//Add data to the row field
PivotField pf1 = null;
if (pt.getPivotFields().get("Quarter") instanceof PivotField){
pf1 = (PivotField) pt.getPivotFields().get("Quarter");
}
pf1.setAxis(AxisTypes.Row);
//Set the title of the row field
pt.getOptions().setRowHeaderCaption("Quarter");

//Add data to the column field
PivotField pf2 = null;
if (pt.getPivotFields().get("Product") instanceof PivotField){
pf2 = (PivotField) pt.getPivotFields().get("Product");
}
pf2.setAxis(AxisTypes.Column);
//Set the title of the column field
pt.getOptions().setColumnHeaderCaption("Product");

//Add data to the value field
pt.getDataFields().add(pt.getPivotFields().get("Sales"),"SUM of sales",SubtotalTypes.Sum);

//Set PivotTable style
pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium12);

//Save the document
workbook.saveToFile("output/CreatePivotTable.xlsx", ExcelVersion.Version2013);
}
}

Output


Refresh a Pivot Table

In addition to creating a pivot table, Free Spire.XLS for Java supports refresh the pivot table after

changing the data source. The following codes demonstrate how to refresh the original pivot table after

changing the products’ names.

import com.spire.xls.*;
public class RefreshPivotTable {
public static void main(String[] args) {
//Load an Excel sample
Workbook wb = new Workbook();
wb.loadFromFile("C:\\Users\\Test1\\Desktop\\CreatePivotTable.xlsx");

//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);

//Change the data source of the Pivot Table
sheet.getCellRange("B2:B5").setText("Refrigerator");
sheet.getCellRange("B6:B9").setText("Air Conditioner");
sheet.getCellRange("B10:B13").setText("Washing Machine");
sheet.getCellRange("B14:B17").setText("Kitchen Ventilator");

//Get the Pivot Table and refresh the data
PivotTable pivotTable = (PivotTable) sheet.getPivotTables().get(0);
pivotTable.getCache().isRefreshOnLoad();

//Saving the resulting file
wb.saveToFile("output/RefreshPivotTable.xlsx",FileFormat.Version2013);
}
}
Output


Sunday, 27 December 2020

[Java] Create a chart in a PowerPoint slide

In general, a chart is a graphical representation of data, and it allows users to see what the results of data to better understand and predict current and future data. Adding charts to a presentation can help create more impact and make data meaningful to your audience. In this article, I’ll show you how to add a chart to a presentation using Java codes programmatically.

Free Spire.Presentation for Java, a free API I used in this tutorial, supports creating many different types of data charts including column charts, cylinder charts, cone charts, pyramid charts, line charts, pie charts and so on. I’ll take a column chart as an example.

Dependency

Before typing codes, you need to download the package and add the jar file to your project or directly reference it from the following Maven configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Create a column chart

Here are steps to create a column chart in a Presentation slide using Free Spire.Presentation for Java.

1.      Create a PowerPoint document

2.      Insert chart and set its title and style.

3.      Create a dataTable and insert data into it.

4.      Import data from dataTable to the column chart.

5.      Set the Series label and Category label.

6.      Assign data to each Series.

7.      Set overlap and gap width.

8.      Save the document.


import com.spire.presentation.*;
import com.spire.pdf.tables.table.*;
import com.spire.presentation.charts.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.geom.Rectangle2D;
import java.lang.Object;

public class CreateChart {
public static void main(String[] args) throws Exception {
//Create a presentation instance
Presentation presentation = new Presentation();

//Add a column clustered chart
Rectangle2D.Double rect = new Rectangle2D.Double(40, 100, 550, 320);
IChart chart = null;
chart = presentation.getSlides().get(0).getShapes().appendChart(ChartType.COLUMN_CLUSTERED, rect);

//Set chart title
chart.getChartTitle().getTextProperties().setText("Sales Report");
chart.getChartTitle().getTextProperties().isCentered(true);
chart.getChartTitle().setHeight(30);
chart.hasTitle(true);

//Create a dataTable
DataTable dataTable = new DataTable();
dataTable.getColumns().add(new DataColumn("Category", DataTypes.DATATABLE_STRING));
dataTable.getColumns().add(new DataColumn("the sales in the first season", DataTypes.DATATABLE_INT));
dataTable.getColumns().add(new DataColumn("the sales in the second season", DataTypes.DATATABLE_INT));
dataTable.getColumns().add(new DataColumn("the sales in the third season", DataTypes.DATATABLE_INT));
DataRow row1 = dataTable.newRow();
row1.setString("Category", "refrigerator");
row1.setInt("the sales in the first season",143000 );
row1.setInt("the sales in the second season", 102000);
row1.setInt("the sales in the third season", 124000);
DataRow row2 = dataTable.newRow();
row2.setString("Category", "air conditioning");
row2.setInt("the sales in the first season", 115000);
row2.setInt("the sales in the second season", 75000);
row2.setInt("the sales in the third season", 59000);

DataRow row3 = dataTable.newRow();
row3.setString("Category", "washing machine");
row3.setInt("the sales in the first season", 102000);
row3.setInt("the sales in the second season", 38000);
row3.setInt("the sales in the third season", 86000);
DataRow row4 = dataTable.newRow();
row4.setString("Category", "range hood");
row4.setInt("the sales in the first season", 144000);
row4.setInt("the sales in the second season", 56000);
row4.setInt("the sales in the third season", 97000);

dataTable.getRows().add(row1);
dataTable.getRows().add(row2);
dataTable.getRows().add(row3);
dataTable.getRows().add(row4);

//Import data from dataTable to chart data
for (int c = 0; c < dataTable.getColumns().size(); c++) {
chart.getChartData().get(0, c).setText(dataTable.getColumns().get(c).getColumnName());
}
for (int r = 0; r < dataTable.getRows().size(); r++) {
Object[] datas = dataTable.getRows().get(r).getArrayList();
for (int c = 0; c < datas.length; c++) {
chart.getChartData().get(r + 1, c).setValue(datas[c]);

}
}
//Set series label
chart.getSeries().setSeriesLabel(chart.getChartData().get("B1", "D1"));

//Set category labels
chart.getCategories().setCategoryLabels(chart.getChartData().get("A2", "A6"));
//Assign values to each series
chart.getSeries().get(0).setValues(chart.getChartData().get("B2", "B6"));
chart.getSeries().get(1).setValues(chart.getChartData().get("C2", "C6"));
chart.getSeries().get(2).setValues(chart.getChartData().get("D2", "D6"));
chart.getSeries().get(2).getFill().setFillType(FillFormatType.SOLID);
chart.getSeries().get(2).getFill().getSolidColor().setKnownColor(KnownColors.LIGHT_BLUE);

//Set overlap
chart.setOverLap(-50);

//Set gap width
chart.setGapDepth(200);

//Save the document
presentation.saveToFile("output/CreateChart.pptx", FileFormat.PPTX_2010);
}
}

Output




Thursday, 24 December 2020

Convert PDF to Word (Doc/Docx) in Java using a free API

As we all know, PDF is widely used for sending the document out to third parties because of its compatibility across multiple platforms. However, in some cases, we need to convert PDF to an editable document format, such as Doc/Docx. This tutorial will showcase how to convert PDF to Word programmatically using Java codes. It’s worth mentioning that I used a free API called Free Spire.PDF for Java to do it.

Before typing codes, you need to download the package Free Spire.PDF for Java and add Spire.Pdf.jar file to your project or reference it using the following Maven configurations:

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
The testing PDF file including an image, text and hyperlink:

Convert PDF to Word (Doc/Docx) using Java

Free Spire.PDF for Java supports converting a PDF document to Word (Doc/Docx) format with several

lines of code. Here are steps required to do it.

l  Create a PdfDocument instance and load a PDF file.

l  Call the SaveToFile method with the output DOC/DOCX file’s name and FileFormat arguments.

import com.spire.pdf.*;

public class PDFToWord {
public static void main(String[] args) {
//create a PdfDocument object
PdfDocument doc = new PdfDocument();

//load a sample PDF file
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

//save as .doc file
doc.saveToFile("output/ToDoc.doc",FileFormat.DOC);
doc.saveToFile("output/ToDoc.docx",FileFormat.DOCX);
doc.close();
}
}

Output



Sunday, 20 December 2020

Create a Word document in Java using a free API

This article will demonstrate how to create a Word document in Java programmatically using a free API. It’s worth mentioning that the free API is called Free Spire.Doc for Java and it is a free and professional Java API that enables Java applications to create, manipulate, read, convert and print Word documents without using Microsoft Office.

Add Spire.Doc.jar as dependency

Before typing codes, please import Spire.Doc.jar as reference in your project. If you are creating a Maven project, you can easily add the jar dependency by writing the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

Copy and paste the following code to generate the Word document.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BuiltinStyle;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.ParagraphStyle;

public class CreateAWordDocument {
public static void main(String[] args) {
//create a Word document
Document document = new Document();

//add a section
Section section = document.addSection();

//add a heading
Paragraph heading = section.addParagraph();
heading.appendText("Java");

//add a subheading
Paragraph subheading_1 = section.addParagraph();
subheading_1.appendText("What's Java");

//add two paragraph under the first subheading
Paragraph para_1 = section.addParagraph();
para_1.appendText("Java is a general purpose, high-level programming language developed by Sun Microsystems."+
" The Java programming language was developed by a small team of engineers, " +
"known as the Green Team, who initiated the language in 1991.");
Paragraph para_2 = section.addParagraph();
para_2.appendText("Originally called OAK, the Java language was designed for handheld devices and set-top boxes. "+
"Oak was unsuccessful and in 1995 Sun changed the name to Java and modified the language to take "+
"advantage of the burgeoning World Wide Web. ");

//add another subheading
Paragraph subheading_2 = section.addParagraph();
subheading_2.appendText("Java Today");

//add one paragraph under the second subheading
Paragraph para_3 = section.addParagraph();
para_3.appendText("Today the Java platform is a commonly used foundation for developing and delivering content "+
"on the web. According to Oracle, there are more than 9 million Java developers worldwide and more "+
"than 3 billion mobile phones run Java.");

//apply built-in style to heading and subheadings
heading.applyStyle(BuiltinStyle.Title);
subheading_1.applyStyle(BuiltinStyle.Heading_3);
subheading_2.applyStyle(BuiltinStyle.Heading_3);

//customize a paragraph style
ParagraphStyle style = new ParagraphStyle(document);
style.setName("paraStyle");
style.getCharacterFormat().setFontName("Arial");
style.getCharacterFormat().setFontSize(11f);
document.getStyles().add(style);

//apply the style to other paragraphs
para_1.applyStyle("paraStyle");
para_2.applyStyle("paraStyle");
para_3.applyStyle("paraStyle");

//automatically add space after each paragraph
for (int i = 0; i < section.getParagraphs().getCount(); i++) {

section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true);
}

//save the document
document.saveToFile("output/CreateAWordDocument.docx", FileFormat.Docx);
}
}

Output



Thursday, 17 December 2020

Sort Data in Excel in Java

In this article, I’ll show you how to sort data by column in Excel worksheets using Java codes programmatically. It’s worth mentioning that I used a third-party library called Spire.XLSfor Java and it is a professional Java API that enables developers to create, manage, manipulate, convert and print Excel worksheets without using Microsoft Office.

The code samples in this tutorial will be demonstrated from three aspects as below.

l  Sort Data Based on Cell Values

l  Sort Data Based on Cell Color

l  Sort Data Based on Font Color

Add Spire.Xls.jar to your Project

You can download the API's JAR file from this link or install using the following Maven configurations.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.xls</artifactId>
<version>3.12.3</version>
</dependency>
</dependencies>

Using the code

Sort Data Based on Cell Values

import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.sorting.SortColumn;

public class CellValues {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Create a sort column with the column index, the sort based on and order by attributes
SortColumn column = workbook.getDataSorter().getSortColumns().add(0, SortComparsionType.Values, OrderBy.Descending);

//Sort specified cell range
workbook.getDataSorter().sort(sheet.getCellRange("A1:A9"));

//Save the result file
workbook.saveToFile("output/SortByValues.xlsx", ExcelVersion.Version2013);
}
}


Sort Data Based on Cell Colors

import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.sorting.SortColumn;
import java.awt.*;

public class CellColors {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Create a sort column with the column index, the sort based on and order by attributes
SortColumn column = workbook.getDataSorter().getSortColumns().add(0, SortComparsionType.BackgroundColor, OrderBy.Top);

//Specify the color to sort the data
column.setColor(Color.yellow);

//Sort specified cell range
workbook.getDataSorter().sort(sheet.getCellRange("A1:A9"));

//Save the result file
workbook.saveToFile("output/SortByCellColor.xlsx", ExcelVersion.Version2013);
}
}

Sort Data Based on Font Colors
import com.spire.xls.*;
import com.spire.xls.core.spreadsheet.sorting.SortColumn;
import java.awt.*;

public class FontColors {
public static void main(String[] args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load the Excel file
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);

//Create a sort column with the column index, the sort based on and order by attributes
SortColumn column = workbook.getDataSorter().getSortColumns().add(0, SortComparsionType.FontColor, OrderBy.Bottom);
//Specify the color to sort the data
column.setColor(Color.red);

//Sort specified cell range
workbook.getDataSorter().sort(sheet.getCellRange("A1:A9"));

//Save the result file
workbook.saveToFile("output/SortByFontColor.xlsx", ExcelVersion.Version2013);
}
}


Monday, 14 December 2020

Create and Manipulate a Table in PowerPoint in Java

A PowerPoint slideshow is a type of document that is mean to be shown to audiences to convey a piece of information among which data and graphics are very important. Creating tables is the simplest way to show those data and graphics without wasting any time or work in vain.

The tutorial in this article will show you how to create a table in your presentation and then manipulate it according to your requirements. It’s worth mentioning that I will do these actions in Java program using a free API called FreeSpire.Presentation for Java without installing Microsoft PowerPoint or any other component.

IMPORT SPIRE.PRESENTATION.JAR IN YOUR IDEA

Before typing codes, you need to create a test environment. In addition to JDK and Intellij IDEA, Spire.Presentation.jar located at Free Spire.Presentation for Java should be imported in your IDEA. There are two methods as follows to do it.

Method 1. Download the jar file from here to your local disk, and add it as a dependency in your project.

Method 2. If you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

CREATE A TABLE

import com.spire.presentation.*;

public class CreateTable {
public static void main(String[] args) throws Exception {
//create a Presentation instance
Presentation presentation = new Presentation();
presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);

//define column widths and row heights
Double[] widths = new Double[]{100d, 100d, 150d, 140d, 120d};
Double[] heights = new Double[]{15d, 15d, 15d, 15d,15d};

//add a table
ITable table = presentation.getSlides().get(0).getShapes().appendTable((float)(presentation.
getSlideSize().getSize().getWidth() - 650)/2, 40, widths, heights);

//define data
String[][] data = new String[][]
{
{"Name", "Capital", "Continent", "Area", "Population"},
{"Indonesia", "Jakarta", "Southeast Asia", "1913578.68", "262000000"},
{"Bangladesh", "Dhaka", "South Aisa", "147570", "164700000"},
{"Mexican", "Mexico City", "North America", "1964375", "123000000"},
{"China", "Beijing", "East Asia", "9600000", "1400500000"},
};

for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {

//fill the table with data
table.get(j, i).getTextFrame().setText(data[i][j]);

//align text in each cell to center
table.get(j, i).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
}
}
//apply built-in table style
table.setStylePreset(TableStylePreset.LIGHT_STYLE_3_ACCENT_2);
//save the document
presentation.saveToFile("output/InsertTable.pptx", FileFormat.PPTX_2013);
}
}

Output


MANIPULATE A TABLE

1. Access an existing table

//load a PowerPoint file containing table
Presentation presentation = new Presentation();
presentation.loadFromFile("Table.pptx");

//get the table from the specified slide
ITable table = null;
for (Object shape: presentation.getSlides().get(0).getShapes()
) {
if (shape instanceof ITable){
table = (ITable)shape;
}
}
2. Add a row or a column
//add a row by duplicating the last row
table.getTableRows().append(table.getTableRows().get(table.getTableRows().getCount()-1));
//obtain the new row added
TableRow lastRow = table.getTableRows().get(table.getTableRows().getCount()-1);
//add a column by duplicating the last column
table.getColumnsList().add(table.getColumnsList().get(table.getColumnsList().getCount()-1));
//obtain the new column added
TableColumn lastColumn = table.getColumnsList().get(table.getColumnsList().getCount()-1);
3. Insert a specific row or column to the specified position
table.getTableRows().insert(0, table.getTableRows().get(0));
table.getColumnsList().insert(0, table.getColumnsList().get(0));
4. Delete a row or a column
table.getTableRows().removeAt(0, false);
table.getColumnsList().removeAt(0, false);
5. Merge cells
table.mergeCells(table.get(0,0), table.get(0,1), false);
6. Split a cell
table.get(0,0).Split(3,2);
7. Set the row height or column width
table.getTableRows().get(0).setHeight(50);
table.getColumnsList().get(0).setWidth(100);
8. Fill a cell with picture
table.get(0,0).getFillFormat().setFillType(FillFormatType.PICTURE);
table.get(0,0).getFillFormat().getPictureFill().getPicture().setUrl((new java.io.File("bkg.jpg")).getAbsolutePath());
9. Fill a cell with solid color
table.get(0,1).getFillFormat().setFillType(FillFormatType.SOLID);
table.get(0,1).getFillFormat().getSolidColor().setColor(Color.blue);
10. Set border color
table.setTableBorder(TableBorderType.All, 1, Color.black);
11. Set the text color
table.get(0,0).getTextFrame().getParagraphs().get(0).getTextRanges().get(0).getFill().setFillType(FillFormatType.SOLID);
table.get(0,0).getTextFrame().getParagraphs().get(0).getTextRanges().get(0).getFill().getSolidColor().setColor(color.red);
12. Set the text alignment within a cell
table.get(0,0).getTextFrame().getParagraphs().get(0).setAlignment(TextAlignmentType.CENTER);
13. Set the font name and font size of text in a cell
table.get(0,0).getTextFrame().getParagraphs().get(0).getTextRanges().get(0).setLatinFont(new TextFont("Calibri"));
table.get(0,0).getTextFrame().getParagraphs().get(0).getTextRanges().get(0).setFontHeight(20f);


Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...