So im trying to first copy the pivot table as values,
the values are already inserted, but then when i want to insert a specific row, above the pivot table values, sheet.createrow(0) replaces the previous row i don't know why. here is my code
for (int iSheet = 0; iSheet < sheets; iSheet++) {
sheet = workbook.getSheetAt(iSheet);
if (sheet != null) {
mySheet = myWorkBook.createSheet(sheet.getSheetName());
mySheet.createRow(0); //creating the first row
fRow = sheet.getFirstRowNum();
lRow = sheet.getLastRowNum();
for (int iRow = fRow; iRow <= lRow; iRow++) {
row = sheet.getRow(iRow);
myRow = mySheet.createRow(iRow);
if (row != null) {
fCell = row.getFirstCellNum();
lCell = row.getLastCellNum();
for (int iCell = fCell; iCell < lCell; iCell++) {
cell = row.getCell(iCell);
myCell = myRow.createCell(iCell);
if (cell != null) {
myCell.setCellType(cell.getCellType());
switch (cell.getCellType()) {
case BLANK:
myCell.setCellValue("");
break;
case BOOLEAN:
myCell.setCellValue(cell.getBooleanCellValue());
break;
case ERROR:
myCell.setCellErrorValue(cell.getErrorCellValue());
break;
case FORMULA:
myCell.setCellFormula(cell.getCellFormula());
break;
case NUMERIC:
myCell.setCellValue(cell.getNumericCellValue());
break;
case STRING:
myCell.setCellValue(cell.getStringCellValue());
break;
default:
myCell.setCellFormula(cell.getCellFormula());
}
}
}
}
}
}
}
Related
I try to sort sheet with use of Apache POI by a given column. As I know there isn't any built-in solution for this purpose. First row of sheet contains merged cells and grouped columns. I try to sort cells by second column.
public static void sortSheet(XSSFWorkbook workbook, Sheet sheet) {
//copy all rows to temp
List<Row> rows = Lists.newArrayList(sheet.rowIterator());
//sort rows in the temp
rows.sort(Comparator.comparing(cells -> cells.getCell(2).getStringCellValue()));
//remove all rows from sheet
removeAllRows(sheet);
//create new rows with values of sorted rows from temp
for (int i = 0; i < rows.size(); i++) {
Row newRow = sheet.createRow(i);
Row sourceRow = rows.get(i);
// Loop through source columns to add to new row
for (int j = 0; j < sourceRow.getLastCellNum(); j++) {
// Grab a copy of the old/new cell
Cell oldCell = sourceRow.getCell(j);
Cell newCell = newRow.createCell(j);
// If the old cell is null jump to next cell
if (oldCell == null) {
newCell = null;
continue;
}
// Copy style from old cell and apply to new cell
CellStyle newCellStyle = workbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
newCell.setCellStyle(newCellStyle);
// If there is a cell comment, copy
if (oldCell.getCellComment() != null) {
newCell.setCellComment(oldCell.getCellComment());
}
// If there is a cell hyperlink, copy
if (oldCell.getHyperlink() != null) {
newCell.setHyperlink(oldCell.getHyperlink());
}
// Set the cell data type
newCell.setCellType(oldCell.getCellType());
// Set the cell data value
switch (oldCell.getCellType()) {
case BLANK:
newCell.setCellValue(oldCell.getStringCellValue());
break;
case BOOLEAN:
newCell.setCellValue(oldCell.getBooleanCellValue());
break;
case ERROR:
newCell.setCellErrorValue(oldCell.getErrorCellValue());
break;
case FORMULA:
newCell.setCellFormula(oldCell.getCellFormula());
break;
case NUMERIC:
newCell.setCellValue(oldCell.getNumericCellValue());
break;
case STRING:
newCell.setCellValue(oldCell.getRichStringCellValue());
break;
}
}
// If there are are any merged regions in the source row, copy to new row
for (int j = 0; j < sheet.getNumMergedRegions(); j++) {
CellRangeAddress cellRangeAddress = sheet.getMergedRegion(j);
if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),
(newRow.getRowNum() +
(cellRangeAddress.getLastRow() - cellRangeAddress.getFirstRow()
)),
cellRangeAddress.getFirstColumn(),
cellRangeAddress.getLastColumn());
sheet.addMergedRegion(newCellRangeAddress);
}
}
}
}
private static void removeAllRows(Sheet sheet) {
for (int i = 0; i < sheet.getLastRowNum(); i++) {
sheet.removeRow(sheet.getRow(i));
}
}
Original source: Apache-POI sorting rows in excel
I got following error message during execution:
org.apache.xmlbeans.impl.values.XmlValueDisconnectedException
at org.apache.xmlbeans.impl.values.XmlObjectBase.check_orphaned(XmlObjectBase.java:1258)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.impl.CTRowImpl.getR(Unknown Source)
at org.apache.poi.xssf.usermodel.XSSFRow.getRowNum(XSSFRow.java:378)
at WriteToExistingFile.sortSheet(WriteToExistingFile.java:234)
at WriteToExistingFile.write(WriteToExistingFile.java:145)
Exception is thrown at this line:
if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {
I am using POI to read excel file and convert it to a two-dimensional array. Following is code section:
import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XlsxRead_2 {
public XlsxRead_2(){
getvalue_1();
}
public static void getvalue_1(){
XSSFRow row;
XSSFCell cell;
String [][] value =null;
double[][] nums =null;
try {
FileInputStream inputStream = new FileInputStream("TEST.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
//get sheet number
int sheetCn = workbook.getNumberOfSheets();
for(int cn = 0; cn < sheetCn; cn++){
//get 0th sheet data
XSSFSheet sheet = workbook.getSheetAt(cn);
//get number of rows from sheet
int rows = sheet.getPhysicalNumberOfRows();
//get number of cell from row
int cells = sheet.getRow(cn).getPhysicalNumberOfCells();
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r); // bring row
if (row != null) {
for (int c = 0; c < cells; c++) {
cell = row.getCell(c);
value = new String[rows][cells];
nums= new double [rows][cells];
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
value [r][c]= cell.getCellFormula();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value [r][c]= "" + cell.getNumericCellValue();
break;
case XSSFCell.CELL_TYPE_STRING:
value [r][c]= "" + cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value [r][c]= "[BLANK]";
break;
case XSSFCell.CELL_TYPE_ERROR:
value [r][c]= "" + cell.getErrorCellValue();
break;
default:
}
System.out.print(value);
} else {
System.out.print("[null]\t");
}
} // for(c)
System.out.print("\n");
}
} // for(r)
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class Starter {
public static void main(String[] args) {
XlsxRead_2 gv=new XlsxRead_2();
}
}
However, it didn't work properly. Attached is wrong result in JAVA. When i worked it without using array, it work properly. Any suggestions is appreciated.
Result in java:
[[Ljava.lang.String;#167fdd33[[Ljava.lang.String;#1e965684
[[Ljava.lang.String;#4d95d2a2[[Ljava.lang.String;#53f65459
[[Ljava.lang.String;#3b088d51[[Ljava.lang.String;#1786dec2
[[Ljava.lang.String;#74650e52[[Ljava.lang.String;#15d0c81b
[[Ljava.lang.String;#6acdbdf5[[Ljava.lang.String;#4b1c1ea0
[[Ljava.lang.String;#3712b94[[Ljava.lang.String;#2833cc44
[[Ljava.lang.String;#33f88ab[[Ljava.lang.String;#27a8c74e
You should create array after first for loop. And also you should create values array for each sheet. And one more point you should print value[r][c] not value
I hope that helps you.
public class XlsxRead_2 {
public static void main(String[] args) {
XlsxRead_2 xread2 = new XlsxRead_2();
}
public XlsxRead_2() {
getvalue_1();
}
public static void getvalue_1() {
XSSFRow row;
XSSFCell cell;
String[][] value = null;
double[][] nums = null;
try {
FileInputStream inputStream = new FileInputStream("TEST.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// get sheet number
int sheetCn = workbook.getNumberOfSheets();
for (int cn = 0; cn < sheetCn; cn++) {
// get 0th sheet data
XSSFSheet sheet = workbook.getSheetAt(cn);
// get number of rows from sheet
int rows = sheet.getPhysicalNumberOfRows();
// get number of cell from row
int cells = sheet.getRow(cn).getPhysicalNumberOfCells();
value = new String[rows][cells];
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r); // bring row
if (row != null) {
for (int c = 0; c < cells; c++) {
cell = row.getCell(c);
nums = new double[rows][cells];
if (cell != null) {
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_FORMULA:
value[r][c] = cell.getCellFormula();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
value[r][c] = ""
+ cell.getNumericCellValue();
break;
case XSSFCell.CELL_TYPE_STRING:
value[r][c] = ""
+ cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value[r][c] = "[BLANK]";
break;
case XSSFCell.CELL_TYPE_ERROR:
value[r][c] = ""+cell.getErrorCellValue();
break;
default:
}
System.out.print(value[r][c]);
} else {
System.out.print("[null]\t");
}
} // for(c)
System.out.print("\n");
}
} // for(r)
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm trying to read the empty cells of an xls file and port them to my object xls as null entries. But I'm not identifying these cells as blank. Can someone can tell me what I'm doing wrong?
private boolean lerArquivo(String dir) throws IOException {
HSSFWorkbook wb = null;
HSSFRow row = null;
HSSFCell cell = null;
String path = dir;
boolean flag = false;
InputStream inp = new FileInputStream(path);
wb = new HSSFWorkbook(inp);
HSSFSheet sheet = wb.getSheetAt(0);
for (Iterator rit = (Iterator) sheet.rowIterator(); rit.hasNext();) {
row = (HSSFRow) rit.next();
for (Iterator cit = (Iterator) row.cellIterator(); cit.hasNext();) {
cell = (HSSFCell) cit.next();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
xls.add(cell.getRichStringCellValue().getString());
break;
case HSSFCell.CELL_TYPE_BLANK:
xls.add(null);
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
xls.add(cell.getDateCellValue().toString());
} else {
xls.add(String.valueOf(cell.getNumericCellValue()));
}
break;
default:
}
}
}
EDIT 01 -
Hello Gagravarr, thanks for your help.
I Tried your suggest, and read the documentation.
following what i understood, i changed my code, reaching this:
even this way, the code isn't reading the blank cell. any guess ?
for (int rowNum = 0; rowNum < 4; rowNum++) {
row = sheet.getRow(rowNum);
for (int celNum = 0; celNum < row.getLastCellNum(); celNum++) {
cell = row.getCell(celNum, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
xls.add(cell.getRichStringCellValue().getString());
break;
case HSSFCell.CELL_TYPE_BLANK: {
xls.add("");
break;
}
case HSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
xls.add(cell.getDateCellValue().toString());
} else {
xls.add(String.valueOf(cell.getNumericCellValue()));
}
break;
default:
}
}
}
Apache POI has pretty detailed and explicit documentation on iterating over rows and cells, you'd be very well advised to read it!
Copying and pasting the example from there, you can see how to handle / detect missing rows and cells, along with blank cells:
// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// The spreadsheet is empty in this cell
} else {
// Do something useful with the cell's contents
}
}
}
Ok so I know you have to add the autoSizeColumns() method after you enter all your data into the sheet and workbook. And that is what I am doing but it is only resizing to the width of the last Cell entered??
public void writeFile() {
Workbook wb = new HSSFWorkbook();
Sheet s = wb.createSheet();
try {
FileOutputStream out = new FileOutputStream(
this.getSelectedFile());
// create a new workbook
// create a new sheet
// declare a row object reference
Row r = null;
// declare a cell object reference
Cell c = null;
// in case of plain ascii
wb.setSheetName(0, "Street Light Report");
// create a sheet with 30 rows (0-29)
// int rownum;
// short rownum;
// PrintWriter printOut = new PrintWriter(
// this.getSelectedFile());
String[] colName = { "Light Id", "Flagged",
"Malfunction", "Comments", "Location", "Date" };
// printOut.println("Light Id,Flagged,Malfunction,Comments,Location,Date");
Connections.connect();
String[][] data = Connections.searchForFlagged();
for (int i = 0; i < data.length; i++) {
r = s.createRow(i);
}
r.setRowNum(0);
for (int j = 0; j < 6; j++) {
c = r.createCell(j);
switch (j) {
case 0:
c.setCellValue(colName[j]);
break;
case 1:
c.setCellValue(colName[j]);
break;
case 2:
c.setCellValue(colName[j]);
break;
case 3:
c.setCellValue(colName[j]);
break;
case 4:
c.setCellValue(colName[j]);
break;
case 5:
c.setCellValue(colName[j]);
break;
}
}
for (int i = 0; i < data.length; i++) {
r.setRowNum(i + 1);
for (int j = 0; j < data[i].length; j++) {
c = r.createCell(j);
// System.out.println(data[i][j]);
switch (j) {
case 0:
c.setCellType(Cell.CELL_TYPE_NUMERIC);
c.setCellValue(Integer.parseInt(data[i][j]));
break;
case 1:
if (data[i][j].equals("true"))
c.setCellValue("Yes");
else
c.setCellValue("No");
break;
case 2:
if (data[i][j].equals("I"))
c.setCellValue("Intermittent");
else
c.setCellValue("Not Functional");
break;
case 3:
c.setCellValue(data[i][j]);
break;
case 4:
c.setCellValue(data[i][j]);
break;
case 5:
c.setCellValue(data[i][j]);
break;
}
}
}
wb.getSheetAt(0).setPrintGridlines(true);
for (int j = 0; j < 6; j++) {
s.autoSizeColumn(j);
}
wb.write(out);
out.close();
} catch (Exception ex) {
}
};
It seems that you do not have too many columns. Can you try defining each column like this:
sheet.autoColumnWidth(column number); //0 for the first column, 1 for the second, etc.
If that works then there is something wrong with your loop.
I'm trying to find a blank value in excel (xlsx) sheet and replace with some string like "ENTER VALUE" using my program with Apache POI library as below
I'm able to read and identify blank/null values in excel sheet but couldnt insert any value into those cells
public static void main(String args[]) throws IOException, InvalidFormatException
{
FileInputStream inputFile = new FileInputStream("//Users//suk//Documents/tes//testexcel.xlsx");
//now initializing the Workbook with this inputFie
// Create workbook using WorkbookFactory util method
Workbook wb = WorkbookFactory.create(inputFile);
// creating helper for writing cells
CreationHelper createHelper = wb.getCreationHelper();
// setting the workbook to handle null
wb.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
int lastCellNo =row.getLastCellNum();
int firstCellNo=row.getFirstCellNum();
int rowNo =row.getRowNum();
System.out.println(" row number = "+rowNo);
System.out.println(" last cell no = "+lastCellNo);
for(int i=firstCellNo;i<lastCellNo;i++){
System.out.println("************");
Cell cell = row.getCell(i);
int colIndex =cell.getColumnIndex();
if(cell==null)
{
System.out.println(" The Cell:"+colIndex+" for row "+row.getRowNum()+" is NULL");
}
System.out.println(" column index = "+colIndex);
int cellType = cell.getCellType();
System.out.println(" cell type ="+cellType);
// writing a switch case statement
switch(cellType)
{
case 0:
{
double numValue = cell.getNumericCellValue();
//System.out.println(numValue);
break;
}
case 1:
{
String cellString = cell.getStringCellValue();
System.out.println("----String value = "+cellString+"---String length ="+cellString.length());
// here checking null consition
/* if(cellString == null || cellString.equalsIgnoreCase("") || cellString.length()<=0 || cellString.equalsIgnoreCase(" "))
{
// here creating the cell value after last cell
} */
break;
}
case 4:
{
boolean bolValue =cell.getBooleanCellValue();
//System.out.println(bolValue);
break;
}
// for case of blank cell
case 3:
{
//int lastCellPlus =lastCellNo+1;
//System.out.println("last+1 column ="+lastCellPlus);
//row.createCell(lastCellPlus).setCellValue(" NULL VALUE..PLEASE ENTER VALUE ");
System.out.println(" cell details = "+cell.getColumnIndex()+" row details ="+row.getRowNum());
cell.setCellValue(createHelper.createRichTextString("ENTER VALUE"));
System.out.println(" Sucessfully written error");
break;
}
default:
System.out.println(" unknown format");
break;
}// switch
} // row and cell iterator
}
}
}
Below is the bit of code by which im identifying its Blank/Null value and trying to insert String but its not writing to that cell
case 3:
{
//int lastCellPlus =lastCellNo+1;
//System.out.println("last+1 column ="+lastCellPlus);
//row.createCell(lastCellPlus).setCellValue(" NULL VALUE..PLEASE ENTER VALUE ");
System.out.println(" cell details = "+cell.getColumnIndex()+" row details ="+row.getRowNum());
cell.setCellValue(createHelper.createRichTextString("ENTER VALUE"));
System.out.println(" Sucessfully written error");
break;
}
if(row.getCell(0))==null || getCellValue(row.getCell(0)).trim().isEmpty()){
cell.setCellValue("ENTER VALUE");
}
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + "";
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + "";
}
else {
return null;
}
}
This should work fine:
Sheet s = wb.getSheetAt(0);
for (int rn=0; rn<s.getLastRowNum(); rn++) {
Row r = s.getRow(rn);
if (r == null) {
// No values exist in this row
r = s.createRow(rn);
}
int minColumnsPerRow=10; // Fix for your needs
for (int cn=0; cn<minColumnsPerRow; cn++) {
Cell c = r.getCell(cn);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// This cell is empty
if (c == null) {
c = r.createCell(cn, Cell.CELL_TYPE_STRING);
}
cell.setCellValue(createHelper.createRichTextString("ENTER VALUE"));
}
}
}
Remember that cells can be blank or null (never used), and rows can be null (never used)