I have a workbook in which I have multiple tabs now I want to read all the tabs name and return the tab name containing particular character in it , in my case its data
example assumpition is :-
Expected tabsname - > welcome_data.xslx , hello_value.xslx;
output -> welcome_data.xslx
Any help is appreciated ,
code which I was trying was :- I was able to get the tabs name but how to filter it .
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class EXcelsheet {
public static void main(String[] args) throws IOException {
String xlsxFile = "/home/working/git/ui_spec.xlsx";
FileInputStream file = new FileInputStream(new File(xlsxFile));
XSSFWorkbook workbook = new XSSFWorkbook(file);
System.out.println("number of sheet::" + workbook.getNumberOfSheets());
List<String> sheetNames = new ArrayList<String>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
sheetNames.add(workbook.getSheetName(i));
}
}
}
I don't get the issue.
Does replacing
sheetNames.add(workbook.getSheetName(i));
with
String sheetName = workbook.getSheetName(i);
if (sheetName.contains(<char>)
{
sheetNames.add(workbook.getSheetName(i));
}
not work?
Related
I am trying to do data driven testing and I am not able to figure it out why I am getting data mismatch. I am trying to automate just usernames and that is in form of string. Can you please review my code and tell me what I am doing wrong?
Below are two files. one is my main method file and one is my excel config file. I have also attached screenshot of my error. Any help would be appreciated. Thank you.
File1:
`
package loginAdmin;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class PersonateUser {
#Test(dataProvider="testdata")
public void login(String username) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver",
C:\\Users\\abc\\Downloads\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(200, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(200, TimeUnit.SECONDS);
driver.get("www.abc.com/AdminHome.aspx");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtLoginName")).
sendKeys("admin");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_txtPassword")).
sendKeys("Password");
driver.findElement(By.id("M_layout_content_PCDZ_MW2NO7V_ctl00_webInputForm_cmdContinue")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_lblUserName")).
click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_txtUserName")).
sendKeys(username);
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_btnSearch")).click();
driver.findElement(By.id("M_layout_content_PCDZ_M5QH8YG_ctl00_resultsGrid_ctl02_LogInAsUser")).
click();
System.out.println("User is able to login successfully");
driver.findElement(By.xpath("/html/body/form/div[3]/div[3]/div[1]/div[1]/div/div[5]/ul/li[6]/a")).
click();
#DataProvider(name="testdata")
public Object[][] TestDataFeed()
{
ReadExcelFile config = new
ReadExcelFile("C:\\Users\\abc\\eclipseworkspace\\Login\\testdata\\testdata.xlsx");
int rows = config.getRowCount(0);
Object[][] credentials = new Object[rows][2];
for(int i = 0; i < rows; i++)
{
credentials[i][0] = config.getData(0, i, 0);
}
return credentials;
}
}
`
File 2:
` package loginAdmin;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFile
{
XSSFWorkbook wb;
XSSFSheet sheet;
public ReadExcelFile(String excelPath)
{
try
{
File src = new File(excelPath);
FileInputStream fis = new FileInputStream(src);
wb =new XSSFWorkbook(fis);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
public String getData(int sheetnumber, int row, int column)
{
sheet= wb.getSheetAt(sheetnumber);
String data = sheet.getRow(row).getCell(column).getStringCellValue();
return data;
}
public int getRowCount(int sheetIndex)
{
int row = wb.getSheetAt(sheetIndex).getLastRowNum();
row = row + 1;
return row;
}
}
`
Error Screenshot:
Excel File:
You are declaring Object[][] credentials = new Object[rows][2]; but you fill only one column keeping other column empty (null). Hence the dimension of your array does not match the number of arguments your method accepts.
Fix it with changing that line to:
Object[][] credentials = new Object[rows][1];
I am working with Apache POI. I am able to read data from excel, but unable to read image from the excel. How to read image from excel.
Instead of puzzling around let's have a complete example.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.PictureData;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Iterator;
class ReadExcelImages {
public static void main(String[] args) throws Exception{
InputStream inp = new FileInputStream("test.xls");
//InputStream inp = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(inp);
List lst = workbook.getAllPictures();
int i = 1;
for (Iterator it = lst.iterator(); it.hasNext(); ) {
PictureData pict = (PictureData)it.next();
String ext = pict.suggestFileExtension();
byte[] data = pict.getData();
if (ext.equals("png")){
FileOutputStream out = new FileOutputStream("pict" + i++ + ".png");
out.write(data);
out.close();
} else if (ext.equals("jpeg")) {
FileOutputStream out = new FileOutputStream("pict" + i++ + ".jpeg");
out.write(data);
out.close();
}
}
}
}
Works for me with HSSF (*.xls) as well as with XSSF (*.xlsx).
I have two docx files which I want to merge and I have the following code in docx4j with some errors! Both the docx files are using for the purpose of track changes. So the output file should be have the details of both the docx files.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.io.SaveToZipFile;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import com.plutext.merge.BlockRange;
import com.plutext.merge.BlockRange.HfBehaviour;
import com.plutext.merge.BlockRange.SectionBreakBefore;
import com.plutext.merge.BlockRange.NumberingHandler;
import com.plutext.merge.BlockRange.StyleHandler;
import com.plutext.merge.DocumentBuilder;
public class MergeWholeDocumentsUsingBlockRange
{
public final static String DIR_IN = System.getProperty("user.dir")+ "/";
public final static String DIR_OUT = System.getProperty("user.dir")+ "/";
public static void main(String[] args) throws Exception {
String[] files = {"table.docx", "Table1.docx"};
List blockRanges = new ArrayList();
for (int i=0 ; i< files.length; i++) {
BlockRange block = new BlockRange(WordprocessingMLPackage.load(new File(DIR_IN + files[i])));
blockRanges.add( block );
block.setStyleHandler(StyleHandler.RENAME_RETAIN);
block.setNumberingHandler(NumberingHandler.ADD_NEW_LIST);
block.setRestartPageNumbering(false);
block.setHeaderBehaviour(HfBehaviour.DEFAULT);
block.setFooterBehaviour(HfBehaviour.DEFAULT);
block.setSectionBreakBefore(SectionBreakBefore.NEXT_PAGE);
}
// Perform the actual merge
DocumentBuilder documentBuilder = new DocumentBuilder();
WordprocessingMLPackage output = documentBuilder.buildOpenDocument(blockRanges);
// Save the result
SaveToZipFile saver = new SaveToZipFile(output);
saver.save(DIR_OUT+"OUT_MergeWholeDocumentsUsingBlockRange.docx");
}
}
I am trying to create an excel file which can have value as name and ID
The lines which have made bol are giving me error in my program.Kindly help me out as what might be the mistake... pls
If possible also help me out with the code of only writing name as in string into the excel file.
package demos;
import jxl.*;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import java.io.*;
import java.util.*;
import com.sun.rowset.internal.Row;
import jxl.CellView;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.biff.RowsExceededException;
public class StringInp
{
public static void main(String[] args) throws IOException
{
try
{
String filename="C:\\virclipse\\input.xls";
WritableWorkbook wb=Workbook.createWorkbook(new File(filename));
//Create a blank sheet
WritableSheet sheet = wb.createSheet("Employee Data",0);
//This data needs to be written (Object[])
Map<String, Object[]> data = new TreeMap<String, Object[]>();
data.put("1", new Object[] {"ID", "NAME"});
data.put("2", new Object[] {101, "Shivany"});
data.put("3", new Object[] {102, "Nalini"});
data.put("4", new Object[] {103, "John"});
data.put("5", new Object[] {104, "Ayush"});
//Iterate over data and write to sheet
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset)
{
***Row row = sheet.createRow(rownum++);***
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr)
{
***Cell cell = row.createCell(cellnum++);***
if(obj instanceof String)
{
***cell.setCellValue((String)obj);***
}
else if(obj instanceof Integer)
{
***cell.setCellValue((Integer)obj);***
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("filename"));
wb.write();
wb.close();
}
}
catch(WriteException e)
{
System.out.println("there is an error");
}
}
}
You are using the right imports but you need to have the required jxml jars in your build path also.
you can read here, what is jExcel API here is a tutorial also you can download API from here please download jexcelapi_2_6_12.zip, after downloading extract it and put jxl.jar in your build path, those errors should go then
I am able to Read the input document using Apache POI and also able to find the data between the tags(What to be hidden) but the problem is i'm unable to write the data in the output file. How can i do the same to write the data and hide it in the output generated file..
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Range;
public class Hidden {
public static void main(String args[]) throws Exception
{
File file = new File("D://me1.doc");
FileInputStream fin = new FileInputStream(file);
FileOutputStream fout = new FileOutputStream("D://Test.doc");
HWPFDocument doc = new HWPFDocument(fin);
Range range = doc.getRange();
WordExtractor extractor = new WordExtractor(doc);
String para[] = extractor.getParagraphText();
String output="";
String hidden="";
for (String p : para) {
String[] w = p.split("[<\\>]");
for(int k=0 ;k<w.length;k++){
if(w[k]!=null && !"".equalsIgnoreCase(w[k])){
if("hidden".equalsIgnoreCase(w[k])){
k++;
CharacterRun run = range.getCharacterRun(k);
hidden= w[k];
k++;
System.out.println(hidden);
run.setVanished(true);
doc.write(fout);
}else{
}
}
}
}
fout.close();
fin.close();
}
}