hi all,
I have generated an excel document which I need to print from the UI using a button without opening the file. Could anyone help me in this? thanks in advance.
Printable View
hi all,
I have generated an excel document which I need to print from the UI using a button without opening the file. Could anyone help me in this? thanks in advance.
Does this question have anything to do with Java?
db
Hello, thanks for replying.
Well, I have written a program in Java that would generate an excel sheet based on the contents in an xml document. I parsed the xml file using JDOM and generated the excel using POI. In the UI, I have controls for browsing the source xml file and choosing the destination folder, some modes of generation comboboxes, some buttons like 'clear', 'generate', 'generate and print' etc. All the components are swing components. I want the print feature in the 'generate and print' button. I require help in sending the generated excel document to the printer in the actionPerformed method of 'generate and print' button.
I can see three approaches:
1. Obtain a commercial package, there are several that support Excel printing from Java code. Search the net.
2. Use JNA to manipulate an Excel instance.
3. Easiest (IMO) but may have some 'gotchas' -- write out a VBScript file and execute it. Here's an abbreviated example:Before using anything like this, be sure to go through all four sections of When Runtime.exec() won't - JavaWorld amd implement ALL the recommendations. Also note that the FileWriter should be closed in a finally block.Code:import java.io.File;
import java.io.FileWriter;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class PrintExcel {
public static void main(String[] args) {
new PrintExcel().init();
}
public void init() {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("Excel", "xls"));
int retVal = chooser.showOpenDialog(null);
if (retVal == JFileChooser.APPROVE_OPTION) {
printFile(chooser.getSelectedFile());
}
}
private void printFile(File file) {
try {
String vbs = "Dim AppExcel\r\n"
+ "Set AppExcel = CreateObject(\"Excel.application\")\r\n"
+ "AppExcel.Workbooks.Open(\"" + file.getPath() + "\")\r\n"
+ "appExcel.ActiveWindow.SelectedSheets.PrintOut\r\n"
+ "Appexcel.Quit\r\n"
+ "Set appExcel = Nothing";
File vbScript = File.createTempFile("vbScript", ".vbs");
vbScript.deleteOnExit();
FileWriter fw = new java.io.FileWriter(vbScript);
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + vbScript.getPath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
db
Wow... did not think of this approach :) Thats solves my problem... Thanks a dozen Darryl... :)