How to use POI SXSSFWorkbook export more than 65535 row data? - apache-poi

as excel 2003(.xls) support 65536 rows data and 256 columns
excel 2007(.xlsx) support 1048576 rows data and 16384 columns
when we need to export the data more than 65536, then we need to use .xlsx

package com.lux.poi_excel;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExportExcelRowThan65535 {
public static void main(String[] args) {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream("C:\\Users\\Desktop\\aaa.xlsx");
bos = new ByteArrayOutputStream();
//load template
XSSFWorkbook workbook = new XSSFWorkbook(fis);
SXSSFWorkbook wb = new SXSSFWorkbook(workbook,100);
//get template sheet
Sheet sheet = wb.getXSSFWorkbook().getSheetAt(0);
//get template sheet head row
Row headRow = wb.getXSSFWorkbook().getSheetAt(0).getRow(0);
for(int i=1;i<100000;i++) {
Row newRow = sheet.createRow(i);
newRow.createCell(0).setCellValue("a");
}
wb.write(bos);
bos.writeTo(new FileOutputStream("C:\\Users\\Desktop\\bbb.xlsx"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
fis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Done");
}
}

Related

Why is batik can't save .svg file using OutputStream?

I want to manipulate with existing .svg file from file system using library Batik by Apache. My goal is load .svg file, draw some shapes on it and than save final result on file system.
Now I have two classes. First class is able to load file .svg and draw shape on it, but don't able to save result. Second class is able to draw shape on new canvas and save result on file system.
This first class. I try to save final result using OutputStream, but it didn't work.
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.apache.batik.swing.JSVGCanvas;
import org.apache.batik.swing.svg.GVTTreeBuilderAdapter;
import org.apache.batik.swing.svg.GVTTreeBuilderEvent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.util.concurrent.atomic.AtomicBoolean;
public class RedrawingSVG extends JFrame {
protected AtomicBoolean shown = new AtomicBoolean(false);
public static void main(String[] args) throws MalformedURLException, InterruptedException, FileNotFoundException, UnsupportedEncodingException, SVGGraphics2DIOException {
RedrawingSVG redrawingSVG = new RedrawingSVG();
redrawingSVG.drawSvg();
}
public void drawSvg() throws MalformedURLException, InterruptedException, FileNotFoundException, UnsupportedEncodingException, SVGGraphics2DIOException {
final JSVGCanvas canvas = new JSVGCanvas();
canvas.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC); // to update it
canvas.setURI(new File("/home/ekuntsevich/Downloads/img.svg").toURI().toURL().toString());
canvas.addGVTTreeBuilderListener(new GVTTreeBuilderAdapter() {
public void gvtBuildCompleted(GVTTreeBuilderEvent e) {
synchronized (shown) {
shown.set(true); // No modifications be fore!!
shown.notifyAll();
}
}
});
getContentPane().add(canvas);
setSize(800, 400);
setVisible(true);
synchronized (shown) { // Strictly required to wait
while (shown.get() == false) {
try {
shown.wait(0);
} catch (Exception e) {
}
}
}
Document doc = canvas.getSVGDocument();
SVGGraphics2D svgGenerator = new SVGGraphics2D(doc);
svgGenerator.setPaint(Color.red);
svgGenerator.fill(new Rectangle(100, 100, 1000, 1000));
Element root = doc.getDocumentElement();
svgGenerator.getRoot(root);
Writer out;
try {
OutputStream outputStream = new FileOutputStream(new File("img2.svg"));
out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, true);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This second class.
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.IOException;
import org.apache.batik.svggen.SVGGraphics2D;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2DIOException;
import org.w3c.dom.Document;
import org.w3c.dom.DOMImplementation;
public class TestSVGGen {
public void paint(Graphics2D g2d) {
g2d.setPaint(Color.red);
g2d.fill(new Rectangle(10, 10, 100, 100));
}
public static void main(String[] args) throws IOException {
// Get a DOMImplementation.
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
// Create an instance of org.w3c.dom.Document.
String svgNS = "http://www.w3.org/2000/svg";
Document document = domImpl.createDocument(svgNS, "svg", null);
// Create an instance of the SVG Generator.
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
// Ask the test to render into the SVG Graphics2D implementation.
TestSVGGen test = new TestSVGGen();
test.paint(svgGenerator);
// Finally, stream out SVG to the standard output using
// UTF-8 encoding.
boolean useCSS = true; // we want to use CSS style attributes
Writer out;
try {
OutputStream outputStream = new FileOutputStream(new File("img3.svg"));
out = new OutputStreamWriter(outputStream, "UTF-8");
svgGenerator.stream(out, useCSS);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SVGGraphics2DIOException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Finally I want to combine capabilities this two classes. I want to have code for: loading .svg image -> drawing something over this image -> save result as .svg image on file system.
I resolved my issue. I looked through different signatures for method stream from class SVGGraphics2D and found out that there is has method with parameters suitable for my case. I used next method stream(Element svgRoot, Writer writer) for saving .svg image. Finally, instead svgGenerator.stream(out, true); I used svgGenerator.stream(root, out);. It works for me.
Fastest way to save SVGDOcument to File [for future generations :) ]
public static void saveSvgDocumentToFile(SVGDocument document, File file)
throws FileNotFoundException, IOException {
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
try (Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8")) {
svgGenerator.stream(document.getDocumentElement(), out);
}
}

Extract hive table partition in Spark - java

Is there any way in Spark to extract only partition column names?
The workaround I am using is to run "show extended table like table_name" using HiveContext
You can use class HiveMetaStoreClient to query directly from HiveMetaStore.
This class is widely used by popular APIS also, for interacting with
HiveMetaStore for ex: Apache Drill
org.apache.hadoop.hive.metastore.api.Partition getPartition(String
db_name, String tbl_name, List part_vals)
org.apache.hadoop.hive.metastore.api.Partition getPartition(String db, String tableName, String partName)
Map> getPartitionColumnStatistics(String
dbName, String tableName, List partNames, List
colNames)
Get partitions column statistics given dbName, tableName, multiple partitions and colName-s
List getPartitionsByNames(String
db_name, String tbl_name, List part_names)
Get partitions by a list of partition names.
Also, there are list methods as well..
List listPartitionNames(String db_name, String tbl_name,
List part_vals, short max_parts)
List listPartitionNames(String dbName, String tblName, short
max)
List listPartitions(String
db_name, String tbl_name, List part_vals, short max_parts)
List listPartitions(String
db_name, String tbl_name, short max_parts)
Sample Code snippet 1 :
import org.apache.hadoop.hive.conf.HiveConf;
// test program
public class Test {
public static void main(String[] args){
HiveConf hiveConf = new HiveConf();
hiveConf.setIntVar(HiveConf.ConfVars.METASTORETHRIFTCONNECTIONRETRIES, 3);
hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://host:port");
HiveMetaStoreConnector hiveMetaStoreConnector = new HiveMetaStoreConnector(hiveConf);
if(hiveMetaStoreConnector != null){
System.out.print(hiveMetaStoreConnector.getAllPartitionInfo("tablename"));
}
}
}
// define a class like this
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.thrift.TException;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HiveMetaStoreConnector {
private HiveConf hiveConf;
HiveMetaStoreClient hiveMetaStoreClient;
public HiveMetaStoreConnector(String msAddr, String msPort){
try {
hiveConf = new HiveConf();
hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, msAddr+":"+ msPort);
hiveMetaStoreClient = new HiveMetaStoreClient(hiveConf);
} catch (MetaException e) {
e.printStackTrace();
System.err.println("Constructor error");
System.err.println(e.toString());
System.exit(-100);
}
}
public HiveMetaStoreConnector(HiveConf hiveConf){
try {
this.hiveConf = hiveConf;
hiveMetaStoreClient = new HiveMetaStoreClient(hiveConf);
} catch (MetaException e) {
e.printStackTrace();
System.err.println("Constructor error");
System.err.println(e.toString());
System.exit(-100);
}
}
public String getAllPartitionInfo(String dbName){
List<String> res = Lists.newArrayList();
try {
List<String> tableList = hiveMetaStoreClient.getAllTables(dbName);
for(String tableName:tableList){
res.addAll(getTablePartitionInformation(dbName,tableName));
}
} catch (MetaException e) {
e.printStackTrace();
System.out.println("getAllTableStatistic error");
System.out.println(e.toString());
System.exit(-100);
}
return Joiner.on("\n").join(res);
}
public List<String> getTablePartitionInformation(String dbName, String tableName){
List<String> partitionsInfo = Lists.newArrayList();
try {
List<String> partitionNames = hiveMetaStoreClient.listPartitionNames(dbName,tableName, (short) 10000);
List<Partition> partitions = hiveMetaStoreClient.listPartitions(dbName,tableName, (short) 10000);
for(Partition partition:partitions){
StringBuffer sb = new StringBuffer();
sb.append(tableName);
sb.append("\t");
List<String> partitionValues = partition.getValues();
if(partitionValues.size()<4){
int size = partitionValues.size();
for(int j=0; j<4-size;j++){
partitionValues.add("null");
}
}
sb.append(Joiner.on("\t").join(partitionValues));
sb.append("\t");
DateTime createDate = new DateTime((long)partition.getCreateTime()*1000);
sb.append(createDate.toString("yyyy-MM-dd HH:mm:ss"));
partitionsInfo.add(sb.toString());
}
} catch (TException e) {
e.printStackTrace();
return Arrays.asList(new String[]{"error for request on" + tableName});
}
return partitionsInfo;
}
public String getAllTableStatistic(String dbName){
List<String> res = Lists.newArrayList();
try {
List<String> tableList = hiveMetaStoreClient.getAllTables(dbName);
for(String tableName:tableList){
res.addAll(getTableColumnsInformation(dbName,tableName));
}
} catch (MetaException e) {
e.printStackTrace();
System.out.println("getAllTableStatistic error");
System.out.println(e.toString());
System.exit(-100);
}
return Joiner.on("\n").join(res);
}
public List<String> getTableColumnsInformation(String dbName, String tableName){
try {
List<FieldSchema> fields = hiveMetaStoreClient.getFields(dbName, tableName);
List<String> infs = Lists.newArrayList();
int cnt = 0;
for(FieldSchema fs : fields){
StringBuffer sb = new StringBuffer();
sb.append(tableName);
sb.append("\t");
sb.append(cnt);
sb.append("\t");
cnt++;
sb.append(fs.getName());
sb.append("\t");
sb.append(fs.getType());
sb.append("\t");
sb.append(fs.getComment());
infs.add(sb.toString());
}
return infs;
} catch (TException e) {
e.printStackTrace();
System.out.println("getTableColumnsInformation error");
System.out.println(e.toString());
System.exit(-100);
return null;
}
}
}
Sample code snippet example 2 (source)
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hive.hcatalog.common.HCatUtil;
import org.apache.thrift.TException;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.util.HashMap;
public class HiveMetaStoreClientTest {
public static void main(String[] args) {
HiveConf hiveConf = null;
HiveMetaStoreClient hiveMetaStoreClient = null;
String dbName = null;
try {
hiveConf = HCatUtil.getHiveConf(new Configuration());
hiveMetaStoreClient = new HiveMetaStoreClient(hiveConf);
dbName = args[0];
getDatabase(hiveMetaStoreClient, dbName);
} catch (MetaException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchObjectException e) {
e.printStackTrace();
System.out.println("===============");
System.out.println("database " + args[0] + "not exists");
System.out.println("===============");
createDatabase(hiveMetaStoreClient, dbName);
try {
getDatabase(hiveMetaStoreClient, dbName);
} catch (TException e1) {
e1.printStackTrace();
System.out.println("TMD");
}
} catch (TException e) {
e.printStackTrace();
}
}
public static Database getDatabase(HiveMetaStoreClient hiveMetaStoreClient, String dbName) throws TException {
Database database = null;
database = hiveMetaStoreClient.getDatabase(dbName);
System.out.println(database.getLocationUri());
System.out.println(database.getOwnerName());
for (String key : database.getParameters().keySet()) {
System.out.println(key + " = " + database.getParameters().get(key));
}
return database;
}
public static Database createDatabase(HiveMetaStoreClient hiveMetaStoreClient, String dbName) {
HashMap<String, String> map = new HashMap<String,String>();
Database database = new Database(dbName, "desc", null, map);
try {
hiveMetaStoreClient.createDatabase(database);
} catch (TException e) {
e.printStackTrace();
System.out.println("some error");
}
return database;
}
}

read username and password from the excel file

Below is my code. How can I read this data?
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yoda {
public static void main(String[] args)
{
// Launch FireFox
WebDriver driver = new FirefoxDriver();
//Enter YODA URL
driver.get("https://q1yda1m2.madc.att.com:20621/YodaGUI/index.jsp");
//Enter UserID
driver.findElement(By.name("userid")).sendKeys("xx3517");
//Enter Password
driver.findElement(By.name("password")).sendKeys("123123a");
//Click on Submit button after entering User ID and Password
driver.findElement(By.name("btnSubmit")).click();
//Click on Remind Me later
driver.findElement(By.name("successOK")).click();
//Click on Search Button on YODA home page
driver.findElement(By.className("MenuBarItemSubmenu")).click();
driver.findElement(By.xpath("//*[text()='Fulfillment Details']")).click();
driver.findElement(By.name("location")).sendKeys("Q400");
driver.findElement(By.name("activity")).sendKeys("OY");
driver.findElement(By.name("orderID")).sendKeys("3955349");
driver.findElement(By.id("fulfillment_submit")).click();
}
}
Your question is a bit confusing. Do you want to read data from the excel file (the image you pasted)? Then you have the right imports (apache poi) though you haven't used it.
To read from the excel, here's the code:
try {
FileInputStream fStream = new FileInputStream(new File(
"sample.xlsx"));
// Create workbook instance referencing the file created above
XSSFWorkbook workbook = new XSSFWorkbook(fStream);
// Get your first or desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0); // getting first sheet
// Iterate through the rows present in sheet
Iterator<Row> rIterator = sheet.iterator();
while (rIterator.hasNext()) {
Row row = rIterator.next();
Iterator<Cell> cIterator = row.cellIterator();// Iterate through
// the columns
// present in
// that row
while (cIterator.hasNext()) {
Cell cell = cIterator.next();
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
System.out.println(cell.getNumericCellValue() + "\t");
else if (cell.getCellType() == Cell.CELL_TYPE_STRING)
System.out.println(cell.getStringCellValue() + "\t");
}
System.out.println(" ");
}
fStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The above code will read a "Sample.xlsx" file and process it to output it's content on the console.
Also, check this link out : how to read all cell value using Apache POI?
EDIT
If you are sure from which column you exactly want to read the values from, the you can use this easier approach:
package example;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadFromExcel {
public static void main(String[] args) {
try {
FileInputStream fStream = new FileInputStream(new File(
"sample.xlsx"));
// Create workbook instance referencing the file created above
XSSFWorkbook workbook = new XSSFWorkbook(fStream);
// Get your first or desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0); // getting first sheet
XSSFRow row = sheet.getRow(1);
XSSFCell cell1 = row.getCell(0);
XSSFCell cell2 = row.getCell(1);
XSSFCell cell3 = row.getCell(2);
String location = cell1.toString();
String activity = cell2.toString();
String order = cell3.toString();
System.out.println(location + order + activity);
fStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, simply pass the value of the Strings "location", "order" and "activity" through your SendKeys()
Edit 2
Your final code should look something like this:
package example;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yoda {
public static void main(String[] args)
{
String location = null;
String activity = null;
String order = null;
// Launch FireFox
WebDriver driver = new FirefoxDriver();
// Enter YODA URL
driver.get("https://q1yda1m2.madc.att.com:20621/YodaGUI/index.jsp");
// Enter UserID
driver.findElement(By.name("userid")).sendKeys("xx3517");
// Enter Password
driver.findElement(By.name("password")).sendKeys("123123a");
// Click on Submit button after entering User ID and Password
driver.findElement(By.name("btnSubmit")).click();
// Click on Remind Me later
driver.findElement(By.name("successOK")).click();
try {
FileInputStream fStream = new FileInputStream(new File(
"C:\\Users\\xxxx\\Desktop\\sample.xlsx")); //Enter the path to your excel here
// Create workbook instance referencing the file created above
XSSFWorkbook workbook = new XSSFWorkbook(fStream);
// Get your first or desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0); // getting first sheet
XSSFRow row = sheet.getRow(1);
XSSFCell cell1 = row.getCell(0);
XSSFCell cell2 = row.getCell(1);
XSSFCell cell3 = row.getCell(2);
location = cell1.toString();
activity = cell2.toString();
order = cell3.toString();
fStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Click on Search Button on YODA home page
driver.findElement(By.className("MenuBarItemSubmenu")).click();
driver.findElement(By.xpath("//*[text()='Fulfillment Details']"))
.click();
driver.findElement(By.name("location")).sendKeys(location);
driver.findElement(By.name("activity")).sendKeys(activity);
driver.findElement(By.name("orderID")).sendKeys(order);
driver.findElement(By.id("fulfillment_submit")).click();
}
}
There are multiple ways to read data from excel and one of the simplest way would be :
try
{
File file = new File("D:/TestData.xlsx");
FileInputStream iFile = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(iFile);
XSSFSheet sheet = wb.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum();
System.out.println("the no of rows are : " + rowCount);
for (int row=1; row<=rowCount; row++)
{
String location = sheet.getRow(row).getCell(0).getStringCellValue();
String activity = sheet.getRow(row).getCell(1).getStringCellValue();
int order=(int) sheet.getRow(row).getCell(2).getNumericCellValue();
System.out.println(location + " , " + activity + " , " +order );
}
iFile.close();
}
catch (IOException e)
{
e.printStackTrace();
}
package package1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class yoda2 {
public static void main(String[] args) {
// Launch FireFox WebDriver driver = new FirefoxDriver();
// Enter YODA URL
driver.get("https://q1yda1m2.madc.att.com:20621/YodaGUI/index.jsp");
// Enter UserID
driver.findElement(By.name("userid")).sendKeys("xx3517");
// Enter Password driver.findElement(By.name("password")).sendKeys("123123a");
// Click on Submit button after entering User ID and Password driver.findElement(By.name("btnSubmit")).click();
// Click on Remind Me later driver.findElement(By.name("successOK")).click();
try { File file = new File("D:/TestData.xlsx");
FileInputStream iFile = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(iFile);
XSSFSheet sheet = wb.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum();
System.out.println("the no of rows are : " + rowCount);
for (int row=1; row<=rowCount; row++)
{ String location = sheet.getRow(row).getCell(0).getStringCellValue();
String activity = sheet.getRow(row).getCell(1).getStringCellValue();
int order=(int) sheet.getRow(row).getCell(2).getNumericCellValue();
System.out.println(location + " , " + activity + " , " +order );
}
iFile.close();
}
catch (IOException e) { e.printStackTrace();
}
// Click on Search Button on YODA home page
driver.findElement(By.className("MenuBarItemSubmenu")).click();
driver.findElement(By.xpath("//*[text()='Fulfillment Details']")).click();
driver.findElement(By.name("location")).sendKeys(location);
driver.findElement(By.name("activity")).sendKeys(activity);
driver.findElement(By.name("orderID")).sendKeys(order);
driver.findElement(By.id("fulfillment_submit")).click(); } }
// ReUsable Code for excel data
public class ExcelLibrary {
public String getExcelData(String sheetname, int rownum, int cellnum) {
String retVal=null;
try {
FileInputStream fis=new FileInputStream("F:.........xlsx");
Workbook wb=WorkbookFactory.create(fis);
Sheet s=wb.getSheet(sheetname);
Row r=s.getRow(rownum);
Cell c=r.getCell(cellnum);
retVal=c.getStringCellValue();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EventException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal;
}
public int getLastRowNumber(String sheetname) {
int retVal=0;
try {
FileInputStream fis=new FileInputStream("F:\\selenium\\eclipse java\\excel.xlsx");
Workbook wb=WorkbookFactory.create(fis);
Sheet s=wb.getSheet(sheetname);
retVal=s.getLastRowNum();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EventException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal;
}
}
// create a new class and call the previous method
public class LoginLogout {
public static void main(String[] args) {
ExcelLibrary xlib=new ExcelLibrary();
System.setProperty("webdriver.gecko.driver","F:\\selenium\\WebDrivers\\geckodriver.exe");
WebDriver driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://demo.actitime.com/login.do");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
int lastrow=xlib.getLastRowNumber("Sheet1");
for (int i = 1; i <= lastrow; i++) {
String un=xlib.getExcelData("Sheet1", i, 0);
String pw=xlib.getExcelData("Sheet1", i, 1);
driver.findElement(By.id("username")).sendKeys(un);
driver.findElement(By.name("pwd")).sendKeys(pw);
driver.findElement(By.id("loginButton")).click();
driver.findElement(By.id("logoutLink")).click();
}
}
}

Colum gets hidden when inserting a file hyper link in Excel using Apache POI

I am trying to insert (into an excel cell), a hyperlink to a file in my local system. The link gets added but the column gets hidden. Sheet.autosizeColumn(colNum) does not seem to work. This happens only with hyperlinks. The columns do not get hidden if I am placing a plain string in the cell.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Xls_Reader {
public String path;
public FileInputStream fis = null;
public FileOutputStream fileOut =null;
private XSSFWorkbook workbook = null;
private XSSFSheet sheet = null;
private XSSFRow row =null;
private XSSFCell cell = null;
public Xls_Reader(String path) {
this.path=path;
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(0);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
public boolean setCellData(String sheetName,String colName,int rowNum, String data,String url){
try{
url = url.replaceAll("\\\\", "/");
System.out.println(url);
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if(rowNum<=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum=-1;
if(index==-1)
return false;
sheet = workbook.getSheetAt(index);
row=sheet.getRow(0);
for(int i=0;i<row.getLastCellNum();i++){
if(row.getCell(i).getStringCellValue().trim().equalsIgnoreCase(colName))
colNum=i;
}
if(colNum==-1)
return false;
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum-1);
if (row == null)
row = sheet.createRow(rowNum-1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
cell.setCellValue(data);
XSSFCreationHelper createHelper = workbook.getCreationHelper();
CellStyle hlink_style = workbook.createCellStyle();
XSSFFont hlink_font = workbook.createFont();
hlink_font.setUnderline(XSSFFont.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
XSSFHyperlink link = createHelper.createHyperlink(XSSFHyperlink.LINK_FILE);
link.setAddress(url);
link.setTooltip("Click to open the file");
cell.setHyperlink(link);
cell.setCellStyle(hlink_style);
sheet.autoSizeColumn(colNum);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
}catch(Exception e){
e.printStackTrace();
return false;
}
return true;
}
public static void main(String arg[]) throws IOException{
Xls_Reader rdr = new Xls_Reader("C:\\Users\\file1\\file2.xlsx");
String url = "file:///C:\\Folde1\\Folder2\\index.htm";
rdr.setCellData("Summary", "Summary", 17, "CLick", url);
}
}

How to generate Castor mapping.xml file from given multiple XSDs?

How to generate Castor mapping.xml file from given multiple XSDs?
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
//import org.exolab.castor.builder.SourceGenerator;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.tools.MappingTool;
public class CastorMappingToolUtil {
public static void generate() throws MappingException, FileNotFoundException {
MappingTool tool = new MappingTool();
tool.setInternalContext(new org.castor.xml.BackwardCompatibilityContext());
tool.addClass(ClassType.class);
OutputStream file = new FileOutputStream("/path/to/xmlFile/gen_mapping.xml" );
Writer writer = new OutputStreamWriter(file);
tool.write(writer);
//SourceGenerator.main(options);
}
/**
* #param args
*/
public static void main(String[] args) {
try {
CastorMappingToolUtil.generate();
} catch (MappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Resources