cannot able to encode the excel sheet using jexceapi - java

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.

Related

Read excel data in page object model

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

Java FileInputStream out of memory issue

I am trying to read an excel file and then write to csv file using xssf .I am getting out of memory error(Heap space). i see that fileinputstream is good for memory management ,but still i see the issue
package xlsxtocsv;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class xlsxtocsv
{
private static final String NEW_LINE_CHARACTER="\r\n";
/**
* Write the string into a text file
* #param csvFileName
* #param csvData
* #throws Exception
*/
private static void writeCSV(String csvFileName,String csvData) throws Exception{
FileOutputStream writer = new FileOutputStream(csvFileName);
writer.write(csvData.getBytes());
writer.close();
System.out.println("Sucessfully written data to "+csvFileName);
}
public static void excelXToCSVfile(String excelFileName,String csvFileName,String Field_Delimiter,int Sheet_Number) {
checkValidFile(excelFileName);
XSSFWorkbook myWorkBook;
try {
myWorkBook = new XSSFWorkbook(new FileInputStream(excelFileName));
XSSFSheet mySheet = myWorkBook.getSheetAt(Sheet_Number);
String csvData="";
DataFormatter formatter = new DataFormatter(Locale.US);
checkValidFile(excelFileName);
int rows = mySheet.getPhysicalNumberOfRows();
String prefix="\"";
for (int eachRow = 0;eachRow<rows;eachRow++) {
XSSFRow myRow = (XSSFRow) mySheet.getRow(eachRow);
for ( int i=0;i<myRow.getLastCellNum();i++){
if(i==0)
{
csvData += prefix+formatter.formatCellValue(myRow.getCell(i))+prefix;
}
else
{
csvData += Field_Delimiter+prefix+formatter.formatCellValue(myRow.getCell(i))+prefix;
}
}
csvData+=NEW_LINE_CHARACTER;
}
try {
writeCSV(csvFileName, csvData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* get Cell value from XLSX file column
* #param myCell
* #return
* #throws Exception
*/
private static void checkValidFile(String fileName){
boolean valid=true;
try{
File f = new File(fileName);
if ( !f.exists() || f.isDirectory() ){
valid=false;
}
}catch(Exception e){
valid=false;
}
if ( !valid){
System.out.println("File doesn't exist: " + fileName);
System.exit(0);
}
}
public static void main(String[] args) throws Exception
{
String inp_file_name="";
String Output_file_name="";
String delimiter=",";
//inp_file_name=args[0];
//Output_file_name=args[1];
enter code here
//delimiter=args[2];
inp_file_name="C:/Users/xxx/Desktop/cloudera_shared/test_data.xlsx";
Output_file_name="C:/Users/xxx/Desktop/cloudera_shared/test_data.csv";
delimiter="|";
if(args.length==4 && (args[3].equals("") == false))
{
int Sheet_Number=Integer.parseInt(args[3]);
excelXToCSVfile(inp_file_name,Output_file_name,delimiter,Sheet_Number);
}
else
{
excelXToCSVfile(inp_file_name,Output_file_name,delimiter,0);
}
}
}
You can set the max size of the heap memory available to your Java process like this (here I increase it to 1024 MB).
java -Xmx1024m -jar myProgram.jar
If you run java -X you can see the different options available.
Try running your program in a profiler to get a better idea of which parts are memory intensive.
I can suggest you the problems beyond your code:
String csvData should be replaced with StringBuffer csvData.
You can declare FileOutputStream(nameFile, true) (set append is true)
You can use the multithread to execute 2 tasks:
First: read content from your file excel.
Two: write that content which is has just read.

Exception reading XLSB File Apache POI java.io.CharConversionException

Im developing a Java aplication that reads an excel xlsb file using Apache POI, but I got an exception while reading it, my code is as follows:
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.Package;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import java.util.Iterator;
public class Prueba {
public static void main (String [] args){
String direccion = "C:/Documents and Settings/RSalasL/My Documents/New Folder/masstigeoct12.xlsb";
Package pkg;
try {
pkg = Package.open(direccion);
XSSFReader r = new XSSFReader(pkg);
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
Iterator<InputStream> sheets = r.getSheetsData();
while(sheets.hasNext()) {
System.out.println("Processing new sheet:\n");
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
sheet.close();
System.out.println("");
}
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OpenXML4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processAllSheets(String filename) throws Exception {
Package pkg = Package.open(filename);
XSSFReader r = new XSSFReader( pkg );
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
Iterator<InputStream> sheets = r.getSheetsData();
while(sheets.hasNext()) {
System.out.println("Processing new sheet:\n");
InputStream sheet = sheets.next();
InputSource sheetSource = new InputSource(sheet);
parser.parse(sheetSource);
sheet.close();
System.out.println("");
}
}
public static XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser =
XMLReaderFactory.createXMLReader(
"org.apache.xerces.parsers.SAXParser"
);
ContentHandler handler = new SheetHandler(sst);
parser.setContentHandler(handler);
return parser;
}
private static class SheetHandler extends DefaultHandler {
private SharedStringsTable sst;
private String lastContents;
private boolean nextIsString;
private SheetHandler(SharedStringsTable sst) {
this.sst = sst;
}
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
// c => cell
if(name.equals("c")) {
// Print the cell reference
System.out.print(attributes.getValue("r") + " - ");
// Figure out if the value is an index in the SST
String cellType = attributes.getValue("t");
if(cellType != null && cellType.equals("s")) {
nextIsString = true;
} else {
nextIsString = false;
}
}
// Clear contents cache
lastContents = "";
}
public void endElement(String uri, String localName, String name)
throws SAXException {
// Process the last contents as required.
// Do now, as characters() may be called more than once
if(nextIsString) {
int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
nextIsString = false;
}
// v => contents of a cell
// Output after we've seen the string contents
if(name.equals("v")) {
System.out.println(lastContents);
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
lastContents += new String(ch, start, length);
}
}
}
And the exception is this:
java.io.CharConversionException: Characters larger than 4 bytes are not supported: byte 0x83 implies a length of more than 4 bytes
at org.apache.xmlbeans.impl.piccolo.xml.UTF8XMLDecoder.decode(UTF8XMLDecoder.java:162)
at org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader$FastStreamDecoder.read(XMLStreamReader.java:762)
at org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader.read(XMLStreamReader.java:162)
at org.apache.xmlbeans.impl.piccolo.xml.PiccoloLexer.yy_refill(PiccoloLexer.java:3474)
at org.apache.xmlbeans.impl.piccolo.xml.PiccoloLexer.yylex(PiccoloLexer.java:3958)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yylex(Piccolo.java:1290)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yyparse(Piccolo.java:1400)
at org.apache.xmlbeans.impl.piccolo.xml.Piccolo.parse(Piccolo.java:714)
at org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3439)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1270)
at org.apache.xmlbeans.impl.store.Locale.parseToXmlObject(Locale.java:1257)
at org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345)
at org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument$Factory.parse(Unknown Source)
at org.apache.poi.xssf.eventusermodel.XSSFReader$SheetIterator.<init>(XSSFReader.java:207)
at org.apache.poi.xssf.eventusermodel.XSSFReader$SheetIterator.<init>(XSSFReader.java:166)
at org.apache.poi.xssf.eventusermodel.XSSFReader.getSheetsData(XSSFReader.java:160)
at EDManager.Prueba.main(Prueba.java:36)
The file has 2 sheets, one with 329 rows and 3 columns and the other with 566 rows and 3 columns, I just want to read the file to find if a value is in the second sheet.
Apache POI doesn't support the .xlsb file format for anything other than text extraction. Apache POI will happily provide full read or write support .xls files (via HSSF) and .xlsx files (via XSSF), or both (via the common SS UserModel interface).
However, the .xlsb format is not supported for generatl operations - it's a very odd hybrid between the two, and the large amount of work involved has meant no-one has been willing to volunteer/sponsor the work required.
What Apache POI does offer for .xlsb, as of Apache POI 3.15 beta3 / 3.16, is a text extractor for .xlsb files - XSSFBEventBasedExcelExtractor. You can use that to get the text out of your file, or with a few tweaks convert it to something like CSV
For full read/write support, you'll need to convert your file to either .xls (if it doesn't have very large numbers of rows/columns), or .xlsx (if it does). If you're really really keen to help though, you could review the source code for XSSFBEventBasedExcelExtractor, then have a go at contributing patches to add full support to POI for it!
(Additionally, I think from the exception that your particular .xlsb file is partly corrupt, but even if it wasn't it still wouldn't be supported by Apache POI for anything other than text extraction, sorry)
I have tried reading XLSB file using Apache POI and it is successful. Below is the code snippet I have used.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.xssf.binary.XSSFBSharedStringsTable;
import org.apache.poi.xssf.binary.XSSFBSheetHandler;
import org.apache.poi.xssf.binary.XSSFBStylesTable;
import org.apache.poi.xssf.eventusermodel.XSSFBReader;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ApachePoiXLSB {
public static void main (String [] args){
String xlsbFileName = "test.xlsb";
OPCPackage pkg;
try {
pkg = OPCPackage.open(xlsbFileName);
XSSFBReader r = new XSSFBReader(pkg);
XSSFBSharedStringsTable sst = new XSSFBSharedStringsTable(pkg);
XSSFBStylesTable xssfbStylesTable = r.getXSSFBStylesTable();
XSSFBReader.SheetIterator it = (XSSFBReader.SheetIterator) r.getSheetsData();
List<String> sheetTexts = new ArrayList<>();
while (it.hasNext()) {
InputStream is = it.next();
String name = it.getSheetName();
TestSheetHandler testSheetHandler = new TestSheetHandler();
testSheetHandler.startSheet(name);
XSSFBSheetHandler sheetHandler = new XSSFBSheetHandler(is,
xssfbStylesTable,
it.getXSSFBSheetComments(),
sst, testSheetHandler,
new DataFormatter(),
false);
sheetHandler.parse();
testSheetHandler.endSheet();
sheetTexts.add(testSheetHandler.toString());
}
System.out.println("output text:"+sheetTexts);
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OpenXML4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.usermodel.XSSFComment;
class TestSheetHandler implements XSSFSheetXMLHandler.SheetContentsHandler {
private final StringBuilder sb = new StringBuilder();
public void startSheet(String sheetName) {
sb.append("<sheet name=\"").append(sheetName).append(">");
}
public void endSheet() {
sb.append("</sheet>");
}
#Override
public void startRow(int rowNum) {
sb.append("\n<tr num=\"").append(rowNum).append(">");
}
#Override
public void endRow(int rowNum) {
sb.append("\n</tr num=\"").append(rowNum).append(">");
}
#Override
public void cell(String cellReference, String formattedValue, XSSFComment comment) {
formattedValue = (formattedValue == null) ? "" : formattedValue;
if (comment == null) {
sb.append("\n\t<td ref=\"").append(cellReference).append("\">").append(formattedValue).append("</td>");
} else {
sb.append("\n\t<td ref=\"").append(cellReference).append("\">")
.append(formattedValue)
.append("<span type=\"comment\" author=\"")
.append(comment.getAuthor()).append("\">")
.append(comment.getString().toString().trim()).append("</span>")
.append("</td>");
}
}
#Override
public void headerFooter(String text, boolean isHeader, String tagName) {
if (isHeader) {
sb.append("<header tagName=\"").append(tagName).append("\">").append(text).append("</header>");
} else {
sb.append("<footer tagName=\"").append(tagName).append("\">").append(text).append("</footer>");
}
}
#Override
public String toString() {
return sb.toString();
}
}
I have a implementation using the smartxls, and my code firts convert the xlsb to xlsx and after can use ApachePoi. The next method receive a java.io.File and verify if its extension is xlsb and convert this to xlsx and replace file whit the new. This works for me.
private void processXLSBFile(File file) {
WorkBook workBook = new WorkBook();
String filePath = file.getAbsolutePath();
if (FilenameUtils.getExtension(filePath).equalsIgnoreCase((Static.XLSB_EXT))) {
try {
workBook.readXLSB(new java.io.FileInputStream(filePath));
filePath = filePath.replaceAll("(?i)".concat(Static.XLSB),
Static.XLSX_EXT.toLowerCase());
workBook.writeXLSX(new java.io.FileOutputStream(filePath));
final File xlsb = new File(filePath);
file = xlsb;
} catch (Exception e) {
logger.error(e.getMessage(), e);
MensajesJSFUtil
.mostrarMensajeNegocio(new GTMException(e, ClaveMensaje.COMANDAS_ADJUNTAR_XLSBFILE_READERROR));
}
}
}

Writing to .xlsx using java. BiffViewer error occurs

jars I have used : dom4j poi-3.8.jar poi-ooxml-3.8.jar poi-ooxml-schemas-3.8.jar xbean.jar
The code :
package org.capgemini.ui;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
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 XSSFWorkBookWriter {
public void writeWorkBook(Vector table) throws Exception {
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet();
table=new Vector();
table.add(new String("Howdy"));
table.add(new java.sql.Date(2012,06,20));
table.add(new Double(13.35D));
table.add(new String("Fine"));
table.add(new java.sql.Date(2012,06,20));
table.add(new Double(13.38D));
Iterator rows=table.iterator();
Enumeration rowsOfVector=table.elements();
int totalNoOfRows=table.size()/2;
int currentRow=0;
while (rows.hasNext () && currentRow<totalNoOfRows){
XSSFRow row = sheet.createRow(currentRow++);
for (int i = 0; i < 3; i++) {
XSSFCell cell=row.createCell(i);
Object val=rows.next();
if( val instanceof String){
cell.setCellValue(val.toString());
}
else if(val instanceof Date){
cell.setCellValue((java.sql.Date)val);
}
else if(val instanceof Double){
cell.setCellValue((Double)val);
}
}
}
FileOutputStream outPutStream = null;
try {
outPutStream = new FileOutputStream("D:/Try.xlsx");
workBook.write(outPutStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outPutStream != null) {
try {
outPutStream.flush();
outPutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
XSSFWorkBookWriter bookWriter=new XSSFWorkBookWriter();
try {
bookWriter.writeWorkBook(new Vector());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ERROR ::
org.apache.poi.hssf.dev.BiffViewer$CommandParseException: Biff viewer needs a filename
at org.apache.poi.hssf.dev.BiffViewer$CommandArgs.parse(BiffViewer.java:333)
at org.apache.poi.hssf.dev.BiffViewer.main(BiffViewer.java:386)
BiffViewer is part of HSSF, which only works with the older .xls files (OLE2 based). You're generating a .xlsx file with XSSF, which is a different low level format.
If you really want to use BiffViewer (not sure why, it's normally only used with debugging, but still), then you'll need to change your XSSF code to be HSSF code. Otherwise, if you did mean to be using XSSF to generate a .xlsx file, then you can't use the HSSF debugging tools. If you want to know what's in your .xlsx file, unzip it (.xlsx is a zip of xml files) and view the XML.

Append Data to Word using JavatoWord API failing

I'm trying to add data to Word document in my automation using JavatoWord API and Word is getting corrupted when I append the data. Can anyone help?
import java.io.*;
import java.text.*;
import java.util.*;
import word.api.interfaces.IDocument;
import word.w2004.Document2004;
import word.w2004.Document2004.Encoding;
import word.w2004.elements.BreakLine;
import word.w2004.elements.Image;
import word.w2004.elements.ImageLocation;
import word.w2004.elements.Paragraph;
import word.w2004.elements.ParagraphPiece;
public void AppendtoWord() throws Exception
{
String strScrShotsFile = "C:/Test.doc/";
String ScrShotsFile = "C:/test.png";
File fileScrShotsFile = new File (strScrShotsFile);
boolean exists = (fileScrShotsFile).exists();
PrintWriter writer = null;
myDoc = new Document2004();
if (!exists) {
try {
writer = new PrintWriter(fileScrShotsFile);
myDoc.encoding(Encoding.UTF_8);
myDoc.company("Comp Inc");
myDoc.author("Test Automation Teams");
myDoc.title("Application Automation Test Results");
myDoc.subject("Screen Shots");
myDoc.setPageOrientationLandscape();
myDoc.addEle(BreakLine.times(2).create());// Document Header and Footer
myDoc.addEle(BreakLine.times(2).create());
myDoc.getHeader().addEle(
Paragraph.withPieces(
ParagraphPiece.with("Screenshots for test case: "),
ParagraphPiece.with( "Test" ).withStyle().bold().create()
).create()
);
myDoc.getFooter().addEle(Paragraph.with(ScrShotsFile).create()); // Images
myDoc.addEle(BreakLine.times(1).create());
myDoc.addEle(Paragraph.with("Test").withStyle().bgColor("RED").create());
writer.println(myDoc.getContent());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
writer.close();
}
} else {
PrintWriter writer1= null;
try {
writer1 = new PrintWriter(new FileWriter(fileScrShotsFile,true));
myDoc.addEle(Paragraph.with("This is Important").withStyle().bgColor("RED").create());
writer1.println(myDoc.getContent());
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
writer1.close();
}
}

Categories