I am using apache poi to write the data in excel file. When I am passing value to columns of first row (for heading), its value does not get updated but from row 2 onward I can see the data in excel file.
Below is the code I am using.
public static void writeWorkBook(Map<String, List<String>> addressMap, List<String> userList) {
System.out.println("Writing Process Started ");
XSSFWorkbook workbook = new XSSFWorkbook();
for (String user : userList) {
XSSFSheet sheet = workbook.createSheet("Data_" + user);
int rownum = 1;
Row row = sheet.createRow(rownum);
Cell cell = row.createCell(0);
cell.setCellValue("User");
cell = row.createCell(1);
cell.setCellValue("Address");
List<String> addressList = addressMap.get(user);
for (String s : addressList) {
row = sheet.createRow(rownum++);
cell = row.createCell(0);
cell.setCellValue(user);
cell = row.createCell(1);
cell.setCellValue(s);
}
}
try {
FileOutputStream out = new FileOutputStream(new File("D://practice/java/testWrite.xlsx"));
workbook.write(out);
out.close();
System.out.println("testWrite.xlsx written successfully on disk.");
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The output I am getting is
First: All indexes are 0-based. So
...
int rownum = 1;
Row row = sheet.createRow(rownum);
...
creates the second row. First row would be
...
int rownum = 0;
Row row = sheet.createRow(rownum);
...
Second: In row = sheet.createRow(rownum++); at first the row is created and then rownum is incremented. So first row is created again instead of second row.
Do
...
row = sheet.createRow(++rownum);
...
instead.
Getting and setting the rows are 0-based, so if you want to have the description in the first row, you need use 0 as argument in
Row row = sheet.createRow(rownum);
Related
I am trying to write out to an existing excel file. I don't want to create new rows or cells, I just want to write out the value from my array into the value at row x column y. Every time I have tried this so far I can only get it to work if I create a new row. Please help!!!
Integer columns = DataImport.columns_in_sheet[0];
Integer rowNum = learnerRow + 2;
try {
FileInputStream inp = new FileInputStream("D:/location/update.xlsx");
XSSFWorkbook wb = null;
wb = (XSSFWorkbook) WorkbookFactory.create(inp);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = sheet.getRow(18);//places the start row
XSSFCell cell = null;//places the start column
cell = row.getCell(0);
//#########################################################################################
//#########################################################################################
for (int j = 0; j < exportData.length; j++) {
//sheet.createRow(rowNum+j);
//row = sheet.getRow(rowNum+j);
//row = sheet.getRow(rowNum+j);
for (int i=0; i < columns;i++){
cell.setCellType(CellType.STRING);
cell.setCellValue(exportData[j][i]);
}
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("D:/location/update.xlsx");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
this code throws a null pointer because of row being null, I can only seem to get rid of the error by creating new rows. I am using XSSF formatting.
The logic of your code snippet is not clear. It looks not logically to me.
But to avoid NPE while using rows and cells from present sheets, one always needs check whether the row or cell was present already or needs to be new created. This is necessary because for not present rows Sheet.getRow will return null. Also Row.getCell will return null for not present cells.
So we can do:
Sheet sheet = ...
Row row = sheet.getRow(rowIdx); if (row == null) row = sheet.createRow(rowIdx);
Cell cell = row.getCell(cellIdx); if (cell == null) cell = row.createCell(cellIdx);
Now row either is a row which was already present or it is a new created row. And cell either is a cell which was already present or it is a new created cell. Neither row nor cell will be null. And at first present rows/cells will be got before they were new created if not present. So present rows and cells will not be destroyed.
The same is needed in loops:
Sheet sheet = ...
Row row;
Cell cell;
for (int rowIdx = 0; rowIdx < 10; rowIdx++) {
row = sheet.getRow(rowIdx); if (row == null) row = sheet.createRow(rowIdx);
for (int cellIdx = 0; cellIdx < 10; cellIdx++) {
cell = row.getCell(cellIdx); if (cell == null) cell = row.createCell(cellIdx);
// do something with cell
}
}
I want to create an Excel file with Apache Poi, based on the sheet of another Excel file. Only the first two columns and their corresponding rows should be applied to the new Excel sheet.
First, I insert all cells of the first column, then I increment the columnIndex to insert the other cells.
private static void createNewWorkBook(XSSFSheet oldSheet) {
XSSFWorkbook newWorkbook = new XSSFWorkbook();
XSSFSheet newSheet = newWorkbook.createSheet("test-sheet");
for (int columnIndex = 0; columnIndex < 2; columnIndex++) {
int rowIndex = 0;
for (Row oldRow : oldSheet) {
XSSFRow newRow = newSheet.createRow(rowIndex);
XSSFCell newCell = newRow.createCell(columnIndex);
newCell.setCellValue("Hello"); // just for test purposes
// newCell.setCellValue(oldSheet.getRow(rowIndex).getCell(columnIndex).getStringCellValue());
rowIndex++;
}
}
try {
FileOutputStream fos = new FileOutputStream(new File("CreateExcelDemo.xlsx"));
newWorkbook.write(fos);
fos.close();
} catch (
IOException e) {
e.printStackTrace();
}
}
Unfortunatley it doesn't work. I only get the values of the second column in my newly generated excel-sheet. The first column is just empty.
BUT:
If I replace the columnIndex with 0 or 1, it works! Where is my thinking problem?
Using Apache POI, I am trying to read an excel file. The file has 1000 rows and 1 column. With this code:
XSSFSheet ws = workbook.getSheetAt(0);
Iterator< Row > rowIt = ws.iterator();
XSSFRow row;
int i = 0;
while ( rowIt.hasNext() ) {
row = (XSSFRow) rowIt.next();
Iterator< Cell > cellIt = row.cellIterator();
while ( cellIt.hasNext() ) {
Cell cell = cellIt.next();
my_array[ i ] = cell.getStringCellValue();
}
++i;
}
It seems that it reads 1001 rows and since the last row is "", my_array get invalid string. Is there any way to fix that? I expect rowIt.hasNext() is responsible for that but it doesn't work as expected.
The file has 1000 rows and 1 column : you must specify what column you are reading.
here an exemple that specify column with this excel file:
public class TestLecture {
public static void main(String[] args) throws IOException{
List<String> mys_list= new ArrayList<String>();
FileInputStream file = new FileInputStream(new File("test.xlsx"));
//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);
//Get first sheet from the workbook
XSSFSheet ws = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIt = ws.iterator();
while (rowIt.hasNext()) {
Row row = rowIt.next();
Iterator<Cell> cellIt = row.iterator();
while (cellIt.hasNext()) {
Cell cell = cellIt.next();
int columnIndex = cell.getColumnIndex();
switch (columnIndex) {
case 2:
mys_list.add(cell.getStringCellValue());
break;
}
}
}
System.out.println(mys_list.size());
for(String g :mys_list){
System.out.println(g);
}
}
}
I have tried to read values from excel file to store each and every row and cells from XSSFWorkbook in an object and add it to arraylist.But its adding only last element in arraylist. Including my code below.
try
{
ArrayList<OrderInfo> orderList = new ArrayList<OrderInfo>();
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("C:/mytemp/Order Details.xlsx"));
for (Sheet sheet : wb ) {
OrderInfo order_Info = new OrderInfo();
for (Row row : sheet) {
int rowId = row.getRowNum();
if(rowId != 0){
Cell del_zone = row.getCell(0);
order_Info.setDel_zone(del_zone.getStringCellValue());
Cell cust_id = row.getCell(1);
order_Info.setCustomer_id(cust_id.getStringCellValue());
}
}
orderList.add(order_Info);
}
for(int i = 0;i<orderList.size();i++){
logger.info("*******Print List Object******"+orderList.get(i).getDel_zone()+"****Cust_Id****"+orderList.get(i).getCustomer_id());
}
}
catch (Exception e)
{
System.err.println("Exception :" + e.getMessage());
}
orderList.add(order_Info) should be inside the for (Row row : sheet) loop, you have it outside
Also it needs to be created inside the loop: OrderInfo order_Info = new OrderInfo(); should be later
for (Sheet sheet : wb ) {
for (Row row : sheet) {
int rowId = row.getRowNum();
if(rowId != 0){
Cell del_zone = row.getCell(0);
OrderInfo order_Info = new OrderInfo();
order_Info.setDel_zone(del_zone.getStringCellValue());
Cell cust_id = row.getCell(1);
order_Info.setCustomer_id(cust_id.getStringCellValue());
orderList.add(order_Info);
}
}
}
How do i get the index of the last column when reading a xlsx file using the Apache POI API?
There's a getLastRowNum method, but I can't find nothing related to the number of columns...
EDIT:
I'm dealing with XLSX files
I think you'll have to iterate through the rows and check HSSFRow.getLastCellNum() on each of them.
Check each Row and call Row.getLastCellNum() the max cell number is the last column number.
Row r = sheet.getRow(rowNum);
int maxCell= r.getLastCellNum();
To get to know the last column that has value of any row , First you need to get the row and then you can find the last column that has value
Syntax :
sheet.getrow(RowNumber).getLastCellNum();
RowNumber --> is the row number for which you want to know the last column that has value
Try this function:
private void maxExcelrowcol() {
int row, col, maxrow, maxcol;
//Put file name here for example filename.xls
String filename = "filename.xls";
static String TAG = "ExelLog";
//you can use 'this' in place of context if you want
Context context = getApplicationContext();
try {
// Creating Input Stream
File file = new File(context.getExternalFilesDir(null), filename);
FileInputStream myInput = new FileInputStream(file);
// Create a POIFSFileSystem object
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
// Create a workbook using the File System
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
// Get the first sheet from workbook
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
//Row iterator
Iterator rowIter = mySheet.rowIterator();
while (rowIter.hasNext()) {
HSSFRow myRow = (HSSFRow) rowIter.next();
//Cell iterator for iterating from cell to next cell of a row
Iterator cellIter = myRow.cellIterator();
while (cellIter.hasNext()) {
HSSFCell myCell = (HSSFCell) cellIter.next();
row = myCell.getRowIndex();
col = myCell.getColumnIndex();
if (maxrow < row) {
maxrow = row;
}
if (maxcol < col) {
maxcol = col;
}
}
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}