I need to read three columns as Name, Empid and empcode from excel, insert into textbox and save the record then setid & reqid fields are generated. Now save the setid and reqid after the Name,Empid and empcode in the same excel. I have tried any code from the internet but not much is working.
Below code for writing in excel
public static XSSFWorkbook wb;
public static XSSFSheet sheet;
public static FileInputStream fs;
public static FileOutputStream out;
public void WriteExcelFile()
{
String str1 = ackgreqid1.getText();
File file = new File(System.getProperty("user.dir") + "/src/main/java/com/testdata/FreeTestData.xlsx");
try {
fs = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
wb = new XSSFWorkbook(fs);
sheet = wb.getSheet("TestData");
} catch (IOException e) {
System.out.println("unable to find workbook or worksheet");
e.printStackTrace();
}
Iterator<Row> sheetrow = sheet.rowIterator();
// Row firstRow = sheetrow.next();
// int rowCount = sheet.getLastRowNum();
// = firstRow.cellIterator();
// Iterator<Cell> cell = firstRow.cellIterator();
while (sheetrow.hasNext()) {
Row value = sheetrow.next();
// System.out.println(value);
Iterator<Cell> cell = value.cellIterator();
Cell cellValue = cell.next();
String cellData = cellValue.getStringCellValue();
while (cell.hasNext()) {
if (cellData.equalsIgnoreCase("Step-Up")) {
int lastCellNum = value.getLastCellNum();
// System.out.println(lastCellNum);
Cell createCell = value.createCell(lastCellNum);
createCell.setCellValue(str1);
try {
out = new FileOutputStream(file);
wb.write(out);
// cell.next();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
break;
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
break;
}
}
Related
I have trouble reading the information in an Excel file to introduce and test with selenium. But the result always NullPoInterException. I tried to change the link in the Excel file. Here’s the 2-part code.
public class TestProviderII {
public static void main(String[] args) {
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
testData(url, "SheetOne");
}
public static void testData(String url, String sheet) {
ExcelUtils excelUtils = new ExcelUtils(url, sheet);
int rowCount = excelUtils.getRowCount();
int colCount = excelUtils.getColCount();
for (int i = 1; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
String cellData = excelUtils.getCellDataString(i, j);
System.out.println("Data : " + cellData);
}
}
}
}
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
static XSSFWorkbook workbook;
static XSSFSheet sheet;
public ExcelUtils(String workBook, String sheetName) {
try {
workbook = new XSSFWorkbook(workBook);
sheet = workbook.getSheet(sheetName);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int getRowCount() {
int rowCount = 0;
try {
rowCount = sheet.getPhysicalNumberOfRows();
System.out.println("No of Row : " + rowCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return rowCount;
}
public static int getColCount() {
int colCount = 0;
try {
colCount = sheet.getRow(0).getPhysicalNumberOfCells();
System.out.println("No of Column" + colCount);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return colCount;
}
public static String getCellDataString(int rowNum, int colNum) {
String cellData = "";
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getStringCellValue();
System.out.println("Data Cell : " + cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
public static Double getCellDataNumber(int rowNum, int colNum) {
double cellData = 0;
try {
cellData = sheet.getRow(rowNum).getCell(colNum).getNumericCellValue();
System.out.println(cellData);
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println(e.getCause());
e.printStackTrace();
}
return cellData;
}
}
And the result is NullPointerException
null
null
null
null
java.lang.NullPointerException
at test.ExcelUtils.getRowCount(ExcelUtils.java:23)
at test.TestProviderII.testData(TestProviderII.java:12)
at test.TestProviderII.main(TestProviderII.java:7)
java.lang.NullPointerException
at test.ExcelUtils.getColCount(ExcelUtils.java:36)
at test.TestProviderII.testData(TestProviderII.java:13)
at test.TestProviderII.main(TestProviderII.java:7)
Process finished with exit code 0
Why the result nullPointerException despite I did exactly what said?
And I changed the Excel file link and the result is the same.
String url = ".\\src\\test\\resources\\dataProvider.xlsx";
String url = "src\\test\\resources\\dataProvider.xlsx";
String url = "C:\\Selenuim\\demoApplication\\src\\test\\resources\\dataProvider.xlsx
Change below line:
testData(url, "SheetOne");
to:
testData(url, "Sheet1");
Assuming the sheet looks like below in your excel file:
Also ensure, there is some data in your excel sheet. I ran your code by just changing to Sheet1. And it worked see below:
Excel sheet:
Console Output:
No of Column3
Data Cell : d
Data : d
Data Cell : e
Data : e
Data Cell : f
Data : f
I'm creating a report from the following code and scheduling it using quartz scheduler but when it is saved, it is getting corrupted..
public class GenerateReport implements Job{
XSSFWorkbook report = new XSSFWorkbook();
MyData myData = new MyData();
public XSSFWorkbook createReport() {
Map<Integer, String> data = new HashMap<Integer, String>();
myData.setData(1652, "Abcs");
myData.setData(1682, "ksaos");
myData.setData(1152, "oass");
myData.setData(1962, "Aajas");
data = myData.getData();
XSSFSheet sheet = report.createSheet("Employee data");
XSSFCellStyle headerStyle = report.createCellStyle();
XSSFFont headerFont = report.createFont();
headerFont.setBold(true);
headerStyle.setFont(headerFont);
XSSFCell cell = null;
XSSFRow row;
int rowNum = 0;
int colNum = 0;
row = sheet.createRow(rowNum++);
row.createCell(colNum++).setCellValue("ID");
row.createCell(colNum).setCellValue("Name");
for(Map.Entry<Integer, String> entry: data.entrySet()) {
colNum = 0;
row = sheet.createRow(rowNum++);
cell = row.createCell(colNum++);
cell.setCellValue(entry.getKey());
cell = row.createCell(colNum);
cell.setCellValue(entry.getValue());
}
return report;
}
public void saveReport() {
XSSFWorkbook finalWorkbook = new XSSFWorkbook();
try {
FileOutputStream fos = new FileOutputStream("C:\\Users\\ra185586\\Desktop\\written.xlsx");
finalWorkbook.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print("Report generated");
}
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
createReport();
saveReport();
System.out.println(" and saved");
}
}
Can you guys help me to resolve, so that when the report is saved, it does not gets corrupt.
Thank you!
You method createReport() return XSSFWorkbook. And you need transfer this XSSFWorkbook to saveReport.
-Change in execute two line on saveReport(createReport());
-Delete line in saveReport XSSFWorkbook finalWorkbook = new XSSFWorkbook();
-Add arguments in saveReport saveReport(XSSFWorkbook finalWorkbook)
I want to return the values present in an excel file but it is returning values like [[Ljava.lang.String;#490ab905. Data is not returning the values like user name. Used jxl and data provider. Even i am not aware of data provider much. Please help me to fetch the accurate values from excel.
Following are my code:
public class excelUtil {
// public String suiteFileName = "/suite.xls";
String testDatafile = "/src/testData/testdata.xls";
// public String testDatafile = "/testdata/Testdata.xls";
#DataProvider
public Object[][] getTestData(String sheetName)
{
//String getTestData(String sheetName, int rowNumber, int colNum) {
// Read Excel
String path = System.getProperty("user.dir") + testDatafile;
Workbook w = null;
File inputWorkbook = new File(path);
// Open workbook
try {
w = Workbook.getWorkbook(inputWorkbook);
} catch (BiffException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the first sheet
Sheet sheet = w.getSheet(sheetName);
//Loop over first 10 column and lines
// Get the first sheet
//Loop over first 10 column and lines
int rowCount = sheet.getRows();
int columnCount = sheet.getColumns();
Object[][] data = new String[rowCount-1][columnCount];
for(int i=1;i<rowCount;i++)
{
Cell cell = sheet.getCell(0, i);
String value = cell.getContents().toString();
System.out.println(value);
data[i-1][0]= value.toString();
System.out.println(data[i-1][0]);
cell = sheet.getCell(1, i);
value = cell.getContents().toString();
data[i-1][1]= value.toString();
}
w.close();
//System.out.println(value);
System.out.println(data);
return data;
}
public static WebDriver driver ;
#Test(dataProvider = "getTestData")
public void OrpakLoginTest(Object username, Object password) {
driver = new FirefoxDriver();
driver.get("http:orpakqa.commdel.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Loginelements lg = new Loginelements();
WebElement element_UserName = lg.getOrpakUserNameField(driver);
element_UserName.sendKeys(username.toString());
WebElement element_Password = lg.getOrpakPasswordField(driver);
element_Password.sendKeys(password.toString());
//WebElement element_LoginBtn = lg.getOrpakLoginButton(driver);
//element_LoginBtn.click();
}
Use POI Jars
https://poi.apache.org/download.html
Below code is working for me:-
public String getXLcellValue(String xlpath, String sheetName, int rowNum, int cellNum)
{
try{
FileInputStream fis=new FileInputStream(xlpath);
Workbook wb=WorkbookFactory.create(fis);
Log.info("Get the value from the cell(getXLcellValue)");
return wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getStringCellValue();
}
catch(Exception ex)
{
Log.info("Error in getXLcellValue ="+ ex.getMessage());
}
return "";
}
xlpath = path of excel file in your system
Sheetname = name of the sheet in excel file
row = row number of username or password
cellnum = cell number of username or password
You can update your code as below and I hope this solution work for you:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ProApp extends OneClass {
Workbook wb;
Sheet sh1;
int numrow;
String username;
String password;
#BeforeMethod
public void oneTimeSetUp() throws InterruptedException {
driver.manage().window().maximize();
driver.get("Testing.com");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='app']/div/main/section/ul/li[1]/a")).click();
Thread.sleep(1000);
}
#Test(dataProvider="testdata")
public void testFireFox(String uname,String password1) throws InterruptedException
{
driver.findElement(By.xpath("//input[#name='username']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='username']")).sendKeys(uname);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password1);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#name='loginButton']")).click();
Thread.sleep(1000);
}
#DataProvider(name="testdata")
public Object[][] TestDataFeed(){
try {
// load workbook
wb=Workbook.getWorkbook(new File("C://File//Book2.xls"));
// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);
// get number of rows so that we can run loop based on this
numrow= sh1.getRows();
}
catch (Exception e)
{
e.printStackTrace();
}
// Create 2 D array and pass row and columns
Object [][] logindata=new Object[numrow][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0;i<numrow;i++){
// Fetch first row username
logindata[i][0]=sh1.getCell(0,i).getContents();
// Fetch first row password
logindata[i][1]=sh1.getCell(1,i).getContents();
}
// Return 2d array object so that test script can use the same
return logindata;
}
}
I have large excel file with several worksheets.
I want to process just one sheet in file...Read value from two columns and update two columns.
Using this code, I am able to read data from sheet.But unable to figure out, how to save output back.
public class ExcelFunctions {
private class ExcelData implements SheetContentsHandler {
private Record rec ;
public void startRow(int rowNum) {
rec = new Record();
output.put("R"+rowNum, rec);
}
public void endRow(int rowNum) {
}
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
int thisCol = (new CellReference(cellReference)).getCol();
if(thisCol==7){
try {
rec.setK1(formattedValue);
} catch (Exception e) {
}
}
if(thisCol==8){
try {
rec.setK2(formattedValue);
} catch (Exception e) {
}
}
if(thisCol == 27){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 27
}
if(thisCol == 28){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 28
}
}
public void headerFooter(String text, boolean isHeader, String tagName) {
}
}
///////////////////////////////////////
private final OPCPackage xlsxPackage;
private final Map<String, Record> output;
public ExcelFunctions(OPCPackage pkg, Map<String, Record> output) {
this.xlsxPackage = pkg;
this.output = output;
}
public void processSheet(
StylesTable styles,
ReadOnlySharedStringsTable strings,
SheetContentsHandler sheetHandler,
InputStream sheetInputStream)
throws IOException, ParserConfigurationException, SAXException {
DataFormatter formatter = new DataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(
styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch(ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
public void process()
throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
boolean found = false;
while (iter.hasNext() && !found) {
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
if(sheetName.equals("All Notes") ){
processSheet(styles, strings, new ExcelData(), stream);
found = true;
}
stream.close();
}
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
File xlsxFile = new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm");
if (!xlsxFile.exists()) {
System.err.println("Not found or not a file: " + xlsxFile.getPath());
return;
}
// The package open is instantaneous, as it should be.
OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ_WRITE);
Map<String, Record> output = new HashMap<String, Record>();
ExcelFunctions xlFunctions = new ExcelFunctions(p, output);
xlFunctions.process();
p.close();
if (output != null){
for(Record rec : output.values()){
System.out.println(rec.full_key());
}
}
}
}
File is very large and I only want to use Event API.
I have successfully tested Using this code.
But this loads Whole file in memory(causing application to crash)...While I only need to edit One sheet.
public static void saveToExcel(String ofn, Map<String, Record> data) {
FileInputStream infile;
try {
infile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm"));
XSSFWorkbook workbook = new XSSFWorkbook (infile);
XSSFSheet sheet = workbook.getSheet("All Notes");
for(Record rec : output.values()){
Row dataRow = rec.getRow(rev.getRownum-1);
setCellValue(dataRow, 26, "SomeValue");
setCellValue(dataRow, 27, "SomeValue");
}
FileOutputStream out = new FileOutputStream(new File(ofn));
workbook.write(out);
infile.close();
out.close();
workbook.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void setCellValue(Row row,int col, String value){
Cell c0 = row.getCell(col);
if (c0 == null){
c0 = row.createCell(col);
}
c0.setCellValue(value);
}
I don't think there is anything provided in POI out of the box which allows to do that.
Therefore you might be better off doing this by unzipping the XLSX/XLSM file (they are actually a bunch of xml-files inside a zip) and reading the xml-files as text-files or with a normal XML Parser so that you can easily write out the changed file again to produce the XLSX/XLSM file again.
this is what i have tried
public class UniqueUSER
{
static HSSFWorkbook hwb=new HSSFWorkbook();
static HSSFSheet sheet = hwb.createSheet("new sheet");
public static void main(String[]args) throws IOException
{
HSSFRow row;
HashSet<String> names = new HashSet<>();
BufferedReader br = new BufferedReader (new FileReader("Sample.log"));
PrintStream out=new PrintStream("D:/Excel.xls");
String str=null;
while((str=br.readLine())!=null)
{
if(str.contains("FLTR"))
{
String user=str.substring(97, 135);
names.add(user);
HSSFRow row1 = sheet.createRow((short)count);
}
}
Iterator itr=names.iterator();
while(itr.hasNext())
{
out.println(itr.next());
}
}
}
This program storing values to excel sheet but when i read same file using following program, I am getting exception and errors..
public class Country1
{
private String name;
private String shortCode;
public Country1(String n, String c)
{
this.name=n;
this.shortCode=c;
}
public void Country(String name2, String shortCode2)
{
// TODO Auto-generated constructor stub
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getShortCode()
{
return shortCode;
}
public void setShortCode(String shortCode)
{
this.shortCode = shortCode;
}
#Override
public String toString()
{
return name + "::" + shortCode;
}
}
public class ReadExcel
{
public static List<Country1> readExcelData(String fileName)
{
List<Country1> countriesList = new ArrayList<Country1>();
try
{
//Create the input stream from the xlsx/xls file
FileInputStream fis = new FileInputStream(fileName);
//Create Workbook instance for xlsx/xls file input stream
Workbook workbook = null;
if(fileName.toLowerCase().endsWith("xlsx"))
{
workbook = new XSSFWorkbook(fis);
}
else if(fileName.toLowerCase().endsWith("xls"))
{
workbook = new HSSFWorkbook(fis);
}
//Get the number of sheets in the xlsx file
int numberOfSheets = workbook.getNumberOfSheets();
//loop through each of the sheets
for(int i=0; i < numberOfSheets; i++)
{
//Get the nth sheet from the workbook
Sheet sheet = workbook.getSheetAt(i);
//every sheet has rows, iterate over them
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
String name = "";
String shortCode = "";
//Get the row object
Row row = rowIterator.next();
//Every row has columns, get the column iterator and iterate over them
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
//Get the Cell object
Cell cell = cellIterator.next();
//check the cell type and process accordingly
switch(cell.getCellType())
{
case Cell.CELL_TYPE_STRING:
if(shortCode.equalsIgnoreCase(""))
{
shortCode = cell.getStringCellValue().trim();
}
else if(name.equalsIgnoreCase(""))
{
//2nd column
name = cell.getStringCellValue().trim();
}
else
{
//random data, leave it
System.out.println("Randomdata::"+cell.getStringCellValue());
}
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Random data::"+cell.getNumericCellValue());
}
} //end of cell iterator
Country1 c = new Country1(name, shortCode);
countriesList.add(c);
} //end of rows iterator
} //end of sheets for loop
//close file input stream
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return countriesList;
}
public static void main(String args[])
{
List<Country1> list = readExcelData("D:\\Excel.xls");
System.out.println("Country List\n"+list);
}
}
I am confused which program is correct and which one is wrong.. please someone could help me.. thanks lot
Exception are like below:
Unable to read entire header; 320 bytes read; expected 512 bytes
at org.apache.poi.poifs.storage.HeaderBlock.alertShortRead(HeaderBlock.java:227)
at org.apache.poi.poifs.storage.HeaderBlock.readFirst512(HeaderBlock.java:208)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:128)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:342)
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:323)
at com.unisys.ReadExcel.readExcelData(ReadExcel.java:32)
at com.unisys.ReadExcel.main(ReadExcel.java:97)
Country List
[]
try to change
Iterator<Row> rowIterator = sheet.iterator();
to
Iterator<Row> rowIterator = sheet.rowIterator()
Also, when writing your create rows, but you do not write anything to them
HSSFRow row1 = sheet.createRow((short)count);
then create cell
row.createCell (0).setCellValue (user);
Update
Just had another look at your code, why on earth are you doing
PrintStream out=new PrintStream("D:/Excel.xls");
Use the POI API to create the xls.