Java: Create a Drop-Down List in Excel
The drop-down list in Excel enables users to select a desired item from a pre-defined list of items as input data. It restricts the input of unwanted or ambiguous data and reduces the occurrence of spelling errors, which is a great option for speeding up data entry tasks. In this article, you will learn how to programmatically create a drop-down list in Excel using Spire.XLS for Java.
- Create a Drop-Down List Based on Values in a Cell Range
- Create a Drop-Down List Based on Values in a String Array
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Create a Drop-Down List Based on Values in a Cell Range
With Spire.XLS for Java, you can add values to a range of cells and then refer to that range of cells as the data validation source to create a drop-down list. This method might be slightly time-consuming, but it allows you to easily update the items in the drop-down list by directly modifying the values in the cells of the result document. The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Get a specified cell or cell range using Worksheet.getCellRange() method.
- Add values to specified cells using CellRange.setValue() method.
- Get data validation of the specified cell range using CellRange.getDataValidation() method.
- Create a drop-down list by referring to a specified data range as the data validation source using Validation.setDataRange() method.
- Save the result document using Workbook.saveToFile() method.
- Java
import com.spire.xls.*; public class DropdownList { public static void main(String[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Load a sample Excel document workbook.loadFromFile("input.xlsx"); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Add values to specified cells sheet.getCellRange("A13").setValue("Complete"); sheet.getCellRange("A14").setValue("Pending"); sheet.getCellRange("A15").setValue("Cancelled"); //Create a drop-down list by referring to a specified data range as the data validation source sheet.getCellRange("C2:C7").getDataValidation().setDataRange(sheet.getCellRange("A13:A15")); //Save the result document workbook.saveToFile("ExcelDropdownList.xlsx", ExcelVersion.Version2013); } }
Create a Drop-Down List Based on Values in a String Array
In Excel, you can create a drop-down list by manually entering a list of values in the “Source” box of the Data Validation menu. By doing this, you don't need to add data in Excel cells, which keeps your Excel document neat and organized. The following steps shows how to use Spire.XLS for Java to achieve the same functionality.
- Create a Workbook object.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Add text to a cell and set its font style.
- Get a specified cell or cell range using Worksheet.getCellRange() method.
- Get data validation of the specified cell range using CellRange.getDataValidation() method.
- Set the values of the drop-down list using Validation.setValues() method.
- Create a drop-down list in the specified cell by setting the values of Validation.isSuppressDropDownArrow() method to false.
- Save the result document using Workbook.saveToFile() method.
- Java
import com.spire.xls.*; public class DropdownList2 { public static void main(String[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Add text to cell B2 and set its font style sheet.getCellRange("B2").setValue("Country"); sheet.getCellRange("B2").getStyle().getFont().isBold(true); sheet.getCellRange("B2").getStyle().setKnownColor(ExcelColors.LightTurquoise); //Set the values of the drop-down list sheet.getCellRange("C2").getDataValidation().setValues(new String[]{"France", "Japan", "Canada", "China", "Germany"}); //Create a drop-down list in the specified cell sheet.getCellRange("C2").getDataValidation().isSuppressDropDownArrow(false); //Save the result document workbook.saveToFile("ExcelDropdownList2.xlsx", ExcelVersion.Version2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: AutoFit Column Width and Row Height in Excel
AutoFit is a very practical feature MS Excel offers to automatically resize cells to accommodate different sized data. With a single click, it makes all the data in a cell clearly visible without having to manually adjust the column width or row height. In this article, you will learn how to programmatically AutoFit the column width and row height in an Excel worksheet using Spire.XLS for Java.
Install Spire.XLS for Java
First, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
AutoFit Column Width and Row Height in Excel
The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Get the used range on the specified worksheet using Worksheet.getAllocatedRange() method.
- Autofit column width and row height in the range using CellRange.autoFitColumns() and CellRange.autoFitRows() methods.
- Save the document to another file using Workbook.saveToFile() method.
- Java
import com.spire.xls.*; public class AutoFitColumn { public static void main(String[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Load a sample Excel document workbook.loadFromFile("E:\\Files\\Test.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //AutoFit column width and row height worksheet.getAllocatedRange().autoFitColumns(); worksheet.getAllocatedRange().autoFitRows(); //Save the document workbook.saveToFile("AutoFitCell.xlsx", ExcelVersion.Version2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Set Background Color and Pattern for Excel Cells
When working with an Excel document that contains a lot of data, setting color or pattern for selected cells can make it very easy for users to locate specific types of information. In Microsoft Excel, you can achieve this function by simply clicking the "Fill Color" button on the formatting toolbar. In this article, you will learn how to programmatically set background color and pattern style for a specified cell or cell range in Excel using Spire.XLS for Java.
Install Spire.XLS for Java
First, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Set Background Color and Pattern for Excel Cells
The detailed steps are as follows.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Get a specified cell range using Worksheet.getRange().get() method.
- Set background color for the specified cell range using CellRange.getStyle().setColor() method.
- Set fill pattern style for the specified cell range using CellRange.getStyle().setFillPattern() method.
- Save the result to another file using Workbook.saveToFile() method.
- Java
import com.spire.xls.*; import java.awt.*; public class CellBackground { public static void main(String[] args) { //Create a Workbook object Workbook workbook = new Workbook(); //Load a sample Excel document workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\data.xlsx"); //Get the first worksheet Worksheet worksheet= workbook.getWorksheets().get(0); //Set background color for range "A1:E1" and "A2:A10" worksheet.getRange().get("A1:E1").getStyle().setColor(Color.green); worksheet.getRange().get("A2:A10").getStyle().setColor(Color.yellow); //Set background color for cell E8 worksheet.getRange().get("E8").getStyle().setColor(Color.red); //Set fill pattern style for range "C4:D5" worksheet.getRange().get("C4:D5").getStyle().setFillPattern(ExcelPatternType.Percent25Gray); //Save the document workbook.saveToFile("CellBackground.xlsx", ExcelVersion.Version2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Hide or Show Rows or Columns in Excel
Sometimes we need to hide some rows and columns in Excel worksheets so that the data appears completely on one screen. At other times, we need to show all the hidden rows and columns to view the data completely. In this article, you will learn how to hide and show rows or columns in Excel in Java applications from the following four parts.
- Hide Excel Rows and Columns
- Show Hidden Rows and Columns in Excel
- Hide Multiple Rows and Columns
- Show All Hidden Rows and Columns
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Hide Rows and Columns
The detailed steps are listed as below.
- Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Hide a specific column using Worksheet.hideColumn(int columnIndex)method.
- Hide a specific row using Worksheet.hideRow(int rowIndex) method.
- Save the document to file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class HideRowsColumns { public static void main(String[] args) throws Exception { //Load the sample document Workbook wb = new Workbook(); wb.loadFromFile("Sample.xlsx "); //Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); //Hide the third column sheet.hideColumn(3); //Hide the third row sheet.hideRow(3); //Save the document wb.saveToFile("HideRowsColumns.xlsx", ExcelVersion.Version2016); } }
Show Hidden Rows and Columns
- Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Show a hidden column using Worksheet.showColumn(int columnIndex)method.
- Show a hidden row using Worksheet.showRow(int rowIndex) method.
- Save the document to file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ShowRowsColumns { public static void main(String[] args) throws Exception { //Load the sample document Workbook wb = new Workbook(); wb.loadFromFile("HideRowsColumns.xlsx "); //Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); //Unhide the third column sheet.showColumn(3); //Unhide the third row sheet.showRow(3); //Save the document wb.saveToFile("ShowRowsColumns.xlsx", ExcelVersion.Version2016); } }
Hide Multiple Rows and Columns
- Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Hide multiple columns using Worksheet.hideColumns(int columnIndex, int columnCount)method.
- Hide multiple rows using worksheet.hideRows(int rowIndex, int rowCount) method.
- Save the document to file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class HideMultiRowsColumns { public static void main(String[] args) throws Exception { //Load the sample document Workbook wb = new Workbook(); wb.loadFromFile("Sample01.xlsx "); //Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); //Hide multiple columns sheet.hideColumns(2,2); //Hide multiple rows sheet.hideRows(3,3); //Save the document wb.saveToFile("HideMultiRowsColumns.xlsx", ExcelVersion.Version2016); } }
Show Multiple Rows and Columns
- Create a Workbook instance and load a sample Excel document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Loop through the rows and find the hidden rows using Worksheet.getRowIsHide() method.
- Show all hidden rows using Worksheet.showRow(i) method.
- Save the document to file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ShowMultiRowsColumns { public static void main(String[] args) throws Exception { //Load the sample document Workbook wb = new Workbook(); wb.loadFromFile("HideMultiRowsColumns.xlsx"); //Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); //Traverse all the rows for (int i = 1; i <= sheet.getLastRow(); i++) { //detect if the row is hidden if (sheet.getRowIsHide(i)) { //Show the hidden rows sheet.showRow(i); } } //Traverse the columns and show all the hidden columns for (int j = 1; j <= sheet.getLastColumn(); j++) { if (sheet.getColumnIsHide(j)) { sheet.showColumn(j); } //Save the document wb.saveToFile("ShowMultiRowsColumns.xlsx", ExcelVersion.Version2016); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Get the Intersection of Two Cell Ranges in Excel
When working with Excel, you may sometimes need to find the common values between two ranges of cells in a worksheet. For this reason, it’s recommended that Java codes can be used to automatically find the intersection of certain ranges. In this article, you'll learn how to achieve the operation using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Get the Intersection of Two Cell Ranges in Excel
The following are detailed steps to get the intersection of two cell ranges in an Excel worksheet.
- Create a Workbook instance and load a sample Excel file using Workbook.loadFromFile() method.
- Get a specific worksheet of the file using Workbook.getWorksheets().get() method.
- Specify two ranges of cells using Worksheet.getRange().get() method and get their intersection using XlsRange.intersect() method.
- Create a StringBuilder instance.
- Loop through the intersection and obtain cell values using CellRange.getValue() method.
- Append the result to the StringBuilder instance using StringBuilder.append() method.
- Java
import com.spire.xls.*; public class getIntersectionOfTwoRanges { public static void main(String[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load a sample Excel file workbook.loadFromFile( "C:\\Users\\Test1\\Desktop\\sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Specify two cell ranges and get their intersection CellRange range = sheet.getRange().get("B2:E7").intersect(sheet.getRange().get("C3:D7")); //Create a StringBuilder instance StringBuilder content = new StringBuilder(); content.append("The intersection of the two ranges \"B2:E7\" and \"C3:D7\" is:"+"\n"); //Loop through the intersection and obtain cell values for(CellRange r : range.getCellList()) { content.append(r.getValue()+"\n"); } //Output the result System.out.println(content); } }
The input Excel:
The output result:
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Get Cell Values by Cell Names in Excel
To extract values from an Excel document, you can copy and paste cell data. Alternatively, you can obtain it automatically by utilizing Java code, which will not only save time and improve efficiency, but ensure there will be no errors. In this tutorial, you will learn how to extract the value of a specified cell by its name using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Get Cell Values by Cell Names in Excel
Spire.XLS for Java offers Worksheet.getRange().get() method to specify a cell in Excel by its name, and CellRange.getValue() method to obtain the cell value. The detailed steps are listed as below.
- Create a Workbook instance.
- Load an Excel sample document using Workbook.loadFromFile() method.
- Get a specified worksheet using Workbook.getWorksheets().get() method.
- Get a specific cell by its name using Worksheet.getRange().get() method.
- Create a StringBulider instance.
- Obtain the cell value using CellRange.getValue() method, and then append the value to the StringBuilder instance using StringBuilder.append() method.
- Java
import com.spire.xls.*; public class GetCellValue { public static void main(String[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel sample document workbook.loadFromFile( "C:\\Users\\Test1\\Desktop\\sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Get the specified cell by its name CellRange cell = sheet.getRange().get("D6"); //Create a StringBuilder instance StringBuilder content = new StringBuilder(); //Get value of the cell "D6" content.append("The value of cell D6 is: " + cell.getValue()+"\n"); //Output the result System.out.println(content); } }
The input Excel:
The output result:
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Shrink Text to Fit in a Cell in Excel in Java
Spire.XLS for Java provides you with the ability to shrink text to fit in a cell by using the setShrinkToFit method of the CellStyleObject class. The setShrinkToFit method accepts the following parameter:
boolean: specify whether to shrink text to fit in a cell.
The following example shows how to shrink text to fit in a cell in Excel using Spire.XLS for Java.
import com.spire.xls.*; public class ShrinkTextToFitInACell { public static void main(String []args) throws Exception { //Create a workbook instance Workbook workbook = new Workbook(); //Load the Excel file workbook.loadFromFile("Sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Get the cell range to shrink text CellRange cell = sheet.getRange().get("B2:B3"); //Enable “shrink to fit” cell.getCellStyle().setShrinkToFit(true); //Save the file workbook.saveToFile("ShrinkTextToFitInACell.xlsx", ExcelVersion.Version2013); } }
The input Excel:
The output Excel:
Java: Wrap or Unwrap Text in Excel Cells
In the process of manipulating Excel worksheets, sometimes you may encounter the situation where the text in a cell is so long that some of it is hidden. At this time, it’s recommended to wrap the extra-long text into multiple lines so you can see it all. This article will demonstrate how to programmatically wrap or unwrap text in Excel cells using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.11.0</version> </dependency> </dependencies>
Wrap or Unwrap Text in Excel cells
Spire.XLS for Java supports wrapping or unwrapping text in Excel cells using the setWrapText() method provided by the IStyle interface. Below are detailed steps for your reference.
- Create a Workbook instance.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Get a specific worksheet of the document using Workbook.getWorksheets().get() method.
- Get a specific cell of the worksheet using Worksheet.getRange().get() method.
- Get the style of the specified cell using XlsRange.getStyle() method and set whether the text is wrapped or not using setWrapText() method provided by IStyle interface.
- Save the document to another file using Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class WrapOrUnwrapText { public static void main(String[] args) { //Create a Workbook instance Workbook workbook = new Workbook(); //Load a sample Excel document workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.xlsx"); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Wrap text in the cell "D8" sheet.getRange().get("D8").getStyle().setWrapText(true); //Unwrap text in the cell "D6" sheet.getRange().get("D6").getStyle().setWrapText(false); //Save the document to another file workbook.saveToFile("output/WrapOrUnwrapText.xlsx", ExcelVersion.Version2013); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Detect Merged Cells in an Excel Worksheet in Java
This article demonstrates how to detect merged cells in an Excel worksheet and unmerge the merged cells using Spire.XLS for Java.
The input Excel file:
import com.spire.xls.CellRange; import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class DetectMergedCells { public static void main(String[] args) throws Exception { //Create a Workbook instance Workbook workbook = new Workbook(); //Load the Excel file workbook.loadFromFile( "Input.xlsx"); //Get the first worksheet Worksheet sheet = workbook.getWorksheets().get(0); //Get the merged cell ranges in the first worksheet and put them into a CellRange array CellRange[] range = sheet.getMergedCells(); //Traverse through the array and unmerge the merged cells for(CellRange cell : range){ cell.unMerge(); } //Save the result file workbook.saveToFile("DetectMergedCells.xlsx", ExcelVersion.Version2013); } }
The output Excel file:
Appy Multiple Fonts in One Cell in Java
This article demonstrates how to apply multiple font styles in a single Excel cell using Spire.XLS for Java.
import com.spire.xls.*; import java.awt.*; public class ApplyMultiFontsInCell { public static void main(String[] args) { //Create a Workbook instance Workbook wb = new Workbook(); //Get the first worksheet Worksheet sheet = wb.getWorksheets().get(0); //Create one Excel font ExcelFont font1 = wb.createFont(); font1.setFontName("Calibri"); font1.setColor(Color.blue); font1.setSize(12f); font1.isBold(true); //Create another Excel font ExcelFont font2 = wb.createFont(); font2.setFontName("Times New Roman"); font2.setColor(Color.red); font2.setSize(14f); font2.isBold(true); font2.isItalic(true); //Insert text to cell B5 RichText richText = sheet.getCellRange("B5").getRichText(); richText.setText("This document was created with Spire.XLS for Java."); //Apply two fonts to the text in the cell B5 richText.setFont(0, 30, font1); richText.setFont(31, 50, font2); //Save the document wb.saveToFile("MultiFonts.xlsx", ExcelVersion.Version2016); } }