i have some problem with my android app; i want that users could upload an excel file on Firebase and populate a RecyclerView with data on this file. I don't have problem about populate the RecyclerView, i know how to do it, i have problem on read the file. I uploaded it on Firebase with this:
StorageReference stRef = storageRef.child("clienti.xlsx");
UploadTask task = stRef.putFile(file);
task.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(getActivity(), "Upload error: "+exception.getMessage() , Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
downloadFile("clienti");
}
It all works until now, i also download the file from firebase to a specific folder but now i don't know how to "read" it and take data from it; i have tried this, but it said to me always that the file doesn't exists.
String[][] arrays = read( Environment.getExternalStorageDirectory() + localFile.getPath());
if(arrays == null){strHyouji="no such file";}else{
for (String[] array : arrays) {
for (String v : array) {
strHyouji = strHyouji + v + ",";
}
strHyouji = strHyouji + "\n";
aList.add(strHyouji);
}
}
Toast.makeText(getActivity(), strHyouji, Toast.LENGTH_SHORT).show();
Here the read() method:
Workbook workbook = null;
try {
WorkbookSettings ws = new WorkbookSettings();
ws.setGCDisabled(true);
workbook = Workbook.getWorkbook(new File(dbStr), ws);
Sheet sheet = workbook.getSheet(0);
int rowCount = sheet.getRows();
String[][] result = new String[rowCount][];
for (int i = 0; i < rowCount; i++) {
Cell[] row = sheet.getRow(i);
result[i] = new String[row.length];
for (int j = 0; j < row.length; j++) {
result[i][j] = row[j].getContents();
}
}
return result;
} catch (BiffException e) {
strHyouji=strHyouji+ e.toString();
} catch (IOException e) {
strHyouji=strHyouji+ e.toString();
} catch (Exception e) {
strHyouji=strHyouji+ e.toString();
} finally {
if (workbook != null) {
workbook.close();
}
}
return null;
With Apache POI, you can read the excel. Here ColumnHeaderString is the actual column header of the excel sheet and datafromcell is the value under the header converted to a String.
Reading the file
File file = new File( path ) // String file path
FileInputStream fileInputStream = new FileInputStream( file )
XSSFWorkbook workbook = new XSSFWorkbook( fileInputStream )
Using the workbook
XSSFSheet sheet = workbook.getSheetAt( 0 );
private DataFormatter excelDataFormatter = new DataFormatter()
Iterator<Row> rowIterator = sheet.rowIterator();
Row header = null;
if( rowIterator.hasNext() )
{
header = rowIterator.next();
}
while( rowIterator.hasNext() )
{
Iterator<Cell> cellIterator = row.cellIterator();
while( cellIterator.hasNext() )
{
Cell cell = cellIterator.next();
int cellIndex = cell.getColumnIndex();
String colHead = header.getCell( cellIndex ).toString();
if( ColumnHeaderString.equals( colHead ) ) // Match the desired column header
{
String datafromcell = excelDataFormatter.formatCellValue( cell ).strip();
}
}
}
Related
This question already has an answer here:
Creating multiple sheets using Apache poi and servlets
(1 answer)
Closed 1 year ago.
I am trying to write the data into same excel file in different sheets, below is the code I tried here only one sheet is creating and data is updating in that sheet, new sheet name is overriding on old sheet. Here I am calling call method two times with 2 different sheet name, when we call from 1st time data need to update in sheet1 and 2nd time call data need to update in sheet2 but in this code only sheet2 is creating and data updating in that.
public static void call(Map<String, String[]> dataListLMS_IPS, String sheet)
{
try {
String filePath = "C:\\Users\\PATIV25\\Downloads\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.close();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(sheet);
XSSFRow row;
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
Cell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
// .xlsx is the format for Excel Sheets...
// writing the workbook into the file...
FileOutputStream out = new FileOutputStream(theDir);
workbook.write(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
call(data, "sheet1");
call(data, "sheet2");
}
The existing logic is incorrect. You need to separate the creation of file and sheets into different sections if you want to call the call method twice. Try this:
public static void call(Map<String, String[]> dataListLMS_IPS, FileOutputStream fileOut) throws IOException
{
XSSFWorkbook workbook = new XSSFWorkbook();
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
XSSFSheet spreadsheet = workbook.createSheet(key);
XSSFRow row;
row = spreadsheet.createRow(0);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
XSSFCell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
workbook.write(fileOut);
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
FileOutputStream fileOut = null;
try {
String filePath = "d:\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
fileOut = new FileOutputStream(filename);
call(data, fileOut);
call(data, fileOut);
}
catch (Exception e)
{
e.printStackTrace();
} finally {
if (fileOut != null)
fileOut.close();
}
}
It will create 2 sheets in the same Excel file.
I am not able to read the data for the cell company code and the drop down value for it. I tried reading the data using
try {
Workbook wb = new XSSFWorkbook(new FileInputStream(
"D:/TCA/Test/test.xlsx"));
// org.apache.poi.ss.usermodel.Workbook wb = new XSSFWorkbook(new
// FileInputStream("D:/TCA/Test/aa.xlsx"));
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
Sheet sheet = wb.getSheetAt(i);
Name name = null;
System.out.println(wb.getSheetName(i));
for (Row row : sheet) {
name = sheet.getWorkbook().createName();
// System.out.println("rownum: " + row.getRowNum());
for (Cell cell : row) {
// System.out.println(cell);
handleCell(cell.getCellType(), cell);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
I have the solution to copy .xls workbook in java but not able to copy .xlsx workbook.
Anybody have solution.
I have searched google, stackoverflow and found solution only to copy xls files.
If anyone wants a simpler procedure just use Files.copy:
File originalWb = new File("orginalWb.xlsx");
File clonedWb = new File("clonedWb.xlsx");
Files.copy(originalWb.toPath(), clonedW.toPath());
No need for any bloated code
I didn't test my code. Just wrote it to give you a basic idea of what to do.
public class CopyXSSFWorkbook {
public static void main(String[] args) {
// Read xlsx file
XSSFWorkbook oldWorkbook = null;
try {
oldWorkbook = (XSSFWorkbook) WorkbookFactory.create(new File("old.xlsx"));
} catch (Exception e) {
e.printStackTrace();
return;
}
final XSSFWorkbook newWorkbook = new XSSFWorkbook();
// Copy style source
final StylesTable oldStylesSource = oldWorkbook.getStylesSource();
final StylesTable newStylesSource = newWorkbook.getStylesSource();
oldStylesSource.getFonts().forEach(font -> newStylesSource.putFont(font, true));
oldStylesSource.getFills().forEach(fill -> newStylesSource.putFill(new XSSFCellFill(fill.getCTFill())));
oldStylesSource.getBorders()
.forEach(border -> newStylesSource.putBorder(new XSSFCellBorder(border.getCTBorder())));
// Copy sheets
for (int sheetNumber = 0; sheetNumber < oldWorkbook.getNumberOfSheets(); sheetNumber++) {
final XSSFSheet oldSheet = oldWorkbook.getSheetAt(sheetNumber);
final XSSFSheet newSheet = newWorkbook.createSheet(oldSheet.getSheetName());
newSheet.setDefaultRowHeight(oldSheet.getDefaultRowHeight());
newSheet.setDefaultColumnWidth(oldSheet.getDefaultColumnWidth());
// Copy content
for (int rowNumber = oldSheet.getFirstRowNum(); rowNumber < oldSheet.getLastRowNum(); rowNumber++) {
final XSSFRow oldRow = oldSheet.getRow(rowNumber);
if (oldRow != null) {
final XSSFRow newRow = newSheet.createRow(rowNumber);
newRow.setHeight(oldRow.getHeight());
for (int columnNumber = oldRow.getFirstCellNum(); columnNumber < oldRow
.getLastCellNum(); columnNumber++) {
newSheet.setColumnWidth(columnNumber, oldSheet.getColumnWidth(columnNumber));
final XSSFCell oldCell = oldRow.getCell(columnNumber);
if (oldCell != null) {
final XSSFCell newCell = newRow.createCell(columnNumber);
// Copy value
setCellValue(newCell, getCellValue(oldCell));
// Copy style
XSSFCellStyle newCellStyle = newWorkbook.createCellStyle();
newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
newCell.setCellStyle(newCellStyle);
}
}
}
}
}
try {
oldWorkbook.close();
newWorkbook.write(new FileOutputStream("new.xlsx"));
newWorkbook.close();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private static void setCellValue(final XSSFCell cell, final Object value) {
if (value instanceof Boolean) {
cell.setCellValue((boolean) value);
} else if (value instanceof Byte) {
cell.setCellValue((byte) value);
} else if (value instanceof Double) {
cell.setCellValue((double) value);
} else if (value instanceof String) {
if (value.startsWith("=")) {
// Formula String
cell.setCellFormula(value.substring(1));
} else {
cell.setCellValue(cstr);
}
} else {
throw new IllegalArgumentException();
}
}
private static Object getCellValue(final XSSFCell cell) {
switch (cell.getCellTypeEnum()) {
case BOOLEAN:
return cell.getBooleanCellValue(); // boolean
case ERROR:
return cell.getErrorCellValue(); // byte
case NUMERIC:
return cell.getNumericCellValue(); // double
case STRING:
case BLANK:
return cell.getStringCellValue(); // String
case FORMULA:
return "=" + cell.getCellFormula(); // String for formula
default:
throw new IllegalArgumentException();
}
}
}
Using Apache POI XSSF library:
public void copyFile(String sourcePath, String destinationPath) throws IOException {
FileInputStream excelFile = new FileInputStream(new File(sourcePath));
Workbook workbook = new XSSFWorkbook(excelFile);
FileOutputStream outputStream = new FileOutputStream(destinationPath);
workbook.write(outputStream);
workbook.close();
}
Clone a workbook in memory (if you can efford it):
public static Workbook cloneWorkbook(final Workbook workbook) {
try {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(4096);
workbook.write(outputStream);
return WorkbookFactory.create(new ByteArrayInputStream(outputStream.toByteArray()));
} catch (final IOException ex) {
log.warn("Error cloning workbook", ex);
return null; // or throw exception
}
}
Apache POI Busy Developers' Guide to HSSF and XSSF Features
POI performs these steps on XLS/XLSX File. XLS: HSSFWorkbook, XLSX: XSSFWorkbook
Read the File as Stream (FileStream): SystemFile to JavaFileObject
Create a WorkBook form Stream. Stream to XSSFWorkbook-JavaObject
Using POI functions you can perform CURD operations on Java Workbook Object.
Convert Java Workbook Object to file/stream.
NOTE: Index Starts form 0 for Row/Column/Sheet.
Following operations are performed on Sheets:
XLSX File with Sheet1, Sheet2
getSheet_RemoveOthers(Sheet1). XLSX File:Sheet1
public static XSSFSheet getSheet_RemoveOthers(String sourceFileSheetName) {
XSSFSheet srcSheet = workBook.getSheet(sourceFileSheetName);
//Sheet srcSheet = oldWorkbook.getSheetAt(0);
int srcSheetIndex = workBook.getSheetIndex(srcSheet);
System.out.println("srcSheetIndex:"+srcSheetIndex);
int numberOfSheets = workBook.getNumberOfSheets();
for (int indexAt = 0; indexAt < numberOfSheets; indexAt++) {
if (srcSheetIndex == indexAt) {
System.out.println("sourceFileSheetName:"+indexAt);
} else {
String sheetName = workBook.getSheetName(indexAt);
System.out.println("Removing sheetName:"+sheetName);
workBook.removeSheetAt(indexAt);
}
}
System.out.println("getSheetName : "+ srcSheet.getSheetName() );
int totalRows = srcSheet.getPhysicalNumberOfRows();
System.out.println("Total Number of Rows : "+ totalRows );
return srcSheet;
}
XSSFSheet.cloneSheet(Sheet1). XLSX File:Sheet1, Sheet1 (2)
public static XSSFSheet cloneSheet(String sourceFileSheetName) {
Sheet srcSheet = workBook.getSheet(sourceFileSheetName);
int srcSheetIndex = workBook.getSheetIndex(srcSheet);
System.out.println("srcSheetIndex:"+srcSheetIndex);
XSSFSheet cloneSheet = workBook.cloneSheet(srcSheetIndex);
return cloneSheet;
}
Full-Length Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
public class POI_XLSX_Report {
static String filePath = "C:/Yash/",
sourceFile = filePath+"POIExcel.xlsx", sourceFileSheetName = "Sheet1",
destinationFile = filePath+"POIExcelCopy.xlsx";
static XSSFWorkbook workBook;
public static void main(String[] args) throws Exception {
File mySrcFile = new File(sourceFile);
FileInputStream stream = new FileInputStream(mySrcFile);
workBook = (XSSFWorkbook) WorkbookFactory.create( stream );
XSSFSheet sheet_RemoveOthers = getSheet_RemoveOthers(sourceFileSheetName);
setSheetValue(sheet_RemoveOthers, 4, 6, "Val2");
// New Sheet with exact copy of Source-Sheet
XSSFSheet cloneSheet = cloneSheet(sourceFileSheetName);
setSheetValue(cloneSheet, 4, 6, "Val2");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
workBook.write( byteArrayOutputStream );
byteArrayOutputStream.close();
File clonedWb = new File(destinationFile);
//Files.copy(mySrcFile.toPath(), clonedWb.toPath()); If a file is already available then throws exception
// Write the output to a file
FileOutputStream fileOutputStream = new FileOutputStream( clonedWb );
byteArrayOutputStream.writeTo(fileOutputStream);
}
public static XSSFSheet getSheet_RemoveOthers(String sourceFileSheetName) {
// ...
}
public static XSSFSheet cloneSheet(String sourceFileSheetName) {
// ...
}
public static void setSheetValue(Sheet sheet, int colIndex, int rowIndex, String value) {
// Row and Column index starts form 0
rowIndex = rowIndex - 1;
colIndex = colIndex - 1;
Row row = sheet.getRow(rowIndex);
if (row == null) {
System.out.println("createRow:");
Row createRow = sheet.createRow(rowIndex);
row= createRow;
}
short lastCellNum = row.getLastCellNum();
System.out.println("Col:"+lastCellNum);
Cell createCell = row.createCell(colIndex, CellType.STRING);
System.out.println("New cell:"+createCell.getStringCellValue());
createCell.setCellValue(value);
}
}
I need to set a value for a specific row and column of the spreadsheet, but I get a null pointer before even i = 1. I've tried changing the code but this error keeps happening and I have no more idea why.Does anyone have any idea why this happens?
My code
public Workbook build(Planilha planilha) {
File file = new File(TEMPLATE_PATH);
if (!file.exists()) {
Log.error(this, String.format("File %s not exists.", file.getAbsolutePath()));
throw new NotFoundException("File not exists.");
}
Workbook wb = null;
try (FileInputStream fs = new FileInputStream(file)) {
wb = new XSSFWorkbook(fs);
wb = writeMetadatas(planilha, wb);
Map<String, Integer> header = getHeader(wb);
Sheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
for (int i = 0; i <= 10; i++) {
row = sheet.getRow(i);
for (int j = 0; j <= 10; j++) {
cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
if (cell.getColumnIndex() == 0 && row.getRowNum() == 7) {
cell.setCellValue("teste");
}
}
}
} catch (Exception e) {
Log.error(this, "Erro: Planilha não existe", e);
System.err.print("Erro");
}
String tmpDir = System.getProperty("java.io.tmpdir");
File f = FileUtil.file(PATH, System.currentTimeMillis() + ".xlsx");
try {
FileOutputStream fout = new FileOutputStream(f);
wb.write(fout);
fout.flush();
fout.close();
} catch (Exception e) {
Log.error(this, "Erro ao abrir arquivo p escrever.");
}
return wb;
}
**NullPointer happens in cell.setCellValue("teste");
I'm trying to set that cell
First, you can test if the row number is a certain number outside of your for loop that loops over the cells in a row. Pull that if outside your j for loop.
It looks like the Cell doesn't exist. row.getCell(j) is returning null.
You can use a MissingCellPolicy to determine whether you want to return a new Cell if the Cell doesn't already exist. The CREATE_NULL_AS_BLANK value will create a blank Cell for you if it doesn't already exist.
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);