Skip to main content

Copy Data From One Excel To Another Using Apache POI


In case there is a requirement where you need to copy the data from one excel file into another excel using test automation, we can use Apache POI open-source library to do that.


Here's the self-explanatory code but do let me know if you have any queries.

For other details, you can go through https://www.javatpoint.com/apache-poi-tutorial

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;

public class CopyExcel {

@Test
public static void CopyOneWBookToOther() throws IOException {

// Step #1 : Locate path and file name of target and output excel.
String TargetSheetPathAndName = "/Users/dheerajgambhir/Desktop/OrgSheet.xlsx";
String NewSheetPathAndName = "/Users/dheerajgambhir/Documents/NewSheet.xlsx";

if (TargetSheetPathAndName != null && !"".equals(TargetSheetPathAndName.trim())) {

try {
File targetFile = new File(TargetSheetPathAndName.trim());
FileInputStream inputStream = new FileInputStream(targetFile);
XSSFWorkbook inputWorkbook = new XSSFWorkbook(inputStream);
int targetSheetCount = inputWorkbook.getNumberOfSheets();
System.out.println("Total no. of sheet(s) in the Target Workbook: " + targetSheetCount);

File outputFile = new File(NewSheetPathAndName.trim());
FileOutputStream outputStream = new FileOutputStream(outputFile);

XSSFWorkbook outputWorkbook = new XSSFWorkbook();
// Step #2 : Creating sheets with the same name as appearing in target workbook.
for (int i = 0; i < targetSheetCount; i++) {
XSSFSheet targetSheet = inputWorkbook.getSheetAt(i);
String inputSheetName = inputWorkbook.getSheetName(i);
XSSFSheet outputSheet = outputWorkbook.createSheet(inputSheetName);

copyExcelWB(targetSheet, outputSheet);
}
// Step #4 : Write all the sheets in the new Workbook using FileOutStream Object

outputWorkbook.write(outputStream);

outputStream.close();
}

catch (Exception ex) {
System.out.println("Please check the target sheet given path and name: " + TargetSheetPathAndName);
System.out.println();
ex.printStackTrace();
}
}
}

public static void copyExcelWB(XSSFSheet targetSheet, XSSFSheet outputSheet) {
int rowCount = targetSheet.getLastRowNum();

System.out.println("There are " + rowCount + " rows in the Target workbook with sheet name -" + "'"
+ targetSheet.getSheetName() + "'");

int currentRowIndex = 0;
if (rowCount > 0) {
Iterator<Row> rowIterator = targetSheet.iterator();
while (rowIterator.hasNext()) {
int currentCellIndex = 0;
Iterator<Cell> cellIterator = ((Row) rowIterator.next()).cellIterator();
while (cellIterator.hasNext()) {
// Step #3: 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++;
}
currentRowIndex++;
}
System.out.println("Total " + (currentRowIndex - 1) + " rows are Copied in the new Workbook with sheet name- "
+ "'" + outputSheet.getSheetName() + "'");

}
}


}




Comments

Popular posts from this blog

The use of Verbose attribute in testNG or POM.xml (maven-surefire-plugin)

At times, we see some weird behavior in your testNG execution and feel that the information displayed is insufficient and would like to see more details. At other times, the output on the console is too verbose and we may want to only see the errors. This is where a verbose attribute can help you- it is used to define the amount of logging to be performed on the console. The verbosity level is 0 to 10, where 10 is most detailed. Once you set it to 10, you'll see that console output will contain information regarding the tests, methods, and listeners, etc. <suite name="Suite" thread-count="5" verbose="10"> Note* You can specify -1 and this will put TestNG in debug mode. The default level is 0. Alternatively, you can set the verbose level through attribute in "maven-surefire-plugin" in pom.xml, as shown in the image. #testNG #automationTesting #verbose # #testAutomation

How to Unzip files in Selenium (Java)?

1) Using Java (Lengthy way) : Create a utility and use it:>> import java.io.BufferedOutputStream; import org.openqa.selenium.io.Zip; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream;   public class UnzipUtil {     private static final int BUFFER_SIZE = 4096;     public void unzip (String zipFilePath, String destDirectory) throws IOException {         File destDir = new File(destDirectory);         if (!destDir.exists()) {             destDir.mkdir();         }         ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));         ZipEntry entry = zipIn.getNextEntry();         // to iterates over entries in the zip folder         while (en...

Stop Overengineering: Why Test IDs Beat AI-Powered Locator Intelligence for UI Automation

  We have all read the blogs. We have all seen the charts showing how Generative AI can "revolutionize" test automation by magically resolving locators, self-healing broken selectors, and interpreting UI changes on the fly. There are many articles that paints a compelling picture of a future where tests maintain themselves. Cool story. But let’s take a step back. Why are we bending over backward to make tests smart enough to deal with ever-changing DOMs when there's a simpler, far more sustainable answer staring us in the face? -             Just use Test IDs. That’s it. That’s the post. But since blogs are supposed to be more than one sentence, let’s unpack this a bit. 1. Test IDs Never Lie (or Change) Good automation is about reliability and stability. Test IDs—like data-testid ="submit-button"—are predictable. They don’t break when a developer changes the CSS class, updates the layout, or renames an element. You know...