Using windows-7 and keep getting errors to write code to ready excel
Trying to read excel data file in java maven Keep getting error on
line#49 sheet= book.getSheet(sheetname); I have added all dependencies and imported but still can not clear this error.
package com.newTour.qa.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hslf.model.Sheet;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import com.newTour.qa.Base.TestBase;
public class TestUtil extends TestBase {
public static String TESTDATA_SHEET_PATH = "C:\\Users\\shahgee\\newtour.qu\\src\\main\\java\\"
+ "com\\qa\\newtour\\testdata\\MercutyTourTestData.xlsx" ;
static Workbook book;
static Sheet sheet;
public static Object[][]getTestData(String sheetname){
FileInputStream file = null;
try {
file = new FileInputStream(TESTDATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book= WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetname);
Object[][]data = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for (int i =0; i <sheet.getLastRowNum();i++){
for (int k =0;k <sheet.getRow(0).getLastCellNum(); k++){
data[i][k]= sheet.getRow(i+1).getCell(k).toString();
}
}
return data;
}
}
try to change the import of Sheet class with
org.apache.poi.ss.usermodel.Sheet
what you use right now is Sheet for Powerpoint Document.
here the reference of the library you use right now:
https://www.oschina.net/uploads/doc/poi-3.1-FINAL/org/apache/poi/hslf/model/Sheet.html
I have spent countless hours trying to find a solution to this. I have tried Apache POI, JExcel and JXLS but no where have I found code to successfully read checkbox (form control) values.
If anyone has found a working solution then it would be great if you could share it here. Thanks!
UPDATE
I have written code that reads the checkbox but it cannot determine whether it is checked or not.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.record.CommonObjectDataSubRecord;
import org.apache.poi.hssf.record.ObjRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SubRecord;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class App {
private static final String path = "C:\\test.xls";
private static final String Workbook = "Workbook";
private static void readExcelfile() {
FileInputStream file = null;
try {
file = new FileInputStream(new File(path));
// Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println();
}
// file.close();
// FileOutputStream out = new FileOutputStream(
// new File(path));
// workbook.write(out);
// out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (file != null)
file.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static void readCheckbox() {
FileInputStream file = null;
InputStream istream = null;
try {
file = new FileInputStream(new File(path));
POIFSFileSystem poifs = new POIFSFileSystem(file);
istream = poifs.createDocumentInputStream(Workbook);
HSSFRequest req = new HSSFRequest();
req.addListenerForAllRecords(new EventExample());
HSSFEventFactory factory = new HSSFEventFactory();
factory.processEvents(req, istream);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (file != null)
file.close();
if (istream != null)
istream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("ReadExcelFile");
readExcelfile();
System.out.println("ReadCheckbox");
readCheckbox();
}
}
class EventExample implements HSSFListener {
public void processRecord(Record record) {
switch (record.getSid()) {
case ObjRecord.sid:
ObjRecord objRec = (ObjRecord) record;
List<SubRecord> subRecords = objRec.getSubRecords();
for (SubRecord subRecord : subRecords) {
if (subRecord instanceof CommonObjectDataSubRecord) {
CommonObjectDataSubRecord datasubRecord = (CommonObjectDataSubRecord) subRecord;
if (datasubRecord.getObjectType() == CommonObjectDataSubRecord.OBJECT_TYPE_CHECKBOX) {
System.out.println("ObjId: "
+ datasubRecord.getObjectId() + "\nDetails: "
+ datasubRecord.toString());
}
}
}
break;
}
}
}
Sorry for the late reply, but I ran into the same. I found a trick to determine the checkbox state.
In your example you ar looping over the SubRecords and you examine the CommonObjectDataSubRecord. But the value for the checkbox can be found in the one of the SubRecord.UnknownSubRecord. This is unfortunately a private class so you cannot call any method on it, but the toString() reveals the data, and with a little regex the value can be found. So using the code below I managed to retrieve the state of the checkbox:
Pattern p = Pattern.compile("\\[sid=0x000A.+?\\[0(\\d),");
if (!(subRecord instanceof CommonObjectDataSubRecord)) {
Matcher m = p.matcher(subRecord.toString());
if (m.find()) {
String checkBit = m.group(1);
if (checkBit.length() == 1) {
boolean checked = "1".equals(checkBit);
checkBox.setChecked(checked);
}
}
}
Now my challenge is to retrieve the checkbox value in a xlsx file...
I have an excel sheet from where I am reading excel cel values and importing to DB
Using Apache POI :
if (row.getCell(8) != null) {
setActualDeparture(DateUtil.getJavaDate(row.getCell(8).getNumericCellValue()));
}
The excel sheet has null on Cell 8 , so it should not import anything . but it takes dates like 1899-12-31T00:00:00
What could be the issue ?
The Row.getCell(int cellnum) returns only NULL if there is nothing stored in the file for this cell. It returns the cell if there is something stored in the file for this cell. Even if this is only a NumberFormat for example or any other information for this cell.
But there is a second method Row.getCell(int cellnum, Row.MissingCellPolicy policy) http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell%28int,%20org.apache.poi.ss.usermodel.Row.MissingCellPolicy%29 which can be used in your case.
Example:
There is nothing in A1 but there is a special NumberFormat and not General applied.
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
class GetEmtyCellTest {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
System.out.println(row.getCell(0).getNumericCellValue()); //0.0
System.out.println(row.getCell(0, Row.RETURN_BLANK_AS_NULL)); //null
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}
I am new to Java POI and i am trying to overwrite an excel file using Java POI.Let me make it clear, i don't want to open a new .xls file every time time i build the code however the code i wrote does it that way.The purpose for this is to, i will build the chart on excel and read the values for the chart from the database and write it to the excel file by using Java POI.Here is my code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");
HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Always use the same filename and when you run the program it will overwrite the file.
EDIT
If you want to modify an existing excel file then have a look HERE and scroll down to the section on "Reading or Modifying an existing file".
The problem is Apache POI doesn't support all features of Excel file format, including charts. So can not generate a chart with POI and when opening an existing Excel file with POI and modifying it, some of the current "objects" in the Excel file could be lost, as POI can't handle it and when writing, writes only the new information generated and existing one that can handle.
This is assumed by Apache as one of the flaws of POI.
We done similar processing of existing Excel file, filling new data onto it, but the existing Excel file contains only formatting styles and they are preserved using POI, but I think charts are very problematic. Trying ti filling data to update an existing chart is not possible with POI.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class UserInput {
public static Map getUserInput() throws InvalidFormatException, IOException {
String userName = System.getProperty("user.name");
String path = "";
int indexofColumn = 10;
Map inputFromExcel = new HashMap();
InputStream inp = new FileInputStream(path);
int ctr = 4;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
inputFromExcel.put("NBKID",cell.toString()) ;
row = sheet.getRow(ctr+1);
cell = row.getCell(indexofColumn);
inputFromExcel.put("Password", cell.toString());
row = sheet.getRow(ctr+2);
cell = row.getCell(indexofColumn);
inputFromExcel.put("NBKIDEmail",cell.toString());
row = sheet.getRow(ctr+3);
cell = row.getCell(indexofColumn);
inputFromExcel.put("sourceExcel" ,cell.toString());
} catch(Exception e) {
}
return inputFromExcel;
}
}
import java.util;
public class Main {
public static void main(String[] args) {
List<String> partyIdList = new ArrayList<String>();
List<String> phNoList = new ArrayList<String>();
String userName = System.getProperty("user.name");
String path = "";
try {
Map data = new HashMap(UserInput.getUserInput());
partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
WriteExcel.writeFile1(partyIdList, path,0,1);
WriteExcel.writeFile1(phNoList,path,1,0);
} catch (Exception e) {
throw new RuntimeException("Error while read excel Sheet" + e);
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
//System.out.println(path);
List<String> ItemList = new ArrayList();
InputStream inp = new FileInputStream(path);
int ctr = 0;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
ItemList.add(cell.toString());
// System.out.println(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
inp.close();
return ItemList;
}
}
I have to create one excel sheet using JExcel api..I cannt able to encode the excel file and am not able to sure whether the file is encoded or not ?...
pls help
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Locale;
import jxl.Sheet;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class Jexcel_test {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
ws.setCharacterSet(0);
ws.setEncoding("utf-8");
ws.setDrawingsDisabled(true);
ws.setGCDisabled(true);
System.out.println(ws.getCharacterSet());
System.out.println(ws.getArrayGrowSize());
System.out.println(ws.getExcelDisplayLanguage());
System.out.println(ws.getExcelRegionalSettings());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter filename :");
File filename= new File("f:/"+br.readLine()+".xls");
Workbook wb1=Workbook.getWorkbook(filename, ws);
Sheet s = wb1.getSheet(0);
SheetSettings settings = s.getSettings();
settings.setDefaultRowHeight(500);
if(!settings.isProtected())
{
settings.setPassword("test");
}
settings.setFitToPages(true);
System.out.println(s.getName());
for (int row = 1; row < s.getRows(); row++) {
String val = s.getCell(0, row).getContents().trim();
System.out.println(val);
}
wb1.close();
System.out.println("Enter new filename :");
File filename1= new File("f:/"+br.readLine()+".xls");
WritableWorkbook wb2 = Workbook.createWorkbook(filename1, ws);
WritableSheet sheet = wb2.createSheet("mysheet",0);
SheetSettings settings1 = sheet.getSettings();
settings1.setDefaultRowHeight(500);
settings1.setProtected(true);
settings1.setPassword("test");
settings1.setFitToPages(true);
System.out.println("Workbook "+filename1+" created");
wb2.write();
wb2.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
First write some non-ascii data in one of the column and then read the same.. you'll get the answer.