Im using jxl to store data entered in by the user into an excel spreadsheet. I want to be able to close my program while its running and open up the excel spreadsheet and view the data. Whenever I do this, I get a message that says that it is in a different format than specified in the file extension. Here is my code.
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import jxl.*;
import jxl.write.*;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ReadWriteTest
{
public static void main(String[] args) throws BiffException, IOException, RowsExceededException, WriteException
{
Scanner scan = new Scanner(System.in);
int i = 1;
Integer iAlliance = -1;
File test = new File("C:\\test.xls");
WritableWorkbook wb = Workbook.createWorkbook(test);
while(iAlliance != 0 && i != 5)
{
WritableSheet sheet = wb.createSheet("Sheet" + i, i);
iAlliance = scan.nextInt();
WriteExcel.addNumber(sheet, 0, 0, iAlliance);
iAlliance = scan.nextInt();
WriteExcel.addNumber(sheet, 1, 0, iAlliance);
i++;
}
wb.write();
wb.close();
}
}
"close my program while its running"
Your code needs to handle that. Right now, it just gets killed at any point (probably in that loop), and nothing after that point happens. The WriteableWorkbook never gets write() or close() called, and the file is probably corrupted.
So see this, try adding some simple output at various places, like "got to line number XXX". Run it, close it, and see how far it got.
You'll probably need to wrap the bulk of your code in a try-catch-finally. The loop is inside the try, the catch handles the lightning-out-of-the-blue program closing from that pesky human at the keyboard, and the finally closes up the workbook file properly.
Related
I'm attempting to run an Access function through Java using Jacob using Application.Run (https://msdn.microsoft.com/en-us/library/office/ff193559.aspx). I am able to open and close an Access database, but not run a function. I suspect the run call actually does go through but that I have opened the file read-only (maybe? not sure I did) which then causes the Access error: Run-time error 3073: Operation must use an updatable query. The query simply appends two strings onto a test table I created, and that query works by hand, but so far not through Java.
If the error is that I've opened it read-only, how can I open it not read-only? If it's something else, how do I call a function (or a macro, either will work) using Jacob? Or you may know some other Java technique besides using Jacob, I'd take that too.
Minimum example:
Java program
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.LibraryLoader;
import com.jacob.com.Variant;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author evans
*/
public class Test {
public static void main(String[] args) {
// Load library/.dll
try {
String libFile = System.getProperty("os.arch").equals("amd64") ? "jacob-1.18-x64.dll" : "jacob-1.18-x86.dll";
FileInputStream inputStream = new FileInputStream(new File(libFile));
File temporaryDll = File.createTempFile("jacob", ".dll");
try (FileOutputStream outputStream = new FileOutputStream(temporaryDll)) {
byte[] array = new byte[8192];
for (int i = inputStream.read(array); i != -1; i = inputStream.read(array)) {
outputStream.write(array, 0, i);
}
}
System.setProperty(LibraryLoader.JACOB_DLL_PATH, temporaryDll.getAbsolutePath());
LibraryLoader.loadJacobLibrary();
temporaryDll.deleteOnExit();
} catch (IOException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
// Open thread
ComThread.InitSTA(true);
// New application
ActiveXComponent ComBridge = new ActiveXComponent("Access.Application");
// Open database
Dispatch.put(ComBridge, "Visible", new Variant(true));
ComBridge.invoke("OpenCurrentDatabase", new Variant("C:/Users/evans/Documents/Book Business/Building Reports/Book Business.accdb"));
// Run function
ComBridge.invoke("Run", new Variant("Test"));
// Shutdown
ComBridge.invoke("Quit");
ComThread.quitMainSTA();
ComThread.Release();
}
}
Access query:
INSERT INTO tblTest ( Test, Test2 )
SELECT "a" AS Expr1, "B" AS Expr2;
I am able to take screenshot by ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
In my application I have to take screenshot for every page so I want to save the multiple screenshot into a single .doc file one by one.
Is there any API?
Any Idea?
Please Help...
Easiest way - take screenshot, put it in PNG/JPEG file, read it, add it in MS-Word, delete the file, simple. here's a ready to use code for you.... BINGO...!!
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class TakeScreenshots {
public static void main(String[] args) {
try {
XWPFDocument docx = new XWPFDocument();
XWPFRun run = docx.createParagraph().createRun();
FileOutputStream out = new FileOutputStream("d:/xyz/doc1.docx");
for (int counter = 1; counter <= 5; counter++) {
captureScreenShot(docx, run, out);
TimeUnit.SECONDS.sleep(1);
}
docx.write(out);
out.flush();
out.close();
docx.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void captureScreenShot(XWPFDocument docx, XWPFRun run, FileOutputStream out) throws Exception {
String screenshot_name = System.currentTimeMillis() + ".png";
BufferedImage image = new Robot()
.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
File file = new File("d:/xyz/" + screenshot_name);
ImageIO.write(image, "png", file);
InputStream pic = new FileInputStream("d:/xyz/" + screenshot_name);
run.addBreak();
run.addPicture(pic, XWPFDocument.PICTURE_TYPE_PNG, screenshot_name, Units.toEMU(350), Units.toEMU(350));
pic.close();
file.delete();
}
}
Selenium Webdriver do not provide any feature to add snapshot in word file.
For this you need to use third party libraries.
Refer below:-
how to insert image into word document using java
How can I add an Image to MSWord document using Java
You can also add your image file in TestNG output file using reporter
Refer below :-
http://www.automationtesting.co.in/2010/07/testng-take-screenshot-of-failed-test.html
Hope it will help you :)
I'm trying to write some text to an html file as an output using PrintWriter, and the text isn't saving to the file.
import java.util.Random;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Creator
{
static ArrayList<Character> grid = new ArrayList<Character>();
public static void main(String[]args) throws FileNotFoundException
{
char[] alphabet={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(int row=0;row<625;row++)
{
grid.add(alphabet[RandGen(0,25)]);
//System.out.print(grid.get(out));
}
Creator.Output();
System.out.println("Executed.");
}
public static int RandGen(int min, int max)
{
Random ran = new Random();
int randomNum = ran.nextInt(max) + min;
return randomNum;
}
public static void Output()throws FileNotFoundException
{
//File file=new File("wsm.html");
//File.createNewFile();
PrintWriter writer = new PrintWriter("wordsearchmaker.html");
writer.println("<html>");
writer.println("<table>");
writer.println("tr");
for(int j=0;j<25;j++)
{
//for(int k=0;k<25;k++)
// {
System.out.println("<th>"+grid.get(j));
writer.println("<th>"+grid.get(j));
// }
}
writer.flush();
writer.close();
System.out.println("Outputting...");
}
}
So I've checked that the methods are all running (hence the "outputting..."), and I system.out.printed the content that I'm intending to write to the file, which is outputting exactly what I want it to. It's supposed to output html code into a html file (named wordsearchmaker.html), but nothing is saving to the file. Everywhere I looked online just said to make sure I'm closing the writer, which I did.
Note: I am working in eclipse, which has always been kind of finicky with me, so I may be messing something up there? I don't usually work in eclipse so that's totally possible.
It looks like you've opened the PrintWriter, which enables you to send data to the file. But you haven't actually opened or created a file.
Try first creating a new file and modifying it:
import java.io.File;
File newFile = new File ("LOCATION OF FILE");
Then, set your PrintWriter to use newFile.
My code here is compiling correctly, but I am running into the problem that my ArrayList of BufferedImages is always empty. Honestly I don't have any knowledge regarding ImageIO or the likes!
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import net.sf.javavp8decoder.imageio.WebPImageReader;
import net.sf.javavp8decoder.imageio.WebPImageReaderSpi;
class MyProj{
public static void main(String[] args) throws IOException{
System.out.println("Main");
ArrayList<BufferedImage> collectedImg=getFrames();
}
static ArrayList<BufferedImage> getFrames() throws IIOException{
File MyWebM= new File("/users/case3/mcclusm4/workspace/LineTech/src/goal.webm");
ArrayList<BufferedImage> frames = new ArrayList<BufferedImage>();
try{
ImageReader ir = new WebPImageReader(new WebPImageReaderSpi());
ir.setInput(ImageIO.createImageInputStream(MyWebM));
for(int i = 0; i < ir.getNumImages(true); i++)
frames.add(ir.read(i));
}catch(IOException e){}
return frames;
}
}
First of all dont catch Exception and do nothing:
catch (Exception e) {}
Now when an exception is catched it silently fails without any information.
Change catch to print stacktrace: e.printStackTrace() and post it.
Disclaimer: I have never tested the code in question myself. But...
From looking at the source code of net.sf.javavp8decoder.imageio.WebPImageReader it cannot decode WebM files. It only supports single frame WebP files.
If you stop swallowing the exception and ignoring it, as suggested by #robocoder, you should get an IIOException with the message "Bad WEBP signature!".
I have a program that ask the user for what application it want to open,
this is how the program works:
the user write what application it want to open in a "inputDialog" example the user write "Open application Notepad".
the program looks for the word "application" in the text file so the program is sure that it was a application the user wanted to open.
both the "open application" sentence and the application name get stored in a text file.
then does program remove "Open application" from the text file, and then is only the application name visible.
but always a space comes in front of the application name. Please help me remove the space infront of the application name!!
Here is my code:
package Test_Code;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JOptionPane;
public class New_Loader_3 {
public static void main(String[]args) throws IOException{
String Test = JOptionPane.showInputDialog("Test");
BufferedWriter writer = new BufferedWriter(new FileWriter("/Applications/Userdata/tmp/Application.txt"));
writer.write(Test);
writer.close();
int tokencount;
FileReader fr=new FileReader("/Applications/Userdata/tmp/Application.txt");
BufferedReader br=new BufferedReader(fr);
String s1;
int linecount=0;
String line;
String words[]=new String[500];
while ((s1=br.readLine())!=null)
{
linecount++;
int indexfound=s1.indexOf("application");
if (indexfound>-1)
{
FileInputStream fstream1121221 = new FileInputStream("/Applications/Userdata/tmp/Application.txt");
DataInputStream in1121211 = new DataInputStream(fstream1121221);
BufferedReader br1112211 = new BufferedReader(new InputStreamReader(in1121211));
String Name12122131;
while ((Name12122131 = br1112211.readLine()) != null) {
if (Name12122131.startsWith(" "))
{
System.out.println("Name12122131");
}
}
String mega = Test.replaceAll("Open application","");
System.out.println(mega);
BufferedWriter Update_Catch = new BufferedWriter(new FileWriter("/Applications/Userdata/tmp/Application.txt"));
Update_Catch.write(mega);
Update_Catch.close();
}
}
System.out.println("Done");
}
}
It's because the user types in Open<space>application<space>Notepad. Now when you replace Open<space>Applicaton the space before Notepad is still left. So I just you use this instead:
String mega = Test.replaceAll("Open application ","");
Adding a <space> at the end of Open<space>Application will replace the space too. So now mega will be Notepad.
Otherwise you could use what you're already using and then call mega.trim()