Passing a list of servlet values - java

Using apache poi, I am reading the first row values of an excel file like this
try
{
FileInputStream file = new FileInputStream(uploadedFile);
XSSFWorkbook workbook = new XSSFWorkbook(file);
for (int i =0; i < workbook.getNumberOfSheets(); i++)
{
XSSFSheet sheet = workbook.getSheetAt(i);
Iterator<Row> rowIterator = sheet.iterator();
String SheetName = "<span class='blue'><b>" +sheet.getSheetName()+ "<b></span><br>";
request.setAttribute("SheetName", SheetName);
Row row = rowIterator.next();
if(row.getRowNum() == 0)
{
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
request.setAttribute("Values2", strval);
break;
}
}
}
}
file.close();
}catch(NoSuchElementException e)
{}
Now, I want to pass a list of values the strval is only sending one value, how do I sent many values??
How to send an array of items to my jsp page?

You can send List as an attribute value. For example:
List<String> cellValues = new ArrayList<String>();
while(cellIterator.hasNext())
{
Cell cell1 = cellIterator.next();
switch(cell1.getCellType())
{
case Cell.CELL_TYPE_STRING:
String strval = cell1.getStringCellValue();
cellValues.add(strval);
break;
}
}
}
}
request.settAttribute("Values2", cellValues);

Related

How to use excel column header as key in java using Apache-poi?

I want to use my column header of excel as key, so that I can print specific data column wise using that key. Below is my code in which I have used row as key, but could not do it column wise:
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet("Bill");
Iterator<Row> rowIterator = sheet.iterator();
HashMap<Integer,List<String>> m= new HashMap<>();
int rownum=0;
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> lst=new LinkedList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
int a=(int) cell.getNumericCellValue();
lst.add(Integer.toString(a));
break;
case Cell.CELL_TYPE_STRING:
lst.add(cell.getStringCellValue());
break;
}
}
m.put(rownum,lst);
rownum++;
}
for (int i:m.keySet())
{
System.out.println(i+"-----"+m.get(i));
}
read the excel like code below. put the first column into the map with key "columns" after reading excel, fetch the column list with
List columns = (List) dataList.get(0).get("columns");
public List<HashMap<String, Object>> readExcel(InputStream inputStream, String dateFormat) {
ArrayList<HashMap<String, Object>> result = new ArrayList<HashMap<String, Object>>();
try {
XSSFWorkbook workbook;
workbook = new XSSFWorkbook(inputStream);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = spreadsheet.iterator();
int c = 0;
ArrayList<String> columns = new ArrayList<String>();
while (rowIterator.hasNext()) {
row = (XSSFRow) rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
HashMap<String, Object> map = new HashMap<String, Object>();
if (c == 0) {
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if (cell.getStringCellValue().trim() != null && !cell.getStringCellValue().trim().equals("")) {
columns.add(cell.getStringCellValue().trim());
}
}
} else {
for (int i = 0; i < columns.size(); i++) {
Cell cell = row.getCell(i);
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellInternalDateFormatted(cell)) {
DateFormat df = new SimpleDateFormat(dateFormat);
map.put(columns.get(i), df.format(cell.getDateCellValue()));
break;
} else {
map.put(columns.get(i), cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_STRING:
map.put(columns.get(i), cell.getStringCellValue().trim());
break;
}
} else {
map.put(columns.get(i), "");
}
}
}
if (c == 0) {
map.put("columns", columns);
}
c++;
if (!isEmptyRow(map)) {
map.put("rowNumber", c);
result.add(map);
}
}
inputStream.close();
return result;
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Read Excel file and write in other excel at specific sheet using POI

I am reading an Excel file and writing the content into an already existing file based on sheet name. The Excel file has 3 header columns.
XSSFSheet conSheet = workbook.getSheet("EMPLOYYEE");
XSSFRow headerRow = conSheet.getRow(0);
XSSFRow dataRow = conSheet.createRow(conSheet.getLastRowNum() + 1);
int physicalNumberOfCells = headerRow.getPhysicalNumberOfCells();
for (int i = 0; i < physicalNumberOfCells; i++) {
XSSFCell headerCell = headerRow.getCell(i);
if (headerCell != null) {
String stringCellValue = headerCell.getStringCellValue();
ConvertsColumn charcol = ConvertsColumn.getEnum(stringCellValue);
XSSFCell dataCell = dataRow.createCell(i);
if (charcol != null) {
try {
FileInputStream file = new FileInputStream("file..anme");
Workbook wb1 = new XSSFWorkbook(file);
Sheet sheet1 = wb1.getSheetAt(0);
Iterator < Row > iterator = sheet1.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator < Cell > cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell nextCell = cellIterator.next();
int columnIndex = nextCell.getColumnIndex();
System.out.println(columnIndex + "" + nextCell);
switch (columnIndex) {
case 0:
dataCell.setCellValue(nextCell.getStringCellValue());
break;
case 1:
dataCell.setCellValue(nextCell.getStringCellValue());
break;
case 2:
dataCell.setCellValue(nextCell.getStringCellValue());
break;
default:
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
We are Using POI. When data is writing to the Excel file it is over-writen with the first column and only one column data is adding with one value...

How to open xlsx files stored in a folder one by one and copy data to another file using JAVA

I wants to open xlsx files stored in a folder (one by one) and copy that sheet data column by column (if column name matches) to another file stored in other folder.
Column name mapping data is stored in a sheet.
Suppose sheet 1 contains column name mapping. using this mapping, I want to copy data of each column from each sheet stored in a particular folder to another file stored in another folder.
I tried with this code given below, but I am able to read and write compare headers, but I am unable to read from file one by one.
Code:
public class Read {
public static void main(String[] args) throws IOException{
//Create blank workbook
HSSFWorkbook workbook1 = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook1.createSheet(" Info ");
//Create row object
// HSSFRow row1;
ArrayList<String> lst = new ArrayList<String>();
Read read = new Read();
String x ="Name";
//int columnIndex = 0;
lst = read.extractExcelContentByColumnIndex(x);
//int rowid = 0;
//row1 = spreadsheet.createRow(rowid++);
//Object [] objectArr = empinfo.get(key);
//int cellid = 0;
//int i=0;
for(int RowNum=0; RowNum<lst.size();RowNum++){
HSSFRow row1 = spreadsheet.createRow(RowNum);
for(int ColNum=0; ColNum<1;ColNum++){
HSSFCell cell = row1.createCell(ColNum);
cell.setCellValue(lst.get(RowNum).toString());
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("Writesheet.xls"));
// System.out.println(lst);
workbook1.write(out);
out.close();
}
public ArrayList<String> extractExcelContentByColumnIndex( String colName)
{
ArrayList<String> columndata = null;
int columnIndex= 0;
int flag=0;
try {
File f = new File("abc.xlsx");
FileInputStream ios = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(ios);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
columndata = new ArrayList<String>();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell1 = cellIterator.next();
String temp=cell1.getStringCellValue().toString();
//System.out.println(temp);
if(temp.equals(colName)){
columnIndex=cell1.getColumnIndex();
flag=1;
break;
}
}
if(flag==1)
{
flag = 0;
break;
}
}
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// System.out.println(row.getRowNum());
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(row.getRowNum() > 0){
//To filter column headings
if(cell.getColumnIndex() == columnIndex){
// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
columndata.add(cell.getNumericCellValue()+"");
break;
case Cell.CELL_TYPE_STRING:
columndata.add(cell.getStringCellValue());
break;
}
}
}
}
}
ios.close();
System.out.println(colName);
for(String ele : columndata){
System.out.println(ele);
}
} catch (Exception e) {
e.printStackTrace();
}
return columndata;
}
}
For reading files one by one you can use java.io.File.listFiles() method.
The method returns the array of abstract pathnames defining the
files in the directory denoted by this abstract pathname.
Sample code
File folder = new File(path / up / to / folder);
File[] listOfFiles = folder.listFiles();
for (File file: listOfFiles) {
if (file.isFile() && file.getName().contains(".xlsx")) {
// if you want to read only xlsx files
// Your logic
}
}

java excel read one column

I have a column (B) that I need to take all the values between B3 and B20
this is my code
try {
OPCPackage fs;
fs = OPCPackage.open(new File(getFilePath()));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheet("Master column name - Used Car");
XSSFRow row;
CellReference cr = new CellReference("B3");
row = sheet.getRow(4);
System.out.println(row);
but as you see, i am getting one value, i didn't know how to get the values for cells B3 until B20
could you help please
have you tried replacing this line:
CellReference cr = new CellReference("B3");
with:
AreaReference ar = new AreaReference("B3:B20");
i.e.
AreaReference ar = new AreaReference("B3:B20");
for (cr : ar.getAllReferencedCells()) {
System.out.print(cr.formatAsString());
System.out.print(" - ");
}
System.out.println();
To read values of certain column or cell from excel you might try this
public static void readFromExcel2(){
try{
FileInputStream file = new FileInputStream(new File("java_excel.xlsx"));//place path of your excel file
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(1);//which sheet you want to read
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()){
Cell cell = cellIterator.next();
if(cell.getColumnIndex()<2&&(cell.getRowIndex()>=3&&cell.getRowIndex()<=20)) {
{
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int) cell.getNumericCellValue()+" \t" );
break;
case Cell.CELL_TYPE_BLANK:
System.out.print(" ");
break;
case Cell.CELL_TYPE_STRING: {
System.out.print(cell.getStringCellValue());
}
}
}
}
}
System.out.println(" ");
}
file.close();
}catch (Exception e){
e.printStackTrace();
}
}
}

Apache POI find last cell in row

I have the following code that reads a spreadsheet and writes to pipe-delimeted file. Rows have differing length. The last cell shouldn't get appended with a pipe character (but does). I tried things like https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getLastCellNum() but cannot make it work.
XSSFWorkbook wb = new XSSFWorkbook(pathandfilename);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
XSSFSheet sheet = wb.getSheetAt(i);
String outfilename = path + "\\" + prefix + sheetname + postfix;
PrintWriter outfilewriter = new PrintWriter(outfilename, "UTF-8");
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
outfilewriter.print(cell.getStringCellValue() + "|");
}
outfilewriter.print("\n");
}
outfilewriter.close();
}
wb.close();
I fixed it as such:
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> recordArry = new ArrayList<String>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellType(Cell.CELL_TYPE_STRING);
recordArry.add(cell.getStringCellValue() + "|");
}
StringBuilder recordString = new StringBuilder();
for (String elem : recordArry) {
recordString.append(elem);
}
String recordString2 = StringUtils.chomp(recordString.toString(), "|");
outfilewriter.print(recordString2);
outfilewriter.print("\n");
}

Categories