How to merge cells to the last row in poi - java

I am creating a workbook using apache poi where i am trying to merge a particular cell to the end of the output.I am using mergeRegion function and cell is merging but, that cell is not merging to the end of the row , it is always ending one line before ,
i am attaching the screen here merged cell
I want the cell to be merged properly, i am posting my code here
for(MarshActiveUser marshActiveUser : listOfMarshUser){
/***/
sheet.addMergedRegion(new CellRangeAddress(
j, //first row (0-based)
j, //last row (0-based)
18, //first column (0-based)
20 //last column (0-based)
));
/***/
int columnNo = 0;
row = sheet.createRow(j+1);
cell = row.createCell(columnNo);
cell.setCellValue(new HSSFRichTextString(String.valueOf(row.getRowNum())));
lockedCellStyle.setFont(hSSFFont);
sheet.autoSizeColumn(0);
cell.setCellStyle(lockedCellStyle);
columnNo = 1;
cell = row.createCell(columnNo);
if(null != marshActiveUser.getFistName()){
cell.setCellValue(new HSSFRichTextString(marshActiveUser.getFistName()));
lockedCellStyle.setFont(hSSFFont);
sheet.autoSizeColumn(1);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
I have tried to start from rowCount +1 but that is not allowed in code , please help me .Thanks in advance.

There is a problem with rowCount increment. Pre incrementing the row count is skipping your last row for merging. Changed it to post increment rowcount++ and its working as expected.
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class SimpleExcelWriterExample {
public static void main(String[] args) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Java Books");
Object[][] bookData = {
{"Head First Java", "Kathy Serria", 79},
{"Effective Java", "Joshua Bloch", 36},
{"Clean Code", "Robert martin", 42},
{"Thinking in Java", "Bruce Eckel", 35},
};
int rowCount = 1;
for (Object[] aBook : bookData) {
/***/
sheet.addMergedRegion(new CellRangeAddress(
rowCount, //first row (0-based)
rowCount, //last row (0-based)
3, //first column (0-based)
5 //last column (0-based)
));
/***/
Row row = sheet.createRow(rowCount++);
int columnCount = 0;
for (Object field : aBook) {
Cell cell = row.createCell(++columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try{
FileOutputStream outputStream = new FileOutputStream("D://JavaBooks.xls");
workbook.write(outputStream);
}catch(Exception e){}
}}
Output:

Related

How to write specific row when condition is met in another Excel sheet [duplicate]

This question already has answers here:
How do I resolve ClassNotFoundException?
(28 answers)
Closed 6 months ago.
I am in a learning stage of Java. I want to write a program in Java which reads one Excel file (.xlsx). This file has some columns and many rows. I want to write the data in another Excel file (.xlsx) only the condition is met not all the data from existing file.
My Excel sheet looks like below
I want to filter only those rows with broker Edelweiss and put it in another Excel sheet. I am aware how to copy all the data from one Excel to another Excel using Java. I don't know how to filter a specific row and put it in another Excel.
Here is my code.
FileInputStream file = new FileInputStream(new File("broker.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
I am getting the below error when I run Axel Richter's code which is shared below
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream
at org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:209)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:222)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:185)
at writefile.main(writefile.java:92)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
I have included below jars in my classpath
POI_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/poi-5.2.2.jar
POI_OOXML_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/poi-ooxml-full-5.2.2.jar
XML_BEANS_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/xmlbeans-5.0.3.jar
COM_COLL_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-collections4-4.4.jar
COM_COMPRESS_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/commons-compress-1.21.jar
COM_CODEC_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-codec-1.15.jar
COM_IO_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-io-2.11.0.jar
COM_MATH_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/commons-math3-3.6.1.jar
LOG_J4_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/log4j-api-2.17.2.jar
SPARSE_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/lib/SparseBitSet-1.2.jar
COM_LOGG_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/commons-logging-1.2.jar
CURVE_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/curvesapi-1.07.jar
SLF4_LIB=$(TOP_DIR)/jar/poi-bin-5.2.2/ooxml-lib/slf4j-api-1.7.36.jar
I will make my comment an answer.
I would open the source sheet and loop through all rows in it. For each row I would get the content of the column where "Broker" is stored. Then, if that content equals "Edelweiss" I would get that row into a Java collection, a list of rows for example. After that I would write the content of that Java collection into the result sheet.
The following complete example shows this.
It contains methods to get the last filled row in a special column of a sheet and to get the last filled column in a special row of a sheet. That is to determine the used cell range of a sheet.
It also contains a method to get the headings, which maps headings to column indexes. The headings must be in first row of the used cell range of the sheet.
It also shows how to use CellUtil.copyCell to copy cells from one sheet to another.
The code is tested and works using current apache poi 5.2.2.
The first sheet of broker.xlsx looks like:
Code:
import java.io.FileOutputStream;
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
class ExcelFilterRowsToNewWorkbook {
static int getLastFilledRow(Sheet sheet, int col) {
int lastStoredRowNum = sheet.getLastRowNum();
for (int r = lastStoredRowNum; r >= 0; r--) {
Row row = sheet.getRow(r);
if (row != null) {
Cell cell = row.getCell(col);
if (cell != null && cell.getCellType() != CellType.BLANK) return row.getRowNum();
}
}
return -1; // the sheet is empty in that col
}
static int getLastFilledColumn(Sheet sheet, int rowIdx) {
int lastStoredCellNum = sheet.getRow(rowIdx).getLastCellNum();
Row row = sheet.getRow(rowIdx);
if (row != null) {
for (int c = lastStoredCellNum; c >= 0; c--) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != CellType.BLANK) return cell.getColumnIndex();
}
}
return -1; // the sheet is empty in that row
}
static Map<Integer, String> getHeadings(Sheet sheet) {
DataFormatter dataFormatter = new DataFormatter(new Locale("en", "US"));
dataFormatter.setUseCachedValuesForFormulaCells(true);
int firstRow = sheet.getFirstRowNum();
int firstCol = sheet.getRow(firstRow).getFirstCellNum();
int lastCol = getLastFilledColumn(sheet, firstRow);
Map<Integer, String> headings = new HashMap<Integer, String>();
Row row = sheet.getRow(firstRow);
if (row != null) {
for (int c = firstCol; c <= lastCol; c++) {
Cell cell = row.getCell(c);
headings.put(c, dataFormatter.formatCellValue(cell));
}
}
return headings;
}
static List<Row> filterRows(Sheet sheet, String filterHeading, String filterValue) {
int filterCol = -1;
Map<Integer, String> headings = getHeadings(sheet);
for (Map.Entry<Integer, String> entry : headings.entrySet()) {
if (entry.getValue().equals(filterHeading)) {
filterCol = entry.getKey();
break;
}
}
List<Row> rows = new ArrayList<Row>();
// add the headings row
int firstRow = sheet.getFirstRowNum();
rows.add(sheet.getRow(firstRow));
// add the fildered rows
if (filterCol > -1) {
DataFormatter dataFormatter = new DataFormatter(new Locale("en", "US"));
dataFormatter.setUseCachedValuesForFormulaCells(true);
int firstCol = sheet.getRow(firstRow).getFirstCellNum();
int lastCol = getLastFilledColumn(sheet, firstRow);
int lastRow = getLastFilledRow(sheet, firstCol);
for (int r = firstRow; r <= lastRow; r++) {
Row row = sheet.getRow(r);
if (row != null && lastCol >= filterCol) {
Cell cell = row.getCell(filterCol);
String cellContent = dataFormatter.formatCellValue(cell);
if (cellContent.equals(filterValue)) {
rows.add(row);
}
}
}
}
return rows;
}
public static void main(String[] args) throws Exception {
try (Workbook workbookSrc = WorkbookFactory.create(new FileInputStream("./broker.xlsx")) ) {
Sheet sheetSrc = workbookSrc.getSheetAt(0);
// get filtered rows
List<Row> rowsSrc = filterRows(sheetSrc, "Broker", "Edelweiss");
// add filtered rows in new workbook
try (Workbook workbookDest = WorkbookFactory.create(true);
FileOutputStream fileout = new FileOutputStream("./brokerFiltered.xlsx") ) {
Sheet sheetDest = workbookDest.createSheet();
int r = 0;
for (Row rowSrc : rowsSrc) {
Row rowDest = sheetDest.createRow(r++);
for (Cell cellSrc : rowSrc) {
Cell cellDest = rowDest.createCell(cellSrc.getColumnIndex());
CellUtil.copyCell(cellSrc,
cellDest,
new CellCopyPolicy(),
new CellCopyContext()
);
}
}
workbookDest.write(fileout);
}
}
}
}
The first sheet of brokerFiltered.xlsx then looks like:

Getting Exception when reorder RowLabel when hiding the Subtotal -Apache POI

As per below code i dont want to add addRowLabel(1) but need addRowLabel(2) . After running the application and open the pivot table its giving exception but if you add addRowLabel(1)(currently commented) its working as expected. This is happening after adding the logic to hide Subtotal. Is this is the expected behaviour of apache POI or It can be fixed?
Please find the code below.
Note: This issue comes when hiding subtotal.
package com.test.pivottables;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
class TestPivotTables {
public static void main(String[] args) throws IOException{
Workbook wb = new XSSFWorkbook();
String[][] data = new String[][]{{"STATUS","PASSED","DATA","VALUE"},
{"BLUE","Y","TTT","20"},
{"RED","N","UUU","10"},{"BLUE","N","PPP","30"}};
XSSFSheet sheet = (XSSFSheet) wb.createSheet("data");
XSSFSheet pivot = (XSSFSheet) wb.createSheet("summary");
for(String[] dataRow : data){
XSSFRow row = sheet.createRow(sheet.getPhysicalNumberOfRows());
for(String dataCell : dataRow){
XSSFCell cell =
row.createCell(row.getPhysicalNumberOfCells());
cell.setCellValue(dataCell);
}
}
XSSFTable table = sheet.createTable();
CTTable cttable = table.getCTTable();
table.setDisplayName("table");
cttable.setRef("A1:D4");
cttable.setId(1);
CTTableColumns columns = cttable.addNewTableColumns();
columns.setCount(3);
int i = 1;
for (String colName : data[0]){
CTTableColumn column = columns.addNewTableColumn();
column.setId(++i);
column.setName(colName);
}
XSSFPivotTable pivotTable = pivot.createPivotTable(new
AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007),
new CellReference("A4"), sheet);
pivotTable.addRowLabel(0);
pivotTable.addRowLabel(2);
//pivotTable.addRowLabel(1);
List<Integer> iterList = new ArrayList<Integer>();
iterList.add(0);
iterList.add(2);
//iterList.add(1);
pivotTable.getCTPivotTableDefinition().setRowHeaderCaption("Colour");
for (int j=0;j<iterList.size();j++) {
CTPivotField ctPivotField =
pivotTable.getCTPivotTableDefinition().getPivotFields().
getPivotFieldList().get(iterList.get(j));
for (i = 0; i < sheet.getLastRowNum()-1; i++) {
if(ctPivotField.getItems().getItemArray(i)!=null) {
ctPivotField.getItems().getItemArray(i).unsetT();
ctPivotField.getItems().getItemArray(i).setX((long)i);
}
}
for (i = sheet.getLastRowNum(); i > sheet.getLastRowNum()-2; i--)
{
if(ctPivotField.getItems().getItemArray(i)!=null) {
ctPivotField.getItems().removeItem(i);
}
}
ctPivotField.getItems().setCount(2);
Set<String> collection = new HashSet<String>();
int ctr = 0;
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(0);
collection.add(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
if(collection!=null && collection.size()>0) {
Iterator value = collection.iterator();
while (value.hasNext()) {
pivotTable.getPivotCacheDefinition().
getCTPivotCacheDefinition().getCacheFields().
getCacheFieldList().get(j).getSharedItems().addNewS().
setV(value.next().toString());
}
}
ctPivotField.setAutoShow(false);
ctPivotField.setDefaultSubtotal(false);
ctPivotField.setSubtotalTop(false);
ctPivotField.setSubtotalCaption(null);
ctPivotField.setCompact(false);
}
System.out.println("----end---");
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 3, "test");
FileOutputStream fileOut = new FileOutputStream("pivotsample1.xlsx");
wb.write(fileOut);
wb.close();
}}
The problem is how you are building the pivot table definition and the pivot cache definition. This must be done because apache poi creates as much fields for each row label as rows are in the pivot table data range. This is wrong when special settings shall be made for pivot fields. You try to do that, but you do it wrong.
I cannot go into detail where exactly you go wrong because that would be too much effort. But what needs to be done is:
For each column which is row label:
Determine unique labels in that column. This is necessary to build
the cache.
Then build pivot table and cache.
For each unique label:
Build pivot field item as numbered item.
Build a cache definition which has a shared element for this label.
Then remove further items from pivot table definition. But leave one default element there, if there should be subtotals. If not, then not.
Complete example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.*;
import java.io.*;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.List;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
class TestPivotTables {
public static void main(String[] args) throws IOException{
Workbook wb = new XSSFWorkbook();
String[][] data = new String[][]{
{"STATUS","PASSED","DATA","VALUE"},
{"BLUE","Y","TTT","20"},
{"RED","N","UUU","10"},
{"BLUE","N","PPP","30"}
};
XSSFSheet sheet = (XSSFSheet) wb.createSheet("data");
XSSFSheet pivot = (XSSFSheet) wb.createSheet("summary");
for(String[] dataRow : data){
XSSFRow row = sheet.createRow(sheet.getPhysicalNumberOfRows());
for(String dataCell : dataRow){
XSSFCell cell = row.createCell(row.getPhysicalNumberOfCells());
cell.setCellValue(dataCell);
}
}
AreaReference areaReference = new AreaReference("A1:D4", SpreadsheetVersion.EXCEL2007);
XSSFPivotTable pivotTable = pivot.createPivotTable(areaReference, new CellReference("A4"), sheet);
pivotTable.getCTPivotTableDefinition().setRowHeaderCaption("Colour");
List<Integer> iterList = new ArrayList<Integer>();
iterList.add(0);
iterList.add(2);
iterList.add(1);
for (Integer j : iterList) {
//create row label - apache poi creates as much fields for each as rows are in the pivot table data range
pivotTable.addRowLabel(j);
//determine unique labels in column j
TreeSet<String> uniqueItems = new java.util.TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
for (int r = areaReference.getFirstCell().getRow()+1; r < areaReference.getLastCell().getRow()+1; r++) {
uniqueItems.add(sheet.getRow(r).getCell(j).getStringCellValue());
}
System.out.println(uniqueItems);
//build pivot table and cache
CTPivotField ctPivotField = pivotTable.getCTPivotTableDefinition().getPivotFields().getPivotFieldArray(j);
int i = 0;
for (String item : uniqueItems) {
//take the items as numbered items: <item x="0"/><item x="1"/>
ctPivotField.getItems().getItemArray(i).unsetT();
ctPivotField.getItems().getItemArray(i).setX((long)i);
//build a cache definition which has shared elements for those items
//<sharedItems><s v="BLUE"/><s v="RED"/></sharedItems>
pivotTable.getPivotCacheDefinition().getCTPivotCacheDefinition().getCacheFields().getCacheFieldArray(j)
.getSharedItems().addNewS().setV(item);
i++;
}
ctPivotField.setAutoShow(false);
ctPivotField.setDefaultSubtotal(false);
//ctPivotField.setSubtotalTop(false);
//ctPivotField.setSubtotalCaption(null);
ctPivotField.setCompact(false);
//remove further items
if (ctPivotField.getDefaultSubtotal()) i++; //let one default item be if there shall be subtotals
for (int k = ctPivotField.getItems().getItemList().size()-1; k >= i; k--) {
ctPivotField.getItems().removeItem(k);
}
ctPivotField.getItems().setCount(i);
}
System.out.println("----end---");
pivotTable.addColumnLabel(DataConsolidateFunction.COUNT, 3, "test");
FileOutputStream fileOut = new FileOutputStream("pivotsample1.xlsx");
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

Print the value of 10 and 11 column from excel using java

I have code to print all the values of excel cells but it's ignoring the blank cells. Is there any way to print the value of blank cell (null) as well?
And also is it possible to print particular 2 specific columns (with blank cells) like 10th and 11th column?
Below is my code. Please suggest what can i change in below code?
package excel;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Excel
{
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Users\\gur29175\\Desktop\\1.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
System.out.print(cell.getStringCellValue() + "\t");
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Row row = rowIterator.next();
for(int i = 0; i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if(cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
// handle not null values
}else{
// handle null values
}
}

Count number of rows in a column of Excel sheet(Java code provided)

In reference to my previous question How to calculate number of rows in a column of Excel document using Java i was able to calculate the total number of columns in the given sheet. Now half of the work is yet to be done as i want to calculate the number of rows in a particular column. Possible solution could be using 2d array and storing column index and the total rows or using map, etc. How i can achieve this? Java code is provided here. I'm getting right count(column count) for my demo file. Please modify/suggest changes as required.
(edit): i've used hasp map to calculate store column index as key and row count as value, but it wasnt working, may be the applied logic was wrong. Well, if i want to accomplish this by using Hash Map, how i can store number of rows in a particular column(while iterating) as a value
Java Code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
static int colrange=1000;
public static void main(String[] args) {
HashMap hm=new HashMap();
int count=0;
try {
FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Demo2.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
for(Row r:sheet)
{
short minColIx=r.getFirstCellNum();
short maxColIx=r.getLastCellNum();
for(short colIx=minColIx;colIx<maxColIx;colIx++) {
Cell c= r.getCell(colIx);
if(c!=null) {
if(c.getCellType()== Cell.CELL_TYPE_STRING||c.getCellType() == Cell.CELL_TYPE_NUMERIC||c.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
count++; ---// can i use hashcode in here to get the key and value pair? key=column index value=total number of rows in that column
}
}
else break;
}
}
System.out.println("\nTotal Number of columns are:\t"+count);
System.out.println(hm);
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ae) {
ae.printStackTrace();
}
}
}
Try this:
private void excelReader() {
String data;
try {
InputStream is = new FileInputStream("Read.xlsx");
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
Row r = (Row)rowIter.next();
short lastCellNum = r.getLastCellNum();
int[] dataCount = new int[lastCellNum];
int col = 0;
rowIter = sheet.rowIterator();
while(rowIter.hasNext()) {
Iterator cellIter = ((Row)rowIter.next()).cellIterator();
while(cellIter.hasNext()) {
Cell cell = (Cell)cellIter.next();
col = cell.getColumnIndex();
dataCount[col] += 1;
DataFormatter df = new DataFormatter();
data = df.formatCellValue(cell);
System.out.println("Data: " + data);
}
}
is.close();
for(int x = 0; x < dataCount.length; x++) {
System.out.println("col " + x + ": " + dataCount[x]);
}
}
catch(Exception e) {
e.printStackTrace();
return;
}
}
Tested code
I created an xlsx file with the following cell data:
Col0 Col1 Col2 Col3 Col4
1 a x a q
2 b y s w
3 c z d e
4 d f r
5 e t
y
The contents of dataCount array is this:
col 0: 6
col 1: 6
col 2: 4
col 3: 5
col 4: 7
The numbers on the right count the number of cells with data for each column, including the header row.
If you want to exclude the header row, just remove the line:
rowIter = sheet.rowIterator();
just before the while loop.
Is this what you are looking for?
Will this solve?
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = myRow.cellIterator();
List<HSSFCell> cellStore = new ArrayList<HSSFCell>();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
rowCount++ //For myRow
}
}
it is giving the total number of data in the excel sheet, i mean including the header column name as well.
In my understanding, you want to count the number of rows that a column has, EXCEPT for the header row.
If that's the case, you can use the solution provided by Binu. Just modify it to skip the row where the column name is.

How to apply bold text style for an entire row using Apache POI?

How to make an entire excel row cells bold text using Apache POI?
E.g:
Column headings should be in bold. Instead of applying style for each and every cell of heading row, how can I apply some style to an entire row?
This should work fine.
Workbook wb = new XSSFWorkbook("myWorkbook.xlsx");
Row row=sheet.getRow(0);
CellStyle style=null;
XSSFFont defaultFont= wb.createFont();
defaultFont.setFontHeightInPoints((short)10);
defaultFont.setFontName("Arial");
defaultFont.setColor(IndexedColors.BLACK.getIndex());
defaultFont.setBold(false);
defaultFont.setItalic(false);
XSSFFont font= wb.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Arial");
font.setColor(IndexedColors.WHITE.getIndex());
font.setBold(true);
font.setItalic(false);
style=row.getRowStyle();
style.setFillBackgroundColor(IndexedColors.DARK_BLUE.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setFont(font);
If you do not create defaultFont all your workbook will be using the other one as default.
Please find below the easy way :
XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
Row row = sheet.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
cell0.setCellStyle(style);
for(int j = 0; j<=3; j++)
row.getCell(j).setCellStyle(style);
This work for me
I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilĂ  first row is bolded.
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0);
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);
This worked for me
Object[][] bookData = { { "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 },
{ "col1", "col2", 3 }, { "col1", "col2", 3 }, { "col1", "col2", 3 } };
String[] headers = new String[] { "HEader 1", "HEader 2", "HEader 3" };
int noOfColumns = headers.length;
int rowCount = 0;
Row rowZero = sheet.createRow(rowCount++);
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
for (int col = 1; col <= noOfColumns; col++) {
Cell cell = rowZero.createCell(col);
cell.setCellValue(headers[col - 1]);
cell.setCellStyle(style);
}
A worked, completed and simple example:
package io.github.baijifeilong.excel;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* Created by BaiJiFeiLong#gmail.com at 2019/12/6 11:41
*/
public class ExcelBoldTextDemo {
#SneakyThrows
public static void main(String[] args) {
new XSSFWorkbook() {{
XSSFRow row = createSheet().createRow(0);
row.setRowStyle(createCellStyle());
row.getRowStyle().getFont().setBold(true);
row.createCell(0).setCellValue("Alpha");
row.createCell(1).setCellValue("Beta");
row.createCell(2).setCellValue("Gamma");
}}.write(new FileOutputStream("demo.xlsx"));
}
}
public class ExcelReader {
private XSSFWorkbook workBook;
private XSSFSheet workSheet;
public ExcelReader(String path, String sheetName){
File file = new File(path);
try {
FileInputStream inputStream = new FileInputStream(file);
workBook = new XSSFWorkbook(inputStream);
workSheet = workBook.getSheet(sheetName);
workBook.close();
}catch (Exception e){
e.printStackTrace();
}
}
public Object[][] getData(){
int rows = workSheet.getLastRowNum(); // returns number of rows
int cols = workSheet.getRow(0).getLastCellNum(); //returns number of cols
Object[][] data = new Object[rows][1];
for (int i = 0; i < rows; i++) {
Map<String,String> map = new HashMap<>();
for (int j = 0; j < cols; j++) {
//each column name is a key
XSSFCell cell = workSheet.getRow(i + 1).getCell(j);// might be null sometimes if the cell is empty
if (cell == null){
System.out.println();
}
map.put(workSheet.getRow(0).getCell(j).toString(),
// each cell under column name will be value
cell == null ? "" : cell.toString() );
}
data[i][0] = map;
}
return data;
}
}

Categories

Resources