poi java code to merge cells based on common data - java

I have data in the above format in an excel file , I want to edit it as follows:
I have used the following code :
public void editExcelTemplate() throws FileNotFoundException, IOException
{
InputStream ExcelFileToRead = new FileInputStream("file.xls");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
String cmp = "none";
for(int i=0;i<rows;i++)
{
Row row = sheet.getRow(i);
int col =row.getPhysicalNumberOfCells();
int colIndex = 1;
int v=0;
for(int j=0;j<col;j++)
{
String content = row.getCell(j).getStringCellValue();
if(!(content == cmp) && !(content.equals("none")))
{
if(!(cmp.equals("none")))
{
System.out.println("content: "+content);
System.out.println("cmp: "+cmp);
v= j;
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
if(!( v-colIndex == 0) && v>0)
{
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
sheet.addMergedRegion(new CellRangeAddress(i,i,colIndex-1,v-1));
System.out.println("merged");
}
}
}
if(!(content == cmp))
{
colIndex = v+1;
}
cmp = content;
}
}
FileOutputStream excelOutputStream = new FileOutputStream(
"file.xls");
wb.write(excelOutputStream);
excelOutputStream.close();
}
I endedup getting the following output :
Can anybody help me get an appropriate output ? The main purpose is to merge the cells with common data in the entire proces.

Related

filter a column in excel to specific word using java code

I have an Excel file which needs filtering on a specific column.
String fileName = "filepath";
String cellContent = "Automation";
int rownr = 0;
int colnr = 0; //column from which you need data to store in array list
InputStream input = new FileInputStream(fileName);
XSSFWorkbook wb = new XSSFWorkbook(input);
XSSFSheet sheet = wb.getSheetAt(0);
List filteredCol = new ArrayList();
filteredCol = findRow(sheet, cellContent);
if (filteredCol != null) {
for (Iterator iter = filteredCol.iterator(); iter.hasNext(); ) {
System.out.println(iter.next());
}
}
private static List findRow(HSSFSheet sheet, String cellContent) {
List filter=new ArrayList();
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
//System.out.println("Row numbers are"+row.getRowNum());
int rownumber=row.getRowNum();
//return row.getRowNum();
XSSFRow row1 = sheet.getRow(rownumber);
XSSFCell cell1 = row1.getCell(0);
filter.add(cell1);
}
}
}
}
return filter;
}
I am getting number format exception on this codeline:
"cell.getRichStringCellValue().getString().trim().equals(cellContent)"

Apache POI - Delete and move up Cell

I'm using the Apache POi HSSF library to import and export an Excel table to my application (tableview). I want to delete from Java a Row in Excel with a specific ID. It works. My Problem is, after i delete a row there are a empty row and it delete more than the selected row. Could everybody help?
FileInputStream inp = new FileInputStream(
"...............";
HSSFWorkbook wb = (HSSFWorkbook) WorkbookFactory.create(inp);
HSSFSheet sheet = wb.getSheetAt(0);
String selectedid = auftragTabelle.getSelectionModel().getSelectedItem().getId();
int rowIndex = 0;
int lastRowNum = sheet.getLastRowNum();
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(selectedid)) {
rowIndex = cell.getRowIndex();
}
}
}
}
if (rowIndex >= 0 && rowIndex < lastRowNum) {
sheet.shiftRows(rowIndex, lastRowNum, -1);
}
if (rowIndex <= lastRowNum) {
HSSFRow removingRow = sheet.getRow(rowIndex);
if (removingRow != null) {
sheet.removeRow(removingRow);
}
}
OutputStream out = new FileOutputStream(
"............";
wb.write(out);
out.close();
}
Here's an example of how I would do it:
public static void main(String[] args) throws InvalidFormatException, IOException {
FileInputStream inp = new FileInputStream(FILENAME);
HSSFWorkbook wb = (HSSFWorkbook) WorkbookFactory.create(inp);
HSSFSheet sheet = wb.getSheetAt(0);
String selectedid = "3";
int rowIndex = getRowIndexOfId(sheet, selectedid);
removeRow(sheet, rowIndex);
OutputStream out = new FileOutputStream(FILENAME);
wb.write(out);
out.close();
}
private static int getRowIndexOfId(HSSFSheet sheet, String selectedid) {
DataFormatter formatter = new DataFormatter();
for (Row row : sheet) {
for (Cell cell : row) {
if (formatter.formatCellValue(cell).trim().equals(selectedid)) {
return row.getRowNum();
}
}
}
return -1;
}
private static void removeRow(HSSFSheet sheet, int rowIndex) {
if (rowIndex >= 0) {
sheet.removeRow(sheet.getRow(rowIndex));
if(rowIndex < sheet.getLastRowNum()) {
sheet.shiftRows(rowIndex + 1, sheet.getLastRowNum(), -1);
}
}
}
A few comments:
You can use the class DataFormatter to format the cell values (so you can compare any cell value)
I - like you - compare any cell in a cell; the typical use case for me would be to search the first col of each row to find the id. SO if you want that, adjust the code accordingly.
I did the shift row in the end, which should work better.

Apache POI - Excel Import, insert data from a new sheet into a column

I'm here to ask for help in my java project in Netbeans.
I'm using Apache POI to import/export excel data. To make you understand what is the problem in my application, I'm showing you a print of the debug.
In the print, you can see 2 sheets. The first header "aiai" and the data from that sheet.
My problem is: How do i insert the data from "aiai2" which is the second sheet from my excel file, in its proper place, below the header "aiai2"
On other words, I want to separate the sheets vertically.
Below, I will show my code:
Workbook wb;
public String Importar(File archivo, JTable tablaD) {
String answer = "Unable to import";
DefaultTableModel modeloT = new DefaultTableModel();
tablaD.setModel(modeloT);
tablaD.getModel();
tablaD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try {
wb = WorkbookFactory.create(new FileInputStream(archivo));
int nsheets = wb.getNumberOfSheets();
for (int i = 0; i < nsheets; i++) {
Sheet sheet = wb.getSheetAt(i);
Iterator filaIterator = sheet.rowIterator();
int rownum = -1;
while (filaIterator.hasNext()) {
rownum++;
Row fila = (Row) filaIterator.next();
/*if (i > 0) {//se o nr da ficha atual for maior que 0, começa a escrever as linhas apartir da row 0 da tabela
modeloT.moveRow(modeloT.getRowCount() -1, modeloT.getRowCount() - 1, 0);
}*/
Iterator columnaIterator = fila.cellIterator();
Object[] listaColumna = new Object[1000];
int columnnum = -1;
while (columnaIterator.hasNext()) {
columnnum++;
Cell celda = (Cell) columnaIterator.next();
if (rownum == 0) {
modeloT.addColumn(celda.getStringCellValue());
} else {
if (celda != null) {
switch (celda.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
listaColumna[columnnum] = (int) Math.round(celda.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
listaColumna[columnnum] = celda.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
listaColumna[columnnum] = celda.getBooleanCellValue();
break;
default:
listaColumna[columnnum] = celda.getDateCellValue();
break;
}//end switch case
System.out.println("Column:" + columnnum + " Row:" + rownum + " value:" + celda + ".");
}
}
}//end while column Iterator
if (rownum != 0) {
modeloT.addRow(listaColumna);
}
}//end while row iterator
}//end for
answer = "Imported with success";
} catch (IOException | InvalidFormatException | EncryptedDocumentException e) {
System.err.println(e.getMessage());
}
return answer;
}
public String Exportar(File archivo, JTable tablaD) {
String answer = "Unable to export";
int numFila = tablaD.getRowCount(), numColumna = tablaD.getColumnCount();
if (archivo.getName().endsWith("xls")) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
Sheet hoja = wb.createSheet("Default");
try {
for (int i = -1; i < numFila; i++) {
Row fila = hoja.createRow(i + 1);
for (int j = 0; j < numColumna; j++) {
Cell celda = fila.createCell(j);
if (i == -1) {
celda.setCellValue(String.valueOf(tablaD.getColumnName(j)));
} else {
celda.setCellValue(String.valueOf(tablaD.getValueAt(i, j)));
}
wb.write(new FileOutputStream(archivo));
}
}
answer = "Exported with success";
} catch (Exception e) {
System.err.println(e.getMessage());
}
return answer;
}
As I understand your question, I assume you want to create a separate table for each sheet, one below other. In that case you need to create a new table everytime you read a new sheet. If you use only one table, you will get only one header.
Try this :
Create a new method Importar that takes a new table and a Sheet parameter
public String Importar(JTable tablaD, Sheet sheet) {
String answer = "Unable to import";
DefaultTableModel modeloT = new DefaultTableModel();
tablaD.setModel(modeloT);
tablaD.getModel();
tablaD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try {
Iterator filaIterator = sheet.rowIterator();
int rownum = -1;
....
....
So the calling method would be :
try {
Workbook wb = WorkbookFactory.create(new FileInputStream(archivo));
int nsheets = wb.getNumberOfSheets();
for (int i = 0; i < nsheets; i++) {
//You have to make sure your JTable gets rendered.
JTable tablaD = new JTable();
Importar( tablaD, wb.getSheetAt(i) );
}
} catch ( Exception e ) {
e.printStackTrace();
}
Important point is that your new table needs to get rendered or added to frame each time before you call Importar

Selenium reading data from Excel file

I am trying to read some test data from an Excel file (3 rows and 2 columns with no blank row in between) but in the output I am getting just the first row of the Excel. After that it is giving me a null pointer exception.
public class ReadDataFromExcel {
public void readExcel(String filePath,String fileName,String sheetName) throws IOException {
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook myWorkbook = null;
String fileExtensionName = fileName.substring(fileName.indexOf("."));
if(fileExtensionName.equals(".xlsx")) {
myWorkbook = new XSSFWorkbook(inputStream);
}
else if(fileExtensionName.equals(".xls")) {
myWorkbook = new HSSFWorkbook(inputStream);
}
Sheet mySheet = myWorkbook.getSheet(sheetName);
int rowCount = mySheet.getLastRowNum()- guru99Sheet.getFirstRowNum();
System.out.println("Total rows= " +rowCount);
for (int i = 0; i < rowCount+1; i++) {
Row row = mySheet.getRow(i);
int columnCount = row.getLastCellNum() - row.getFirstCellNum();
for(int j=0; j <= columnCount; j++) {
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
}
System.out.println();
}
}
public static void main(String...strings) throws IOException {
ReadDataFromExcel objExcelFile = new ReadDataFromExcel();
String filePath = System.getProperty("user.dir")+"\\src\\testFileInputOutput";
objExcelFile.readExcel(filePath,"testExcel.xlsx","testSheet");
}
}
I am getting the exception on this line:
System.out.print(row.getCell(j).getStringCellValue()+"|| ");
To get past NullPointerException you can check for null by replacing the line that is throwing the exception with this:
Cell cell = row.getCell(j);
if (cell != null) {
System.out.print(cell.getStringCellValue());
}
System.out.print("|| ");

How can i copy data from cells of one excel file to another excel file(in desired row and columns) in java using Apache POI

Here is the code below to fetch data from one sheet. Now my query is how can i store this all output data, so that i can write another method to paste it in a diffrent sheet.
public void ReadCount(String Path) {
String []module;
int [][]status;
try {
FileInputStream fs = new FileInputStream(new File(Path));
XSSFWorkbook workBook = new XSSFWorkbook(fs);
boolean isPresent = false;
XSSFSheet sheet = workBook.getSheetAt(0);
for (int i=0; i<sheet.getLastRowNum(); i++) {
Row r = sheet.getRow(i);
for (int cn=0; cn<r.getLastCellNum(); cn++) {
Cell c = r.getCell(cn);
c.setCellType ( Cell.CELL_TYPE_STRING );
String text = c.getStringCellValue();
if(text.trim().equalsIgnoreCase("Module Name")) {
for(int a = i+2; a<sheet.getLastRowNum(); a++) {
Row p = sheet.getRow(a);
Cell q = p.getCell(cn);
q.setCellType ( Cell.CELL_TYPE_STRING );
String m = q.getStringCellValue();
System.out.println(m);
Cell k = p.getCell(cn+1);
k.setCellType ( Cell.CELL_TYPE_NUMERIC );
double PASS = k.getNumericCellValue();
int P = (int)PASS;
System.out.println(P);
Cell l = p.getCell(cn+2);
l.setCellType ( Cell.CELL_TYPE_NUMERIC );
double FAIL = l.getNumericCellValue();
int F = (int)FAIL;
System.out.println(F);
Cell n = p.getCell(cn+3);
n.setCellType ( Cell.CELL_TYPE_NUMERIC );
double ONHOLD = n.getNumericCellValue();
int O = (int)ONHOLD;
System.out.println(O);
}
//return module;
}
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
The console output for this method is
ROW1
1
0
0
ROW2
1
0
0
ROW3
0
1
0
ROW4
0
1
1

Categories