Last active
March 16, 2024 08:57
-
-
Save javapriyan/8c7c8560c97ec296bc938020d6dd4693 to your computer and use it in GitHub Desktop.
Create Excelsheet with dropdown using POI library in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.trustrace; | |
import java.io.File; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.time.Instant; | |
import org.apache.poi.ss.usermodel.Cell; | |
import org.apache.poi.ss.usermodel.DataValidation; | |
import org.apache.poi.ss.usermodel.DataValidationConstraint; | |
import org.apache.poi.ss.usermodel.DataValidationHelper; | |
import org.apache.poi.ss.usermodel.Row; | |
import org.apache.poi.ss.usermodel.Workbook; | |
import org.apache.poi.ss.util.CellRangeAddressList; | |
import org.apache.poi.xssf.usermodel.XSSFDataValidationHelper; | |
import org.apache.poi.xssf.usermodel.XSSFSheet; | |
import org.apache.poi.xssf.usermodel.XSSFWorkbook; | |
public class ExcelGenerator { | |
public static void main(String[] args) throws IOException { | |
//SpringApplication.run(Application.class, args); | |
Workbook wb = new XSSFWorkbook(); | |
XSSFSheet sheet = (XSSFSheet) wb.createSheet("Example"); | |
sheet.setColumnWidth(0, 2); | |
//sheet.setColumnWidth(0, 2); | |
Row headerRow = sheet.createRow(0); | |
for (int i = 0; i < 10; i++) { | |
Cell cell = headerRow.createCell(i); | |
cell.setCellValue("Title" + i); | |
} | |
for (int i = 1; i <= 10; i++) { | |
Row row = sheet.createRow(i); | |
for (int j = 0; j < 10; j++) { | |
Cell cell = row.createCell(j); | |
cell.setCellValue("SELECT"); | |
} | |
} | |
for (int i = 0; i < 10; i++) { | |
sheet.autoSizeColumn(i); | |
} | |
DataValidation dataValidation = null; | |
DataValidationConstraint constraint = null; | |
DataValidationHelper validationHelper = null; | |
validationHelper = new XSSFDataValidationHelper(sheet); | |
CellRangeAddressList addressList = new CellRangeAddressList(1, 11, 0, 9); | |
constraint = validationHelper.createExplicitListConstraint(new String[]{"10", "20", "30"}); | |
dataValidation = validationHelper.createValidation(constraint, addressList); | |
dataValidation.setSuppressDropDownArrow(true); | |
sheet.addValidationData(dataValidation); | |
File file = new File("/home/karthikeyan/repo/tt-service/example" + Instant.now() + ".xlsx"); | |
file.createNewFile(); | |
FileOutputStream outputStream = new FileOutputStream(file, false); | |
wb.write(outputStream); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could you please provide me dropdown event in excel using apache poi?