Apache poi + Java: Write to a worksheet without deleting existing data - java

I need to check if the worksheet exists.
If it exists, you must type in the next existing row and do not create a new worksheet.
You are currently deleting the current spreadsheet and I always get only 1 line written in the spreadsheet.
How do I solve this?
public class ApachePOIExcelWrite {
private static final String FILE_NAME = "c:/viagem.xlsx";
XSSFWorkbook workbook = new XSSFWorkbook();
//name Sheet
XSSFSheet sheet = workbook.createSheet("Viagem");
Object[][] datatypes = {
//head colums
{
"Destino",
"Valor por pessoa",
"Aeroporto",
"Hotel",
"data Pesquisa",
"Hora Pesquisa"
},
{
destino,
pega_valor,
aeroporto.replace("GRU", "Guarulhos").replace("CGH", "Congonhas"),
hotel.replaceAll("Pontos", "Estrelas"),
data_da_pesquisa.format(d),
hora_da_pesquisa.format(d)
}
};
int rowNum = 0;
System.out.println("Creating excel");
for (Object[] datatype: datatypes) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field: datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
try {
FileOutputStream outputStream = new FileOutputStream(FILE_NAME);
workbook.write(outputStream);
workbook.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* Opens an existing sheet or creates a new one if the given sheet name doesn't exist.
* Appends values after the last existing row.
*/
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook("C:\\Users\\Administrator\\Desktop\\test.xlsx");
Sheet sheet = workbook.getSheet("Sheet1");
if (sheet == null)
sheet = workbook.createSheet("Sheet1");
Object[][] values = {{"A2", "B2", "C2"}, {"A3","B3","C3","D3"}};
int initRow = sheet.getLastRowNum() + 1;
int initCol = 0;
for (int i = 0; i < values.length; i++) {
Object[] rowValues = values[i];
for (int j = 0; j < rowValues.length; j++) {
Object value = rowValues[j];
writeValueToCell(value, initRow + i, initCol + j, sheet);
}
}
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\output.xlsx");
workbook.write(fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void writeValueToCell(Object value, int rowIdx, int colIdx, Sheet sheet) {
Row row = sheet.getRow(rowIdx);
Cell cell;
if (row == null) {
cell = sheet.createRow(rowIdx).createCell(colIdx);
} else {
cell = row.getCell(colIdx);
if (cell == null)
cell = row.createCell(colIdx);
}
if (value == null)
cell.setCellType(Cell.CELL_TYPE_BLANK);
else if (value instanceof String)
cell.setCellValue(value.toString());
else if (value instanceof Integer)
cell.setCellValue((Integer) value);
else if (value instanceof Double)
cell.setCellValue((Double) value);
else if (value instanceof Date) {
cell.setCellValue((Date) value);
CellStyle style = sheet.getWorkbook().createCellStyle();
style.setDataFormat(sheet.getWorkbook().getCreationHelper().createDataFormat().getFormat(("yyyy/m/d")));
cell.setCellStyle(style);
} else {
cell.setCellValue("Unknown type");
}
}

Related

I am facing problem at cell iterator and blank cell type in excel sheet. how to handle the blank cells and blank columns adjustment dynamically

In Java, how do I handle the blank cells in excel sheet and blank columns adjustment dynamically.
I am facing problem at cell iterator and blank cell type.
When I am creating dynamic queries for postgresql db, at insert query I am getting exceptions because of blank case in excel. I am trying to work with poi getting exception at blank case.
Excel image
try {
DataFormatter dataFormatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(excelFile);
Iterator<Sheet> sheetIterator = workbook.sheetIterator();
List<List<List<Object>>> sheets = new ArrayList<>();
while (sheetIterator.hasNext()) {
List<List<Object>> sheetList = new ArrayList<>();
Sheet sheet = sheetIterator.next();
logger.info(" ---sheet name ---" + sheet.getSheetName());
if (sheetNames != null) {
for (String sheetName : sheetNames) {
if (sheet.getSheetName().equals(sheetName)) {
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Object> rows = new ArrayList<>();
// Now let's iterate over the columns of the current row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellType type = cell.getCellType();
if (type == CellType.BLANK) {
Integer intsample = 0;
cell.setCellValue(intsample);
// rows.add(dataFormatter.formatCellValue(cell));
rows.add(cell);
}
else if (type == CellType.STRING) {
rows.add(cell.getRichStringCellValue().toString());
} else if (type == CellType.NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
rows.add(cell.getDateCellValue());
} else if (dataFormatter.formatCellValue(cell).contains(".")) {
try {
rows.add(Double.parseDouble(dataFormatter.formatCellValue(cell)));
} catch (Exception e) {
rows.add(cell.getRichStringCellValue().toString());
}
} else {
try {
rows.add(Long.parseLong(dataFormatter.formatCellValue(cell)));
} catch (Exception e) {
rows.add(dataFormatter.formatCellValue(cell));
}
}
} else if (type == CellType.BOOLEAN) {
rows.add(cell.getBooleanCellValue());
} else {
rows.add(dataFormatter.formatCellValue(cell));
}
}
sheetList.add(rows);
}
sheets.add(sheetList);
}
}
}
}
workbook.close();
return sheets;
} catch (Exception e) {
e.printStackTrace();
}
The CellIterator skips empty cells when it iterates the cells in a row. You could work around the problem by using a for loop instead of an iterator:
Row row = rowIterator.next();
...
int lastCellIndex = 8; // (9-1 cells)
for (int i=0; i<=lastCellIndex; i++) {
Cell cell = row.getCell(cn, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
...
}
The number of cells is 9 in your example, making the lastCellIndex 8. If the number of cells in a row would vary, use row.getLastCellNum(); on the top header row to receive the length.
More info on getCell() can be found in the documentation.
I am trying like with out using celliterator,rowiterator,sheetiterator.but again skipping cell is happen ...
here is my code
try {
DataFormatter dataFormatter = new DataFormatter();
Workbook workbook = WorkbookFactory.create(file);
List<List<List<Object>>> sheets = new ArrayList<List<List<Object>>>();
for (int sh = 0; sh < workbook.getNumberOfSheets(); sh++) {
Sheet sheet = workbook.getSheetAt(sh);
List<List<Object>> sheetList = new ArrayList<List<Object>>();
for (int i = 0; i < sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
List<Object> rows = new ArrayList<Object>();
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
CellType type = cell.getCellType();
// System.out.println(type+ " -----type -------");
if (type == CellType.STRING) {
rows.add(cell.getRichStringCellValue().toString());
} else if (type == CellType.NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
rows.add(cell.getDateCellValue());
} else if (dataFormatter.formatCellValue(cell).contains(".")) {
try {
rows.add(Double.parseDouble(dataFormatter.formatCellValue(cell)));
} catch (Exception e) {
rows.add(cell.getRichStringCellValue().toString());
}
} else {
try {
rows.add(Long.parseLong(dataFormatter.formatCellValue(cell)));
} catch (Exception e) {
rows.add(dataFormatter.formatCellValue(cell));
}
}
} else if (type == CellType.BOOLEAN) {
rows.add(cell.getBooleanCellValue());
} else if (type == CellType.BLANK) {
cell.setCellValue("NA");
//System.out.println(cell);
//Cell cell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Integer intsample = 0;
//cell.setCellValue(intsample);
// rows.add(dataFormatter.formatCellValue(cell));
rows.add(cell);
} else {
rows.add(dataFormatter.formatCellValue(cell));
}
}
sheetList.add(rows);
System.out.println(rows);
}
sheets.add(sheetList);
// System.out.println(sheets+"\n");
}
workbook.close();
return sheets;
} catch (Exception e) {
e.printStackTrace();
}

Write multiple data in excel file having column name TestCol and TestCol1 in selenium webdriver with java

I want to write multiple data in excel with column name like TestCol and TestCol1.
Same data store in excel, now want to read either TestCol or TestCol1.
Xls_reader reader = new Xls_reader();
reader.Xls_Reader("C:uat\testdata\FreeCMSTestData.xlsx");
reader.addSheet("TestData");
reader.addColumn("TestData", "TestCol");
reader.addColumn("TestData", "TestCol1");
int n=3;
for(int i=2;i<n;i++)
{
reader.setCellData("TestData", "TestCol", i, str1);
reader.setCellData("TestData", "TestCol1", i, part);
}
Now, Data is not going in respective Column one below the other instead it get add to the adjacent.
public class Xls_reader {
public String path;
public FileInputStream fis = null;
public FileOutputStream fileOut = null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row = null;
private XSSFCell cell = null;
public void Xls_Reader(String path) {
this.path = path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// returns the row count in a sheet
public int getRowCount(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return 0;
else {
sheet = workbook.getSheetAt(index);
int number = sheet.getLastRowNum() + 1;
return number;
}
}
// returns the data from a cell
public String getCellData(String sheetName, String colName, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
int col_Num = -1;
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName.trim()))
col_Num = i;
}
if (col_Num == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum - 1);
if (row == null)
return "";
cell = row.getCell(col_Num);
if (cell == null)
return "";
// System.out.println(cell.getCellType());
if (cell.getCellType() == Cell.CELL_TYPE_STRING)
return cell.getStringCellValue();
else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC || cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal = Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.DAY_OF_MONTH) + "/" + cal.get(Calendar.MONTH) + 1 + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
} catch (Exception e) {
e.printStackTrace();
return "row " + rowNum + " or column " + colName + " does not exist in xls";
}
}
// returns the data from a cell
public String getCellData(String sheetName, int colNum, int rowNum) {
try {
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(rowNum - 1);
if (row == null)
return "";
cell = row.getCell(colNum);
if (cell == null)
return "";
if (cell.getCellType() == Cell.CELL_TYPE_STRING)
return cell.getStringCellValue();
else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC || cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
String cellText = String.valueOf(cell.getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(cell)) {
// format in form of M/D/YY
double d = cell.getNumericCellValue();
Calendar cal = Calendar.getInstance();
cal.setTime(HSSFDateUtil.getJavaDate(d));
cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2);
cellText = cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText;
// System.out.println(cellText);
}
return cellText;
} else if (cell.getCellType() == Cell.CELL_TYPE_BLANK)
return "";
else
return String.valueOf(cell.getBooleanCellValue());
} catch (Exception e) {
e.printStackTrace();
return "row " + rowNum + " or column " + colNum + " does not exist in xls";
}
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName, String colName, int rowNum, String data) {
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return false;
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if (colNum == -1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
// cell style
// CellStyle cs = workbook.createCellStyle();
// cs.setWrapText(true);
// cell.setCellStyle(cs);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if data is set successfully else false
public boolean setCellData(String sheetName, String colName, int rowNum, String data, String url) {
// System.out.println("setCellData setCellData******************");
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return false;
sheet = workbook.getSheetAt(index);
// System.out.println("A");
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum = i;
}
if (colNum == -1)
return false;
sheet.autoSizeColumn(colNum); // ashish
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
// cell style for hyperlinks
// by default hypelrinks are blue and underlined
CellStyle hlink_style = workbook.createCellStyle();
XSSFFont hlink_font = workbook.createFont();
hlink_font.setUnderline(XSSFFont.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
// hlink_style.setWrapText(true);
XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
link.setAddress(url);
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is created successfully else false
public boolean addSheet(String sheetname) {
FileOutputStream fileOut;
try {
workbook.createSheet(sheetname);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if sheet is removed successfully else false if sheet does
// not exist
public boolean removeSheet(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return false;
FileOutputStream fileOut;
try {
workbook.removeSheetAt(index);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// returns true if column is created successfully
public boolean addColumn(String sheetName, String colName) {
// System.out.println("**************addColumn*********************");
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
int index = workbook.getSheetIndex(sheetName);
if (index == -1)
return false;
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
if (row == null)
row = sheet.createRow(0);
// cell = row.getCell();
// if (cell == null)
// System.out.println(row.getLastCellNum());
if (row.getLastCellNum() == -1)
cell = row.createCell(0);
else
cell = row.createCell(row.getLastCellNum());
cell.setCellValue(colName);
cell.setCellStyle(style);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// removes a column and all the contents
public boolean removeColumn(String sheetName, int colNum) {
try {
if (!isSheetExist(sheetName))
return false;
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheet(sheetName);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
style.setFillPattern(HSSFCellStyle.NO_FILL);
for (int i = 0; i < getRowCount(sheetName); i++) {
row = sheet.getRow(i);
if (row != null) {
cell = row.getCell(colNum);
if (cell != null) {
cell.setCellStyle(style);
row.removeCell(cell);
}
}
}
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
// find whether sheets exists
public boolean isSheetExist(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if (index == -1) {
index = workbook.getSheetIndex(sheetName.toUpperCase());
if (index == -1)
return false;
else
return true;
} else
return true;
}
// returns number of columns in a sheet
public int getColumnCount(String sheetName) {
// check if sheet exists
if (!isSheetExist(sheetName))
return -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
if (row == null)
return -1;
return row.getLastCellNum();
}
// String sheetName, String testCaseName,String keyword ,String URL,String
// message
public boolean addHyperLink(String sheetName, String screenShotColName, String testCaseName, int index, String url,
String message) {
// System.out.println("ADDING addHyperLink******************");
url = url.replace('\\', '/');
if (!isSheetExist(sheetName))
return false;
sheet = workbook.getSheet(sheetName);
for (int i = 2; i <= getRowCount(sheetName); i++) {
if (getCellData(sheetName, 0, i).equalsIgnoreCase(testCaseName)) {
// System.out.println("**caught "+(i+index));
setCellData(sheetName, screenShotColName, i + index, message, url);
break;
}
}
return true;
}
public int getCellRowNum(String sheetName, String colName, String cellValue) {
for (int i = 2; i <= getRowCount(sheetName); i++) {
if (getCellData(sheetName, colName, i).equalsIgnoreCase(cellValue)) {
return i;
}
}
return -1;
}

poi java code to merge cells based on common data

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.

Create Multiple Sheet in jExcel API

I need to create multiple excel sheet in Java using jExcel API if one sheet is full (65536 rows). Suppose if one sheet got full then in the next sheet it should start writing automatically from where it left off in the first sheet. I am just stuck on putting the logic to create it dynamically whenever one sheet is full. Below is the code that I have done so far.
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
writingToExcel(workbook);
}
//Logic to create sheet dyanmically if one is full should be done here I guess?
private void writingToExcel(WritableWorkbook workbook) {
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
try {
createLabel(excelSheet);
createContent(excelSheet);
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
private void createLabel(WritableSheet sheet) throws WriteException {
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
times = new WritableCellFormat(times10pt);
times.setWrap(true);
WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
cv.setFormat(timesBoldUnderline);
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "Header 1");
addCaption(sheet, 1, 0, "This is another header");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
for (int i = 1; i < 70000; i++) {
addNumber(sheet, 0, i, i + 10);
addNumber(sheet, 1, i, i * i);
}
}
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
I am not sure how to add that logic here in my code.
Any suggestions will be of great help?
Or in any case, can anyone provide me a simple example in which if one sheet is full, it should start writing automatically into different sheet (Second sheet)?
I made changes to the following 2 methods:-
private void writingToExcel(WritableWorkbook workbook) {
try {
// don't create a sheet now, instead, pass it in the workbook
createContent(workbook);
}
catch (WriteException e) {
e.printStackTrace();
}
finally {
try {
workbook.write();
workbook.close();
}
catch (IOException e) {
e.printStackTrace();
}
catch (WriteException e) {
e.printStackTrace();
}
}
}
// instead of taking a sheet, take a workbook because we cannot ensure if the sheet can fit all the content at this point
private void createContent(WritableWorkbook workbook) throws WriteException {
int excelSheetIndex = 0;
int rowIndex = 0;
WritableSheet excelSheet = null;
for (int i = 1; i < 70000; i++) {
// if the sheet has hit the cap, then create a new sheet, new label row and reset the row count
if (excelSheet == null || excelSheet.getRows() == 65536) {
excelSheet = workbook.createSheet("Report " + excelSheetIndex, excelSheetIndex++);
createLabel(excelSheet);
rowIndex = 0;
}
// instead of using i for row, use rowIndex
addNumber(excelSheet, 0, rowIndex, i + 10);
addNumber(excelSheet, 1, rowIndex, i * i);
// increment the sheet row
rowIndex++;
}
}
public class DscMigration {
private WritableCellFormat timesBoldUnderline;
private WritableCellFormat times;
private String inputFile;
public void setOutputFile(String inputFile) {
this.inputFile = inputFile;
}
public void write() throws IOException, WriteException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
workbook.createSheet("Report", 0);
WritableSheet excelSheet = workbook.getSheet(0);
createLabel(excelSheet);
createContent(excelSheet);
workbook.write();
workbook.close();
}
private void createLabel(WritableSheet sheet) throws WriteException {
// Lets create a times font
WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
// Define the cell format
times = new WritableCellFormat(times10pt);
// Lets automatically wrap the cells
times.setWrap(true);
// Create create a bold font with unterlines
WritableFont times10ptBoldUnderline = new WritableFont(
WritableFont.TIMES, 10, WritableFont.BOLD, false,
UnderlineStyle.SINGLE);
timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
// Lets automatically wrap the cells
timesBoldUnderline.setWrap(true);
CellView cv = new CellView();
cv.setFormat(times);
// cv.setFormat(timesBoldUnderline);
// cv.setFormat(cf)
cv.setAutosize(true);
// Write a few headers
addCaption(sheet, 0, 0, "COM_ID");
addCaption(sheet, 1, 0, "OBJECTID");
addCaption(sheet, 2, 0, "GNOSISID");
}
private void createContent(WritableSheet sheet) throws WriteException,
RowsExceededException {
/**
* Create a new instance for cellDataList
*/
List<DataObj> cellDataListA = new ArrayList<DataObj>();
List<DataObj> nonDuplicateA = new ArrayList<DataObj>();
List<DataObj2> cellDataListB = new ArrayList<DataObj2>();
List<DataObj2> nonDuplicateB = new ArrayList<DataObj2>();
List<DataObj> nonDuplicateAB = new ArrayList<DataObj>();
List<DataObj> misMatchAB = new ArrayList<DataObj>();
List<DataObj> copyA = new ArrayList<DataObj>();
List<DataObj2> comID = new ArrayList<DataObj2>();
try {
/**
* Create a new instance for FileInputStream class
*/
// input1--> col1 -livelink id ; col2->livlink filename; col3-> gnosis id; col4-> filename
FileInputStream fileInputStream = new FileInputStream(
"C:/Documents and Settings/nithya/Desktop/DSC/Report/input1.xls");
//input2 --> col1 comid all, col2 -> object id for common
FileInputStream fileInputStream2 = new FileInputStream(
"C:/Documents and Settings/nithya/Desktop/DSC/Report/input2.xls");
/**
* Create a new instance for POIFSFileSystem class
*/
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
POIFSFileSystem fsFileSystem2 = new POIFSFileSystem(fileInputStream2);
/*
* Create a new instance for HSSFWorkBook Class
*/
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
HSSFWorkbook workBook2 = new HSSFWorkbook(fsFileSystem2);
HSSFSheet hssfSheet2 = workBook2.getSheetAt(0);
/**
* Iterate the rows and cells of the spreadsheet to get all the
* datas.
*/
Iterator rowIterator = hssfSheet.rowIterator();
Iterator rowIterator2 = hssfSheet2.rowIterator();
while (rowIterator.hasNext()) {
HSSFRow hssfRow = (HSSFRow) rowIterator.next();
if ((hssfRow.getCell((short) 0) != null)
&& (hssfRow.getCell((short) 1) != null)) {
cellDataListA.add(new DataObj(hssfRow.getCell((short) 0)
.toString().trim(), hssfRow.getCell((short) 1)
.toString().trim()));
}
if ((hssfRow.getCell((short) 2) != null)
&& (hssfRow.getCell((short) 3) != null)) {
cellDataListB.add(new DataObj2(hssfRow.getCell((short) 2)
.toString().trim(), hssfRow.getCell((short) 3)
.toString().trim()));
}
}
// Replace Duplicate in Livelink Startd
Set set = new HashSet();
List newList = new ArrayList();
nonDuplicateA.addAll(cellDataListA);
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj b = nonDuplicateA.get(i);
if (set.add(b.getCol1()))
newList.add(nonDuplicateA.get(i));
}
nonDuplicateA.clear();
nonDuplicateA.addAll(newList);
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
}
System.out.println("nonDuplicateA=="+nonDuplicateA.size());
// Replace Duplicate in Livelink End
// Replace Duplicate in Gnosis Startd
Set set2 = new HashSet();
List newList2 = new ArrayList();
System.out.println("cellDataListB=="+cellDataListB.size());
nonDuplicateB.addAll(cellDataListB);
for (int i = 0; i < nonDuplicateB.size(); i++) {
DataObj2 b = nonDuplicateB.get(i);
if (set2.add(b.getCol1()))
newList2.add(nonDuplicateB.get(i));
}
nonDuplicateB.clear();
nonDuplicateB.addAll(newList2);
System.out.println("nonDuplicateB=="+nonDuplicateB.size());
// Replace Duplicate in Gnosis End
// Common record
//System.out.println("------Common----");
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
for (int j = 0; j < nonDuplicateB.size(); j++) {
DataObj2 b = nonDuplicateB.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
//System.out.println("---------");
if (a.getCol2().equalsIgnoreCase(b.getCol2())) {
// System.out.println(a.getCol2() +"--"+i+"--"+b.getCol2());
nonDuplicateAB.add(new DataObj(a.getCol1().toString()
.trim(), b.getCol1().toString().trim()));
//addLabel(sheet, 0, i, a.getCol1().toString().trim());
// addLabel(sheet, 1, i, b.getCol1().toString().trim());
break;
}
}
}
}
System.out.println("nonDuplicateAB=="+nonDuplicateAB.size());
TreeMap misA = new TreeMap();
//System.out.println("------Missing----");
for (int i = 0; i < nonDuplicateA.size(); i++) {
DataObj a = nonDuplicateA.get(i);
for (int j = 0; j < nonDuplicateB.size(); j++) {
DataObj2 b = nonDuplicateB.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
if (!(a.getCol2().equals(b.getCol2()))) {
//System.out.println(a.getCol1() +"="+b.getCol1());
//break;
if(misA.containsValue(a.getCol2())){
misA.remove(a.getCol1());
}
else
{
misA.put(a.getCol1(), a.getCol2());
}
}
}
}
}
//System.out.println("SIze mis="+misA);
TreeMap misB = new TreeMap();
for (int i = 0; i < nonDuplicateB.size(); i++) {
DataObj2 a = nonDuplicateB.get(i);
for (int j = 0; j < nonDuplicateA.size(); j++) {
DataObj b = nonDuplicateA.get(j);
if((a.getCol2()!=null && b.getCol2()!=null )){
if (!(a.getCol2().equals(b.getCol2()))) {
//System.out.println(a.getCol1() +"="+b.getCol1());
if(misB.containsValue(a.getCol2())){
misB.remove(a.getCol1());
}
else
{
misB.put(a.getCol1(), a.getCol2());
}
}
}
}
}
// System.out.println("SIze misB="+misB);
//Getting ComID and Object Id from excel start
while (rowIterator2.hasNext()) {
HSSFRow hssfRow2 = (HSSFRow) rowIterator2.next();
if ((hssfRow2.getCell((short) 0) != null)
&& (hssfRow2.getCell((short) 1) != null)) {
comID.add(new DataObj2(hssfRow2.getCell((short) 0)
.toString().trim(), hssfRow2.getCell((short) 1)
.toString().trim()));
}
}
System.out.println("Size ComID="+comID.size());
TreeMap hm = new TreeMap();
System.out.println("Please wait...Data comparison.. ");
for (int i = 0; i < nonDuplicateAB.size(); i++) {
DataObj a = nonDuplicateAB.get(i);
for(int j=0;j<comID.size();j++ ){
DataObj2 b = comID.get(j);
//System.out.println((b.getCol2()+"---"+a.getCol1()));
if(b.getCol2().equalsIgnoreCase(a.getCol1())){
hm.put(b.getCol1(), b.getCol2());
break;
}
}
}
System.out.println("Size HM="+hm.size());
//Getting ComID and Object Id from excel End
//Data Base Updation
Connection conn = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#cxxxxx:5487:dev", "",
"");
System.out.println("after calling conn");
Set set6 = hm.entrySet();
Iterator i = set6.iterator();
String gnosisNodeId="";
int update=1;
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
//System.out.print(me.getKey() + ": ");
//System.out.println(me.getValue());
// System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
for(int m=0;m<nonDuplicateAB.size();m++){
DataObj a = nonDuplicateAB.get(m);
if(me.getValue().toString().equalsIgnoreCase(a.getCol1())){
gnosisNodeId=a.getCol2().toString();
nonDuplicateAB.remove(m);
break;
}
}
//System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
if(gnosisNodeId!=null){
//System.out.println("LOOP");
String s1="UPDATE component SET com_xml = UPDATEXML(com_xml, '*/url/value/text()', '";
String s2="http://dmfwebtop65.pfizer.com/webtop/drl/objectId/"+gnosisNodeId;
String s3="') where com_id="+me.getKey().toString().substring(1)+"";
Statement stmt1=null;
//http://dmfwebtop65.pfizer.com/webtop/drl/objectId/0901201b8239cefb
try {
String updateString1 = s1+s2+s3;
stmt1 = conn.createStatement();
int rows =stmt1.executeUpdate(updateString1);
if (rows>0) {
addLabel(sheet, 0, update, me.getKey().toString().substring(1));
addLabel(sheet, 1, update, me.getValue().toString().substring(1));
addLabel(sheet, 2, update,gnosisNodeId );
update++;
System.out.println("Update Success="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
}
else
{
System.out.println("Not Updated="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
}
} catch (SQLException e) {
System.out.println("No Connect" + e);
} catch (Exception e) {
System.out.println("Error "+e.getMessage());
}
}
else{System.out.println("No gnosis id found for ObjectID="+me.getKey().toString().substring(1)); }
}//While
} //try
catch (Exception e) {
e.printStackTrace();
}
}//Main try
catch (Exception e) {
e.printStackTrace();
}
} //method
private void addCaption(WritableSheet sheet, int column, int row, String s)
throws RowsExceededException, WriteException {
Label label;
label = new Label(column, row, s, timesBoldUnderline);
sheet.addCell(label);
}
private void addNumber(WritableSheet sheet, int column, int row,
Integer integer) throws WriteException, RowsExceededException {
Number number;
number = new Number(column, row, integer, times);
sheet.addCell(number);
}
private void addLabel(WritableSheet sheet, int column, int row, String s)
throws WriteException, RowsExceededException {
Label label;
label = new Label(column, row, s, times);
sheet.addCell(label);
}
public static void main(String[] args) throws WriteException, IOException {
DscMigration test = new DscMigration();
test.setOutputFile("C:/Documents and Settings/nithya/Desktop/DSC/Report/Mapping.xls");
test.write();
System.out
.println("Please check the result file under C:/Documents and Settings/nithya/Desktop/DSC/Report/Report.xls ");
}
}
XXXXInternal Use
Based on WTTE-0043 ELC Maintenance Release and Bug Fix Plan Template
Version 4.0 Effective Date: 01-Jul-2010
//Bug Fix Plan
Author:
1 Approval Signatures
Table of Contents
I have authored this deliverable to document the plan for executing a maintenance release or bug fix to project.
NAME DATE
I have authored this deliverable to document the plan for executing a maintenance release or bug fix to XXX Plus v4.5.
NAME DATE
I approve this change and agree that this record represents the accurate and complete plan for executing the maintenance release or bug fix, and fully supports the implementation, testing and release activities for this project.
NAME DATE
I have reviewed the content of this record and found that it meets the applicable BT compliance requirements.
NAME DATE
Signatures
2 Introduction
This project deliverable documents the requested change, planned approach, development solution, test plan, test results and release approval for a maintenance release or and bug fix to project.
3 Change Request
Requestor Name:
XX
Object/
System Name:
project
Priority (High/Medium/Low):
High
Change Request No.:
NA
Change Request Date:
22-NOV-2011
Description of Problem or Requested Change:
Estimated Development Time Needed:
1 day (approx.)
4)4 Maintenance Release and Bug Fix Approach
5 Development Solution
8 Supporting References
9 Revision History

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

i'm using Apache POI(XSSF API) for reading xlsx file.when i tried to read file.i got the following error:
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]
Code:
public class ReadXLSX
{
private String filepath;
private XSSFWorkbook workbook;
private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String FilePath)
{
logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath=FilePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream)
{
logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream=fileStream;
}
private void loadFile() throws FileNotFoundException, NullObjectFoundException
{
if(resourceAsStream==null)
throw new FileNotFoundException("Unable to locate give file..");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
}
catch(IOException ex)
{
}
}
}// end loadxlsFile
public String[] getSheetsName()
{
int totalsheet=0;int i=0;
String[] sheetName=null;
try {
loadFile();
totalsheet=workbook.getNumberOfSheets();
sheetName=new String[totalsheet];
while(i<totalsheet)
{
sheetName[i]=workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
logger.error(ex);
} catch (NullObjectFoundException ex) {
logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex()
{
int totalsheet=0;int i=0;
int[] sheetIndex=null;
String[] sheetname=getSheetsName();
try {
loadFile();
totalsheet=workbook.getNumberOfSheets();
sheetIndex=new int[totalsheet];
while(i<totalsheet)
{
sheetIndex[i]=workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
logger.error(ex);
} catch (NullObjectFoundException ex) {
logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index)
{
if(index < getSheetsIndex().length && index >=0)
return true;
else
return false;
}
public int getNumberOfSheet()
{
int totalsheet=0;
try {
loadFile();
totalsheet=workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex)
{
int NO_OF_Column=0;XSSFCell cell = null;
XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
}
else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex)
{
int NO_OF_ROW=0; XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
}
else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex);}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex)
{
int noOfColumns = 0;XSSFCell cell = null; int i =0;
String columns[] = null; XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator cellIter = Row.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
}
else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
logger.error(ex);}
return columns;
}//end of method
public String[][] getSheetData(int SheetIndex)
{
int noOfColumns = 0;XSSFRow row = null;
XSSFCell cell = null;
int i=0;int noOfRows=0;
int j=0;
String[][] data=null; XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows =getNumberOfRows(SheetIndex)+1;
data = new String[noOfRows][noOfColumns];
Iterator rowIter = sheet.rowIterator();
while(rowIter.hasNext())
{
row = (XSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
j=0;
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
if(cell.getCellType() == cell.CELL_TYPE_STRING)
{
data[i][j] = cell.getStringCellValue();
}
else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC)
{
if (HSSFDateUtil.isCellDateFormatted(cell))
{
String formatCellValue = new DataFormatter().formatCellValue(cell);
data[i][j] =formatCellValue;
}
else
{
data[i][j] = Double.toString(cell.getNumericCellValue());
}
}
else if(cell.getCellType() == cell.CELL_TYPE_BOOLEAN)
{
data[i][j] = Boolean.toString(cell.getBooleanCellValue());
}
else if(cell.getCellType() == cell.CELL_TYPE_FORMULA)
{
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
}
else throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex);}
return data;
}
public String[][] getSheetData(int SheetIndex,int noOfRows)
{
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i=0;
int j=0;
String[][] data=null;
XSSFSheet sheet=null;
try {
loadFile(); //load give Excel
if(validateIndex(SheetIndex))
{
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator rowIter = sheet.rowIterator();
while(i<noOfRows)
{
row = (XSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
j=0;
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
if(cell.getCellType() == cell.CELL_TYPE_STRING)
{
data[i][j] = cell.getStringCellValue();
}
else if(cell.getCellType() == cell.CELL_TYPE_NUMERIC)
{
if (HSSFDateUtil.isCellDateFormatted(cell))
{
String formatCellValue = new DataFormatter().formatCellValue(cell);
data[i][j] =formatCellValue;
}
else
{
data[i][j] = Double.toString(cell.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
}else throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
logger.error(ex);
}
return data;
}
please help me to sort out this problem.
Thanks
The error is telling you that POI couldn't find a core part of the OOXML file, in this case the content types part. Your file isn't a valid OOXML file, let alone a valid .xlsx file. It is a valid zip file though, otherwise you'd have got an earlier error
Can Excel really load this file? I'd expect it wouldn't be able to, as the exception is most commonly triggered by giving POI a regular .zip file! I suspect your file isn't valid, hence the exception
.
Update: In Apache POI 3.15 (from beta 1 onwards), there's a more helpful set of Exception messages for the more common causes of this problem. You'll now get more descriptive exceptions in this case, eg ODFNotOfficeXmlFileException and OLE2NotOfficeXmlFileException. This raw form should only ever show up if POI really has no clue what you've given it but knows it's broken or invalid.
Pretty sure that this exception is thrown when the Excel file is either password protected or the file itself is corrupted. If you just want to read a .xlsx file, try my code below. It's a lot more shorter and easier to read.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Sheet;
//.....
static final String excelLoc = "C:/Documents and Settings/Users/Desktop/testing.xlsx";
public static void ReadExcel() {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(excelLoc));
Workbook wb = WorkbookFactory.create(inputStream);
int numberOfSheet = wb.getNumberOfSheets();
for (int i = 0; i < numberOfSheet; i++) {
Sheet sheet = wb.getSheetAt(i);
//.... Customize your code here
// To get sheet name, try -> sheet.getSheetName()
}
} catch {}
}
You get this exact error should you pass an old school .xls file into this API. Save the .xls as a .xlsx and then it will work.
I was using XSSFWorkbook to read .xls, which resulted in InvalidFormatException. I have to use a more generic Workbook and Sheet to make it work.
This post helped me solved my problem.
You might also see this error if you attempt to parse the same file twice from the same source.
I was parsing the file once to validate and again (from the same InputStream) to process - this produced the above error.
To get round this I parsed the source file into 2 different InputStreams, one to validate and one to process.
Cleaned up the code (commented out the logger mostly) to make it run in my Eclipse environment.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
public class ReadXLSX {
private String filepath;
private XSSFWorkbook workbook;
// private static Logger logger=null;
private InputStream resourceAsStream;
public ReadXLSX(String filePath) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.filepath = filePath;
resourceAsStream = ClassLoader.getSystemResourceAsStream(filepath);
}
public ReadXLSX(InputStream fileStream) {
// logger=LoggerFactory.getLogger("ReadXLSX");
this.resourceAsStream = fileStream;
}
private void loadFile() throws FileNotFoundException,
NullObjectFoundException {
if (resourceAsStream == null)
throw new FileNotFoundException("Unable to locate give file..");
else {
try {
workbook = new XSSFWorkbook(resourceAsStream);
} catch (IOException ex) {
}
}
}// end loadxlsFile
public String[] getSheetsName() {
int totalsheet = 0;
int i = 0;
String[] sheetName = null;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetName = new String[totalsheet];
while (i < totalsheet) {
sheetName[i] = workbook.getSheetName(i);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetName;
}
public int[] getSheetsIndex() {
int totalsheet = 0;
int i = 0;
int[] sheetIndex = null;
String[] sheetname = getSheetsName();
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
sheetIndex = new int[totalsheet];
while (i < totalsheet) {
sheetIndex[i] = workbook.getSheetIndex(sheetname[i]);
i++;
}
} catch (FileNotFoundException ex) {
// logger.error(ex);
} catch (NullObjectFoundException ex) {
// logger.error(ex);
}
return sheetIndex;
}
private boolean validateIndex(int index) {
if (index < getSheetsIndex().length && index >= 0)
return true;
else
return false;
}
public int getNumberOfSheet() {
int totalsheet = 0;
try {
loadFile();
totalsheet = workbook.getNumberOfSheets();
} catch (FileNotFoundException ex) {
// logger.error(ex.getMessage());
} catch (NullObjectFoundException ex) {
// logger.error(ex.getMessage());
}
return totalsheet;
}
public int getNumberOfColumns(int SheetIndex) {
int NO_OF_Column = 0;
#SuppressWarnings("unused")
XSSFCell cell = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = firstRow.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex.getMessage());
}
return NO_OF_Column;
}
public int getNumberOfRows(int SheetIndex) {
int NO_OF_ROW = 0;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
NO_OF_ROW = sheet.getLastRowNum();
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return NO_OF_ROW;
}
public String[] getSheetHeader(int SheetIndex) {
int noOfColumns = 0;
XSSFCell cell = null;
int i = 0;
String columns[] = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
columns = new String[noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
XSSFRow Row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = Row.cellIterator();
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
columns[i] = cell.getStringCellValue();
i++;
}
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
}
catch (Exception ex) {
// logger.error(ex);
}
return columns;
}// end of method
public String[][] getSheetData(int SheetIndex) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int noOfRows = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
noOfRows = getNumberOfRows(SheetIndex) + 1;
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (rowIter.hasNext()) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
data[i][j] = Boolean.toString(cell
.getBooleanCellValue());
}
else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
data[i][j] = cell.getCellFormula().toString();
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
public String[][] getSheetData(int SheetIndex, int noOfRows) {
int noOfColumns = 0;
XSSFRow row = null;
XSSFCell cell = null;
int i = 0;
int j = 0;
String[][] data = null;
XSSFSheet sheet = null;
try {
loadFile(); // load give Excel
if (validateIndex(SheetIndex)) {
sheet = workbook.getSheetAt(SheetIndex);
noOfColumns = getNumberOfColumns(SheetIndex);
data = new String[noOfRows][noOfColumns];
Iterator<Row> rowIter = sheet.rowIterator();
while (i < noOfRows) {
row = (XSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
j = 0;
while (cellIter.hasNext()) {
cell = (XSSFCell) cellIter.next();
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
data[i][j] = cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (HSSFDateUtil.isCellDateFormatted(cell)) {
String formatCellValue = new DataFormatter()
.formatCellValue(cell);
data[i][j] = formatCellValue;
} else {
data[i][j] = Double.toString(cell
.getNumericCellValue());
}
}
j++;
}
i++;
} // outer while
} else
throw new InvalidSheetIndexException("Invalid sheet index.");
} catch (Exception ex) {
// logger.error(ex);
}
return data;
}
}
Created this little testcode:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ReadXLSXTest {
/**
* #param args
* #throws FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
ReadXLSX test = new ReadXLSX(new FileInputStream(new File("./sample.xlsx")));
System.out.println(test.getSheetsName());
System.out.println(test.getNumberOfSheet());
}
}
All this ran like a charm, so my guess is you have an XLSX file that is 'corrupt' in one way or another. Try testing with other data.
Cheers,
Wim
I get the same exception for .xls file, but after I open the file and save it as xlsx file , the below code works:
try(InputStream is =file.getInputStream()){
XSSFWorkbook workbook = new XSSFWorkbook(is);
...
}
If the excel file is password protected, then this error comes up.
Try saving the file as Excel Workbook ONLY. NOT any other format. It worked for me. I was getting the same error.
I was able to solve this issue by either
Open and resave the file using MS-EXCEL
Open the file using the Woorbookfactory:
Workbook workbook = WorkbookFactory.create(byteFile);

Categories