how to create appendable excelsheet using java - java

I want to create an append-able excel sheet.
Like i have four columns stream1 stream2 stream3 stream4
first time i am inserting data only first column(stream1)
after that i want to full fill other columns one by one.
this is the code which i am using:
public void createFile(Jqueue stream1, Jqueue stream2, Jqueue stream3, Jqueue stream4) {
try {
String filename = "path";
boolean alreadyExists = (new File(filename)).exists();
HSSFRow rowhead = sheet1.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("Stream 1");
rowhead.createCell((short) 1).setCellValue("Stream 2");
rowhead.createCell((short) 2).setCellValue("Stream 3");
rowhead.createCell((short) 3).setCellValue("Stream 4");
int i = 1;
while (!stream1.isEmpty()) {
String urlstream1 = "";
String urlstream2 = "";
String urlstream3 = "";
String urlstream4 = "";
HSSFRow row = sheet1.createRow((short) i);
try {
if (stream1.size() > 0) {
urlstream1 = stream1.dequeue().toString();
}
} catch (Exception ex) {
}
try {
if (stream2.size() > 0) {
urlstream2 = stream2.dequeue().toString();
}
} catch (Exception ex) {
}
try {
if (stream3.size() > 0) {
urlstream3 = stream3.dequeue().toString();
}
} catch (Exception ex) {
}
try {
if (stream4.size() > 0) {
urlstream4 = stream4.dequeue().toString();
}
} catch (Exception ex) {
}
row.createCell((short) 0).setCellValue(urlstream1);
row.createCell((short) 1).setCellValue(urlstream2);
row.createCell((short) 2).setCellValue(urlstream3);
row.createCell((short) 3).setCellValue(urlstream4);
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
But this is not append-able code. its inserting data row by row.
thx in advanced.

I suppose a slight change in your code should do it.
Try replacing
int i = 1;
with the following:
int i = sheet1.getLastRowNum() + 1;
You would also need to change your implementation for reading and writing files a bit.

Related

Java and VBScript to populate and run macro throwing error

I have an Excel file which has a macro and I would like to automate the process. I have Java code which fills the Excel columns and I have written the VBScript to run the macro in the Excel.
My Java code is (I pass the Excel fileName which has the macro)
public void excelupdate(String fileName) {
FileInputStream file = null;
FileOutputStream out = null;
try {
file = new FileInputStream(new File(fileName));
HSSFWorkbook yourworkbook = new HSSFWorkbook(file);
HSSFSheet sheet1 = null;
for (int i = 0; i < yourworkbook.getNumberOfSheets(); i++) {
if (yourworkbook.getSheetName(i).contains("Sheet-Macro")) {
sheet1 = yourworkbook.getSheetAt(i);
}
}
Cell cell = null;
int rowValue = 10;
for (int i = 0; i < list.size() - 1; i++) {
cell = sheet1.getRow(rowValue).getCell(2);
cell.setCellValue(list.get(i));
rowValue++;
}
Cell cell1 = null;
int rowValue1 = 10;
for (int j = 0; j < Input1list.size() - 1; j++) {
cell1 = sheet1.getRow(rowValue1).getCell(3);
cell1.setCellValue(Input1list.get(j));
rowValue1++;
}
Cell cell2 = null;
int rowValue2 = 22;
for (int k = 0; k < Input2list.size() - 1; k++) {
cell2 = sheet1.getRow(rowValue2).getCell(4);
cell2.setCellValue(Input2list.get(k));
rowValue2++;
}
out = new FileOutputStream(("C:\\Users\\Desktop\\EXCEL.xls"));
yourworkbook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
} catch (Exception e) {
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
The Java code runs on Apache Poi to fill in the columns and moves the Excel file to a particular directory and then I have the below VBScript to run the macro:
Dim objXL
Set objXL = CreateObject("Excel.Application")
Set objWorkbook = objXL.Workbooks.Open("F:\testmacro\testmacro\EXCEL.xls")
objWorkbook.Sheets("AD stages").Cells(6, 4) = "F:\set1\set.txt"
objXL.Application.DisplayAlerts = False
objXL.ActiveWorkbook.Save
objXL.Application.Run "macro_cal"
objXL.ActiveWorkbook.Save
objXL.ActiveWorkbook.Close
objXL.Application.DisplayAlerts = True
objXL.Application.Quit
WScript.Echo "ExCEL file updated successfully"
WScript.Quit
Set objXL = Nothing
I call the above VBscript from the java as below,
File file = new File(excelFilename);
file.setExecutable(true);
file.setReadable(true);
file.setWritable(true);
Runtime runtime = Runtime.getRuntime();
try {
String sample="cmd /c start "+vbScript+" "+"\"" +excelFilename + "\"" + " "+"\"" +outFile + "\"";
System.out.println(sample);
Process process1 = runtime.exec(sample);
} catch (IOException e) {
logger.error(e);
}
But the problem is, once the Java populates the Excel columns and save the file, the file becomes protected and hence the VBScript is throwing an error stating it can't open/run the macro in protected Excel.
Any advice?
Thanks to #AxelRitcher, the solution is "Please read about Error message in Microsoft Office: "Office has detected a problem with this file". So seems as if the location F:\testmacro\testmacro is not a trusted location for Excel files having macros in it."

Every time I write to excel, it overwrites the entire file with a blank file - PUZZLED

What I am trying to do is onTestFailure (TestNG) I am trying to write a pass/fail to a specified column. In the below code, I just wanted to do a little test to write Fail to a specified cell. But what's happening is, instead of writing a pass/fail to the specified cell, it literally overwrites the entire file and erases all of my data and I am puzzled as to why that's happening. I have looked on here and googled but cannot find the answer. Below is the following code:
#Override
public synchronized void onTestFailure(ITestResult tr){
try {
Workbook workbook = Workbook.getWorkbook(new File(testData), workbookSettings);
WritableWorkbook wb = Workbook.createWorkbook(new File(testData), workbook);
WritableSheet ws = wb.getSheet("OrderEditQA3");
Label label = new Label(5,2, "Fail");
ws.addCell(label);
wb.write();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException b){
System.out.print("Error!");
} catch (WriteException we){
System.out.print("");
}
}
Any help would be greatly appreciated.
UPDATED...
Below is another class that I use to get test data returned to a Dataprovider and I also load all of my elements from a specified sheet. Below is the code
// Code to get all test data
protected static Object[][] loadTestData(String sheetName)throws BiffException, IOException{
Sheet sheet = null;
try{
sheet = getWorkBook().getSheet(sheetName);
rowCount = sheet.getRows();
colCount = sheet.getColumns();
data = new String[rowCount -1][colCount-1];
int ci;
int cj;
ci=0;
for(int i=1; i< rowCount; i++, ci++){
cj=0;
for(int j=1; j< colCount; j++, cj++){
Cell cell = sheet.getCell(j,i);
if(cell.getContents().isEmpty()){ continue;}
System.out.print(cell.getContents() + "\n");
data[ci][cj] = cell.getContents();
}
}
}catch (IOException io){
System.out.print(String.format("File: %s not found!", testData));
}
getWorkBook().close();
return data;
}
//Code to retrieve all element attributes:
#BeforeClass
protected static List<String> loadElements()throws BiffException, IOException {
Sheet sheet = null;
sheet = getWorkBook().getSheet("Elements");
rowCount = sheet.getRows();
colCount = sheet.getColumns();
List<String> list = new ArrayList<>(rowCount);
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
Cell cell = sheet.getCell(j,i);
if(cell.getContents().isEmpty()) {continue;}
String cellContents = cell.getContents();
list.add(cellContents);
System.out.print(cell.getContents() + "\n");
}
}
elements = list;
getWorkBook().close();
return list;
}
Just forgot that pesky close() method
#Override
public synchronized void onTestFailure(ITestResult tr){
try {
Workbook workbook = Workbook.getWorkbook(new File(testData), workbookSettings);
WritableWorkbook wb = Workbook.createWorkbook(new File(testData), workbook);
WritableSheet ws = wb.getSheet("OrderEditQA3");
Label label = new Label(5,2, "Fail");
ws.addCell(label);
wb.write();
wb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException b){
System.out.print("Error!");
} catch (WriteException we){
System.out.print("");
}
}

Strange out of bounds exception when trying to read cell

I've been trying to read an excel sheet and insert data from cells into a program. I am successful to a point, but when I try and get the data from cells in position 4 and onwards, I get an out of bounds exception. No idea why this would be, as I can call positions 0,1,2 and 3 just fine. Here is my code.
public void readExcel(File file) {
try {
//Workbook newBook = new Workbook();
Workbook workbook = Workbook.getWorkbook(file);
WritableWorkbook workbookOutput = Workbook.createWorkbook(new File("output.xls"));
// Workbook workbook = Workbook.getWorkbook(new File(“Res.xls”));
WritableSheet sheetOutput = workbookOutput.createSheet("First Sheet", 0);
sheet = workbook.getSheet(0);
boolean isnotnull = true;
int i = 0;
while(isnotnull){
//Cell a1 = sheet.getCell(0, 2);
try{
Cell a2 = sheet.getCell(0, i);
Cell a3 = sheet.getCell(1, i);
Cell a4 = sheet.getCell(2, i);
stringa1 = a2.getContents();
stringa2 = a3.getContents();
stringa3 = a4.getContents();
char c = stringa2.charAt(0);
char d = stringa2.charAt(1);
if(Character.isDigit(c) || Character.isDigit(d)){
System.out.println("found one");
stringa1 = stringa1 + "" + stringa2;
stringa2 = stringa3;
Cell a5 = sheet.getCell(3, i);
try{
Cell a10 = sheet.getCell(4, i);
// System.out.print("Cell" + a6.getContents());
}
catch(Exception e){
System.out.println(e);
}
stringa4 = a5.getContents();
stringa3 = stringa4;
// checkCells(1, i);
}
Label label = new Label(0, i, stringa1);
Label label2 = new Label(1, i, stringa2);
Label label3 = new Label(2, i, stringa3);
sheetOutput.addCell(label);
sheetOutput.addCell(label2);
sheetOutput.addCell(label3);
i++;
System.out.println(stringa1 + " |||||||||||| " + stringa2 + " |||||||| " + stringa3 + " " + i);
}catch(Exception e){
System.out.println(e);
isnotnull = false;
}
}
workbookOutput.write();
try{
workbookOutput.close();
}catch(Exception r){
System.out.println(r);
}
System.out.println(stringa1);
workbook.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}`enter code here`
This cell simply doesn't exist in a spreadsheet. It seems that createSheet method creates only few first Cells.

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