Copying of two different excel sheets to one sheet using Java - java

Copying of two different excel sheets to one new excel sheet using Java code is resulting in partial output.
This is for Java code running in IntelliJ, using Apache POI.
public static void copySheet(XSSFSheet inputSheet1, XSSFSheet outputSheet, XSSFSheet inputSheet2)
{
int rowCount = inputSheet1.getLastRowNum();
int rc = inputSheet2.getLastRowNum(),rcnt=0,cri =0,l=0;
int currentRowIndex = 0, cell = 0;
if (rowCount > 0) {
Iterator rowIterator = inputSheet1.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex = 0;
Iterator cellIterator;
Row row = (Row) rowIterator.next();
cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
//Creating new Row, Cell and Input value in the newly created sheet.
String cellData = cellIterator.next().toString();
if (currentCellIndex == 0)
outputSheet.createRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
else
outputSheet.getRow(currentRowIndex).createCell(currentCellIndex).setCellValue(cellData);
currentCellIndex++;
System.out.println("content test2 " + cellData);
System.out.println("current row index " + currentRowIndex);
System.out.println("current cell " + cell);
}
currentRowIndex++;
cell = currentCellIndex;
rcnt = cell;
}
}
cri = 0;
if (rc > 0) {
Iterator rowIterator = inputSheet2.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex2 = 0,cci = rcnt+1;
Iterator cellIterator2;
Row row = (Row) rowIterator.next();
cellIterator2 = row.cellIterator();
while (cellIterator2.hasNext()) {
String cellData = cellIterator2.next().toString();
if (currentCellIndex2 == 0)
outputSheet.createRow(cri).createCell(cci).setCellValue(cellData);
else
outputSheet.getRow(cri).createCell(cci).setCellValue(cellData);
currentCellIndex2 = currentCellIndex2+1;
cci = cci +1;
System.out.println("content "+cellData);
System.out.println("current row index " + cri);
}
cri++;
}
}
}
Expected output :
both the sheets should be copied to the new sheet.
Actual output :
only the second input sheet is copied to the new sheet.
If I try to copy one the first sheet it will be copied. But if I try to copy both only second sheet will be present.
Input_one
Input_two
Output

It looks like you are overwriting output of the first while loop with the output of the second because in one you use currentRowIndex and in the second you use cri. Reuse the currentRowIndex for the second while-loop as well, so that the rows from the second sheet get appended after the ones for the first one.

Related

How to get cell value from the cell which consists of formula in excel xls file

I am writing java code to read excel file and to create an object from that but one column consists of formula when I read cell formula is coming in value field instead of value
I tried to get from cell index
I tried to get value from iterator(hasnext()) method :
like:
public static void CheckDuplicate(File file) throws Exception {
Set newReordsList = new LinkedHashSet();
LinkedHashMap<String, DataCleansingObject> lhm = new LinkedHashMap<String, DataCleansingObject>();
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
HSSFRow row;
Iterator< Row> rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
row = (HSSFRow) rowIterator.next();
if(row.getRowNum() == 0) {
continue;
}
DataCleansingObject dataObj = new DataCleansingObject();
Iterator< Cell> cellIterator = row.cellIterator();
String key = "";
if (cellIterator.hasNext()) {
dataObj.setDocType(row.getCell(1).toString());
dataObj.setDocNo(row.getCell(2).toString());
dataObj.setDocVer(Long.parseLong(row.getCell(3).toString()));
dataObj.setDocPart(row.getCell(4).toString());
dataObj.setDocLang(row.getCell(5).toString());
dataObj.setDocRev(row.getCell(6).toString());
dataObj.setDocStatus(row.getCell(7).toString());
dataObj.setDocSD(row.getCell(8).toString());
dataObj.setDocLD(row.getCell(9).toString());
dataObj.setDocChangeNumber(row.getCell(10).toString());
key = row.getCell(1).toString() + "_" + row.getCell(2).toString() + "_" + row.getCell(3).toString() + "_" + row.getCell(4).toString();
}
lhm.put(key, dataObj);
}
fis.close();
copyInExcel(newReordsList);
}
When ever I call below line
Long.parseLong(row.getCell(3).toString())
I need to get long value not formula in that cell

How to swap up columns in a xlsx file in apache POI

I am working in a xlsx file , where i have to just append the values in the lower row to the upper row.Also i have to skip that row from the output file.First i am giving the excel file screen
I have to append the values below the row Name6 i.e in the header there will be Name1,Name2,Name3....... Name6admin|Name6loc, Name7.
For now the since the cells are merged cell poi is giving the output as Part of a merged cell after Name6.i.e Name6|part of a merged cell that way .I want to modify that as i mentioned.
Now my code is working like I will have All the rows starting from Name1 to Name7 and all the below values they hold.And the thing is i am generating the output in a text file which can not contain the row below Name1,Name2,...etc.But i also have to append values from that . I am givinf my code
#Override
public List<String> processSheet(Sheet sheet) {
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " started");
List<String> rows = new ArrayList<String>();
Iterator<Row> rowIterator = sheet.iterator();
final int startCell=0;
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
StringBuilder row = new StringBuilder();
for (int i = 0; i < currentRow.getLastCellNum(); i++) {
//skipping the rows which i can not contains in the output
if(currentRow.getRowNum()==0 || currentRow.getRowNum()==1|| currentRow.getRowNum()==2|| currentRow.getRowNum()==3|| currentRow.getRowNum()==4|| currentRow.getRowNum()==5|| currentRow.getRowNum()==6|| currentRow.getRowNum()==7|| currentRow.getRowNum()==9|| currentRow.getRowNum()==10|| currentRow.getRowNum()==11) {
continue;
}
//removing the last three rows containing total
if (currentRow.getLastCellNum() < 0 || currentRow.getCell(startCell) == null || "".equals(currentRow.getCell(startCell).getStringCellValue()) || (currentRow.getCell(startCell).getStringCellValue() != null && currentRow.getCell(startCell).getStringCellValue().contains("Total"))) {
continue;
}
else {
Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String cellValue = excelManager.evalCell(currentCell);
if (!cellValue.isEmpty()) {
row.append(cellValue);
}
//adjusting the cell values with the | or BLANK
if(currentCell == null || currentCell.getCellType() == Cell.CELL_TYPE_BLANK) {
row.append("");
}else {
row.append(SEPARATOR);
}
}
}
if (!row.toString().isEmpty()) {
rows.add(row.toString());
}
}
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " completed");
return rows;
}

Reading and Validating Rows with Aspose JAva

I am trying to read and validate a Row with Aspose Cells Java, but I have never used ir before and de documentation is not very clear, it doesn't even show you how to read a Row. Heres what I've done so far:
public static void main(String[] args) {
String dataDir = "C:\\Users\\apoac22836\\Desktop\\";
Workbook wb = new Workbook(dataDir + "Example.xlsm");
Worksheet worksheet = wb.getWorksheets().get("BOM");
int column = 1;
for (int i = 0; i < 40; i++) {
Cell lastCell = worksheet.getCells().endCellInColumn((short) column);
for (int row = 0; row <= lastCell.getRow(); row++) {
Cell cell = worksheet.getCells().get(row, column);
System.out.println(cell.getStringValue());
}
column += 1;
System.out.println("------------------------------------------------");
}
}
I brings the value of the cells by columns.
Well, if you need to efficiently enumerate all the data (non empty values) in a range, rows, cells, you may try to use Range.iterator(), RowCollection.iterator() and Cells.iterator() method to get the iterator for specific range, initialized rows and non empty or initialized cells, see the following sample codes for your reference:
e.g
Sample code:
//Range Iterator.
Workbook book = new Workbook("sample.xlsx");
Worksheet sheet = book.getWorksheets().get(0);
Range range = sheet.getCells().getMaxDisplayRange();//You may also create your desired range (in the worksheet) using, e.g sheet.getCells().createRange("A1", "J11");
Iterator rangeIterator = range.iterator();
while(rangeIterator.hasNext())
{
Cell cell = (Cell)rangeIterator.next();
System.out.println(cell.getName() + " is not empty");
}
//Cells Iterator.
Workbook workbook = new Workbook("Book1.xls");
Worksheet sheet = workbook.getWorksheets().get(0);
Cells cells = sheet.getCells();
//Get the iterator from Cells collection
Iterator cellIterator = cells.iterator();
//Traverse cells in the collection
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
System.out.println(cell.getName() + " " + cell.getValue());
}
//Rows collection Iterator.
String filePath = "c:\\source.xlsx";
Workbook workbook = new Workbook(filePath);
Worksheet worksheet = workbook.getWorksheets().get(0);
RowCollection rows = worksheet.getCells().getRows();
Object obj = rows.iterator().next();
Iterator<Row> rowIterator = worksheet.getCells().getRows().iterator();
while(rowIterator.hasNext())
{
Row r = rowIterator.next();
Iterator<Cell> cellIterator = r.iterator();
while(cellIterator.hasNext())
{
Cell cell= cellIterator.next();
System.out.println(cell.getStringValue());
}
}
Hope, this helps a bit.
I am working as support developer/Evangelist at Aspose.

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
}
}

Get exact last filled row number in an excel file that has is associated with a complex formula using Apache POI

A complex formula is applied to a column till end of the excel sheet.but when I'm retrieving the last row number using Sheet.getLastRowNum()
it is returning last row of the sheet though the excel sheet is having only 10 rows.Is there any way get the exact last filled row in the excel file even if
formula applied to end of the excel sheet?
From http://affy.blogspot.cz/2004/04/poi-optimization-eliminating-trailing.html
Retrieve required formula then use this code. it will remove all those empty rows and then you can get required data with your data retrieving code.
List yourlist = new ArrayList();
String value = null;
FileInputStream inputStreams1 = null;
inputStreams1 = new FileInputStream(FileNameWithPath);
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(inputStreams1);
HSSFSheet sheet = (HSSFSheet) workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
boolean stop = false;
boolean nonBlankRowFound;
short c;
HSSFRow lastRow = null;
HSSFCell cell = null;
HSSFRow FirsttRow = null;
while (stop == false) {
nonBlankRowFound = false;
lastRow = (HSSFRow) sheet.getRow(sheet.getLastRowNum());
for (c = lastRow.getFirstCellNum(); c <= lastRow.getLastCellNum(); c++) {
cell = lastRow.getCell(c);
if (cell != null && lastRow.getCell(c).getCellType() != HSSFCell.CELL_TYPE_BLANK) {
nonBlankRowFound = true;
}
}
if (nonBlankRowFound == true) {
stop = true;
yourlist = yourMethod(FileNameWithPath, sheet); //updated HSSFSheet object which will have 10 rows
/*use this code to remove all those empty rows then use hsheet object. now use this hsheet object will
have only non empty rows(in your case 10 rows)*/
} else {
sheet.removeRow(lastRow);
}
}

Categories