Error when editing an excel file with Java (ConcurrentModificationException) - java

I'm trying to modify the last cell of the rows in an excel workbook that in any cell match another value.
In the first iteration it works fine, but in the second loop I get this java.util.ConcurrentModificationException error in the for (Cell cell : row) { line.
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1486)
at java.base/java.util.TreeMap$ValueIterator.next(TreeMap.java:1531)
at Package.Fotos.initial(Fotos.java:266)
at Package.Fotos.main(Fotos.java:360)
Does anyone know what I'm doing wrong? This is the code I'm using based on this answer.
...
for (int i = 0; i < cuentafilas; i++) {
List<WebElement> columnas = filas.get(i).findElements(By.tagName("img"));
int cuentacolumnas = columnas.size();
for (int k = 0; k < cuentacolumnas; k++) {
String c = columnas.get(k).getAttribute("src");
if (c.contains("jpg")) {
String filtroValor = id;
Workbook libro = WorkbookFactory.create(new FileInputStream("D:\\archivos\\entrada.xlsx"));
DataFormatter formatter = new DataFormatter();
Sheet hoja = libro.getSheetAt(0);
for (Row row : hoja) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
String text = formatter.formatCellValue(cell);
if (filtroValor.equals(text)) {
Row fila = hoja.getRow(row.getRowNum());
int ultimaCelda = fila.getLastCellNum();
Cell celda = fila.createCell(ultimaCelda);
celda.setCellValue(c);
OutputStream os = new FileOutputStream("D:\\archivos\\entrada.xlsx");
libro.write(os);
}
}
}
}
}
}
...
Thanks.

The error lies in
Cell celda = fila.createCell(ultimaCelda);
where you create a new cell in the row.
You can't add a cell, while iterating over the list of all cells.
Try creating a copy of the list you are wanting to edit and iterate
over that one instead, so the other one becomes editable
the java.util.ConcurrentModificationException appears,
when editing a list, that you are currently iterating over.

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:

POI Word Unable to merge newly created cell vertically

I know how to merge cells vertically with Apache POI word. But it seems if a new row is created, the merge won't take effect.
Here is the input table:
I wish to add a new row between old row 2 and old row 3, and have the new row's cell at first column merged into C2, like this:
So I created a new row and added it to the table below old row 2, and attempt to merge the cells
github source code link is here, it can reproduce the problem.
public class POIWordAddSubRowQuestionDemo{
public static void main(String[] args) throws IOException, XmlException{
ClassLoader classLoader = POIWordAddSubRowQuestionDemo.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("input.docx");
String outputDocxPath = "F:/TEMP/output.docx";
assert inputStream != null;
XWPFDocument doc = new XWPFDocument(inputStream);
XWPFTable table = doc.getTables().get(0);
//this is 'old row 2'
XWPFTableRow secondRow = table.getRows().get(1);
//create a new row that is based on 'old row 2'
CTRow ctrow = CTRow.Factory.parse(secondRow.getCtRow().newInputStream());
XWPFTableRow newRow = new XWPFTableRow(ctrow, table);
XWPFRun xwpfRun = newRow.getCell(1).getParagraphs().get(0).getRuns().get(0);
//set row text
xwpfRun.setText("new row", 0);
// add new row below 'old row 2'
table.addRow(newRow, 2);
//merge cells at first column of 'old row 2', 'new row', and 'old row 3'
mergeCellVertically(doc.getTables().get(0), 0, 1, 3);
FileOutputStream fos = new FileOutputStream(outputDocxPath);
doc.write(fos);
fos.close();
}
static void mergeCellVertically(XWPFTable table, int col, int fromRow, int toRow) {
for(int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
CTVMerge vmerge = CTVMerge.Factory.newInstance();
if(rowIndex == fromRow){
// The first merged cell is set with RESTART merge value
vmerge.setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
vmerge.setVal(STMerge.CONTINUE);
// and the content should be removed
for (int i = cell.getParagraphs().size(); i > 0; i--) {
cell.removeParagraph(0);
}
cell.addParagraph();
}
// Try getting the TcPr. Not simply setting an new one every time.
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
tcPr.setVMerge(vmerge);
}
}
}
But the merge did not work and I got:
In another attempt, I tried to merge based on the table in picture 3 to get the table in picture 2, and it was a success. The only difference between the 2 attempts is that new row was not newly created, but rather read from the docx document, so I believe creating a new row was the reason why merge failed.
So is there a solution for merging newly created rows? I really don't want to split this operation like this: adding rows > saving docx to disk> read docx from disk> merge rows.
The problem you have is not with mergeCellVertically method but with your approach to copy table row. When copying the underlying CTRow and inserting it in CTTbl.TrArray using XWPFTable.addRow it must be fully complete. Later changings are not written in XML. I told that in my answer java Apache POI Word existing table insert row with cell style and formatting already. And I provided a method commitTableRows in my answer Can't change row text in .docx file once row is added to table. This method needs to be called before writing out the document, so the later changes get written in XML.
So because you are copying second row, which is the start of merging, that setting also gets copied. And the later called mergeCellVertically does not take effect. So your newRow remains new start of merging. This is what you get.
So after all changes and before writing out, call commitTableRows.
Complete example:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
public class WordInsertTableRowAndMerge {
static XWPFTableRow insertNewTableRow(XWPFTableRow sourceTableRow, int pos) throws Exception {
XWPFTable table = sourceTableRow.getTable();
CTRow newCTRrow = CTRow.Factory.parse(sourceTableRow.getCtRow().newInputStream());
XWPFTableRow tableRow = new XWPFTableRow(newCTRrow, table);
table.addRow(tableRow, pos);
return tableRow;
}
static void commitTableRows(XWPFTable table) {
int rowNr = 0;
for (XWPFTableRow tableRow : table.getRows()) {
table.getCTTbl().setTrArray(rowNr++, tableRow.getCtRow());
}
}
static void mergeCellVertically(XWPFTable table, int col, int fromRow, int toRow) {
for(int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
System.out.println("rowIndex: " + rowIndex);
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
CTVMerge vmerge = CTVMerge.Factory.newInstance();
if(rowIndex == fromRow){
// The first merged cell is set with RESTART merge value
vmerge.setVal(STMerge.RESTART);
} else {
// Cells which join (merge) the first one, are set with CONTINUE
vmerge.setVal(STMerge.CONTINUE);
// and the content should be removed
for (int i = cell.getParagraphs().size(); i > 0; i--) {
cell.removeParagraph(0);
}
cell.addParagraph();
}
// Try getting the TcPr. Not simply setting an new one every time.
CTTcPr tcPr = cell.getCTTc().getTcPr();
if (tcPr == null) tcPr = cell.getCTTc().addNewTcPr();
tcPr.setVMerge(vmerge);
}
}
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument(new FileInputStream("./source.docx"));
XWPFTable table = doc.getTables().get(0);
XWPFTableRow row = table.getRow(1);
XWPFTableRow newRow = insertNewTableRow(row, 2);
XWPFTableCell cell = newRow.getCell(0); if (cell == null) cell = newRow.addNewTableCell();
// not needed because merged to cell above
cell = newRow.getCell(1); if (cell == null) cell = newRow.addNewTableCell();
for (XWPFParagraph paragraph : cell.getParagraphs()) { // only use first text runs in paragraphs
for (int r = paragraph.getRuns().size()-1; r >= 0; r--) {
XWPFRun run = paragraph.getRuns().get(r);
if (r == 0) {
run.setText("new row 1", 0);
} else {
paragraph.removeRun(r);
}
}
}
mergeCellVertically(table, 0, 1, 3);
commitTableRows(table);
FileOutputStream out = new FileOutputStream("./result.docx");
doc.write(out);
out.close();
doc.close();
}
}
Here's a VBA approach you might like to adapt. It inserts a new row between rows 3 & 4:
Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Tables(1)
.Cell(4, 2).Range.InsertBreak (wdColumnBreak)
.Rows.Add
.Cell(2, 1).Merge MergeTo:=.Cell(4, 1)
.Range.Characters.Last.Next.Delete
.Cell(2, 1).Merge MergeTo:=.Cell(5, 1)
End With
Application.ScreenUpdating = True
End Sub

POI XSSF overwriting specific cells in excel file

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

SetCellValue is not working for first row java

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);

Apache POI copy one row from Excel file to another new Excel File

I am using JAVA 8 and Apache POI 3.17. I have an Excel file and i want to keep only few lines and delete the others. But my Excel have 40K rows and deleting them one by one is quite long (nearly 30 min :/ )
So i try to change my way of doing it. Now i think it's better to only take rows that i need in the excel source and copy to another new one. But what i have tried so far is not efficient.
I have all my rows and want to keep in a List. But this not working and create me a blank excel :
public void createExcelFileFromLog (Path logRejetFilePath, Path fichierInterdits) throws IOException {
Map<Integer, Integer> mapLigneColonne = getRowAndColumnInError(logRejetFilePath);
Workbook sourceWorkbook = WorkbookFactory.create(new File(fichierInterdits.toAbsolutePath().toString()));
Sheet sourceSheet = sourceWorkbook.getSheetAt(0);
List<Row> listLignes = new ArrayList<Row>();
// get Rows from source Excel
for (Map.Entry<Integer, Integer> entry : mapLigneColonne.entrySet()) {
listLignes.add(sourceSheet.getRow(entry.getKey()-1));
}
// The new Excel
Workbook workbookToWrite = new XSSFWorkbook();
Sheet sheetToWrite = workbookToWrite.createSheet("Interdits en erreur");
// Copy Rows
Integer i = 0;
for (Row row : listLignes) {
copyRow(sheetToWrite, row, i);
i++;
}
FileOutputStream fos = new FileOutputStream(config.getDossierTemporaire() + "Interdits_en_erreur.xlsx");
workbookToWrite.write(fos);
workbookToWrite.close();
sourceWorkbook.close();
}
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
newRow = sourceRow;
}
EDIT : Change the method of copyRow it's better but the date have weird format and blank cells from the original row are gone.
private static void copyRow(Sheet newSheet, Row sourceRow, int newRowNum) {
Row newRow = newSheet.createRow(newRowNum);
Integer i = 0;
for (Cell cell : sourceRow) {
if(cell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(cell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(cell.getStringCellValue());
}
i++;
}
}
EDIT 2 : To keep blank cell
private static void copyRow(Sheet newSheet, Row sourceRow, Integer newRowNum, Integer cellToColor) {
Row newRow = newSheet.createRow(newRowNum);
//Integer i = 0;
int lastColumn = Math.max(sourceRow.getLastCellNum(), 0);
for(int i = 0; i < lastColumn; i++) {
Cell oldCell = sourceRow.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if(oldCell == null) {
newRow.createCell(i).setCellValue("");
} else if (oldCell.getCellTypeEnum() == CellType.NUMERIC) {
newRow.createCell(i).setCellValue(oldCell.getDateCellValue());
} else {
newRow.createCell(i).setCellValue(oldCell.getStringCellValue());
}
}
}

Categories

Resources