OutputStream - ApachePOI - Workbook.write to outputStream
Hello,
I have a requirement, where an input XML from a webservice is read and have to create an MS Excel file sent via Oracle B2B to SFTP server. I have written a Java code that can read xml and write to MS Excel as a file if I use FileOutPutStream (for testing purpose). However, when I use an ByteArrayOutputStream, I get the ASCII in the Excel file.here is the spinet of the code,
public class xmlexcel implements Callout {
public void execute(CalloutContext calloutContext, List input,
List output) throws CalloutDomainException,
CalloutSystemException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos); //Write Workbook to ByteArrayOutputStream
CalloutMessage cmOut;
cmOut = new CalloutMessage(bos.toString()); //CalloutMessage can be either String or byte[]
output.add(cmOut);
bos.close();Also tried this,
ByteArrayOutputStream bos = new ByteArrayOutputStream();
workbook.write(bos);
byte[] bytes = bos.toByteArray();
CalloutMessage cmOut;
cmOut = new CalloutMessage(bytes);
output.add(cmOut);
bos.close();In both the cases, the Excel (xls) file that gets created has ASCII values, like this, ÃÃà ¡±á;þÿ.
Any ideas and suggestions are greatly appreciated,
Ven
bos.toString()Don't do that. It takes binary data which isn't meant to represent text, and forces it into a text format. Only bad things can result from that, and you're seeing exactly what bad things.
Similar Messages
-
OutputStream already retrieved?
Hi , all:
Now i use the popup dialog to export excel , after export the data , i use AdfFacesContext.getCurrentInstance().returnFromDialog(null, null); back to the main page.but when the program run this, it will has error as follows:
javax.faces.FacesException: #{excelExporter.doExport}: javax.faces.el.EvaluationException: java.lang.IllegalStateException: OutputStream already retrieved
and when i export excel, i use these code:
try {
OutputStream out = response.getOutputStream();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + filename);
HSSFWorkbook workbook = createWorkbook(iter, attr, attributes, maxrowcount);
workbook.write(out);
out.flush();
out.close();
FacesContext.getCurrentInstance().responseComplete();
} catch (IOException ex) {
ex.printStackTrace();
createWorkbook is the method to generate the excel.
After this i will call the AdfFacesContext.getCurrentInstance().returnFromDialog(null, null); to return and at this time it has error.
How to solve this problem.
Thanks in advance.Hi,
what I am suggesting is to defer the whole Excel processing to the return listener. The data entered in the dialog can be returned to the return listener in a HashMap (second argument in the closeDialog statement). Then you handle Excel generation etc. in the listener code. My assumption is that you are getting into conflict with the internal dialog processing. From the application's workflow there is no difference between your approach and what I am suggesting
Frank -
Report generation toolkit jumping between workbooks
Hi,
I am having an issue with my VI which I am wondering if anyone has a fix too or workaround.
Basically during my tests I write multiple sets of data to different sheets in Excel using the Report Generation Toolkit.
At the start of my code I open a workbook (template Excel file), I write data to the file at the end of each test for each iteration and then save and close the file at the end.
I have attached a PNG of one of my sub VIs which writes one set of data to one sheet, this could be called numerous times during my code.
The issue I have is that if I am working with a seperate workbook, each time my sub VI runs it will jump to the test results workbook.
I am aware that I do "Get" the workbook in my code and this is why it happens.
Is there a way to call different sheets in a workbook in a VI without affecting the user who is working on a seperate workbook, write data in the background?
I am unsure if it is possible to write data to different sheets in a workbook without using the "Excel Get Worksheet VI" before entering the data.
I also know I could just save all data in arrays and then at the very end write all data to the workbook but this is not a preference
Any information would be gratefully appreciated
Thanks.
Solved!
Go to Solution.
Attachments:
write_to_excel.PNG 14 KBChanged the window state to "No Change" in the new report VI
Seems to have done the trick
Attachments:
report_settings.PNG 2 KB -
Write several time in an excel file?
Hi
I'm using a excel file to take back data from GPIB device.
so I need to create an excel file
write the data and this several time in the same seet.
WritableWorkbook workbook = Workbook.createWorkbook(new File(Fo));
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
if(new_run==true && allowoverwrite==true){
Label label = new Label(0, 2, "NEW RUN");
sheet.addCell(label);
new_run=false;
Label label = new Label(0, ww, bonnevar);
sheet.addCell(label);
Number number = new Number(1,ww, bonnevalue);
sheet.addCell(number);
ww=ww+1;
workbook.write();
workbook.close();
catch(Exception ex) {
JOptionPane.showMessageDialog(null, "Impossible de cr�er le fichier xls", "Erreur", JOptionPane.ERROR_MESSAGE);
}if i had to write only one value in the excel file it is OK it works.
but if i have to write 2 data and more (i mean i need to enter 2 times in the loop) the first data are deleted and replace by the new one.
i'm affraid it comes from the fact i recreate each time a workbook and a sheet.
but i don't know how to solve my issue.
do you know if it is possible to open an excel file, write data , close the excel file , then reopen the same excel file and add data without erase the pervious one
thanks a lot for your help
BRbonjour
et oui je suis francais :)
my english is so bad isn't it :)
so effectively there is no loop because the source code i have inserted is a small part of my entire code.
but recursively i come on this part of the code that why i have spoke about a loop.
and each time I want to write something on the excel file, the previous data are erased and replace by the new one....
so if you have any idea so solve this it would be great...
ciao -
Read database-writeExcel-readExcel-Write database table
package datamigration;
import java.sql.*;
import java.io.*;
import java.io.IOException;
import jxl.*;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.read.biff.BiffException;
public class NewExcel {
//In the following method we will be reading the Table from the Database and write it in an Excel File
public void getDataAndWrite() throws ClassNotFoundException, SQLException, WriteException, IOException {
Connection conn = null; //Manages connection
Statement stmt = null; //Query statement
ResultSet rs = null;
final String driver = "oracle.jdbc.driver.OracleDriver";
final String url = "jdbc:oracle:thin:@inbgewdrnd90hfm:1521:VISUAL"; //This URL will be specific to your Database
WritableWorkbook workbook = null;
workbook = Workbook.createWorkbook(new File("C:\\NewExcel2.xls")); //Again the name of file and its location will be your own
Class.forName(driver);
conn = DriverManager.getConnection(url, "visual", "visual");
stmt = conn.createStatement();
System.out.println("Executing query...");
rs = stmt.executeQuery("select * FROM TRANSACTION"); //the query is selecting everything from TRANSACTION table
WritableSheet sheet = workbook.createSheet("first sheet", 0);
Label FULLTEXT = new Label(0, 0, "FULLNAME");
sheet.addCell(FULLTEXT);
if (rs != null) {
int i = 0;
while (rs.next()) {
i++; //the counter
Label NAMEFULL = new Label(0, i, rs.getString(1)); //getting the values from the Table and appending them in TEXTFULL column
sheet.addCell(TEXTFULL); //adding column to Sheet
workbook.write();
workbook.close();
//Reading the Excel file
public void read(String inputFile) throws IOException, BiffException, ClassNotFoundException, SQLException {
Connection conn = null; //Manages connection
Statement stmt = null; //Query statement
ResultSet rs = null;
final String driver = "oracle.jdbc.driver.OracleDriver";
final String url = "jdbc:oracle:thin:@INBGEWDRND90Hgf:1521:wsa";
Class.forName(driver);
conn = DriverManager.getConnection(url, "corpus", "corpus");
stmt = conn.createStatement();
File inputWorkbook = new File(inputFile);
Workbook w;
w = Workbook.getWorkbook(inputWorkbook);
if (Workbook.getWorkbook(inputWorkbook) != null) {
System.out.println("Got the workbook" + "\n");
} else {
System.out.println("No workbook to print");
//Get the first sheet from the input file which is set earlier
Sheet sheet = w.getSheet(0);
//Set the for loop for reading the rows
for (int i = 0; i < sheet.getRows(); i++) {
String verbatim = sheet.getCell(0, i).getContents();
verbatim = verbatim.replaceAll("'", "''"); //"'" was causing an error so it was handled through"'"
verbatim = verbatim.replaceAll("&", "\\&");
String query = "insert into TRANSACTION (FULLNAME) values ('" + verbatim + "' )";
System.out.println(query);
stmt.executeUpdate(query);
public static void main(String[] args) throws ClassNotFoundException, WriteException, SQLException, IOException, BiffException {
NewExcel migratedata = new NewExcel();
migratedata.getDataAndWrite();
migratedata.read("C:\\NewExcel2.xls");
}1.) Please make sure that your code is readable (use the CODE button)
2.) What is your question?
3.) Please read [How To Ask Questions The Smart Way|http://www.catb.org/~esr/faqs/smart-questions.html] -
How do I save a xls document in Java
Hi!
How do I save a xls Document from java?
I mean, I want to specify which xls document to save and then save it.
Any useful code would be of great help!This is the code!
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Locale;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.write.Label;
import jxl.write.WritableCell;
import jxl.write.WritableCellFormat;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.Number;
import jxl.write.*;
import java.io.IOException;
import java.io.OutputStream;
public class writeXls
public String templateName;
public String outputName;
public writeXls (String t, String o)
templateName = "c://"+t;
outputName = "c://"+o;
public void writeYearVolume(String []yearvolymeArray)
WritableWorkbook workbook = null;
try
// Setup workbook
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(Locale.UK);
ws.setEncoding("Windows-31J");
// Load workbook
Workbook template = Workbook.getWorkbook(new FileInputStream(templateName));
// Create new workbook
workbook = Workbook.createWorkbook(new FileOutputStream(outputName), template, ws);
// Create new sheet
WritableSheet sheet = workbook.getSheet(1);
// Create new label
Number amc1000= new Number(4, 1, Integer.parseInt(yearvolymeArray[0]));
Number amc800 = new Number(4, 2, Integer.parseInt(yearvolymeArray[1]));
sheet.addCell(amc1000);
sheet.addCell(amc800);
// Write wookbook
workbook.write();
workbook.close();
catch (IOException e)
e.printStackTrace();
catch (WriteException e)
e.printStackTrace();
catch(Exception e)
e.printStackTrace();
}The xls file is modified but not saved, how do I save the file?
Some of the cells in the xls file contains formulas, because of that, the cells containing formulas dosen't update its value.
if I however save the file manually then the cells are updated. I want to save the xls file automatically from Java.
Any ideas on how to do that? -
Export To Excel in new popup window
Hi all,
I am trying to implement the 'exportToExcel' functionality in which will open a XL file in a new window(which has to be the MS EXcel window,not the browser).My code snippet is as follows:
public ModelAndView exportToExcel(HttpServletRequest request,HttpServletResponse response, ReceivingExceptionVO command)
throws Exception
System.out.println("Inside exportToExcel method:Hurray!!");
try {
ReceivingExceptionVO commandObject = (ReceivingExceptionVO) command;
response.setHeader("Cache-Control", "public");
response.setHeader("Pragma", "public");
response.setHeader("Expires", "0");
response.setHeader("Content-disposition", "inline; filename=\""+ "receive" + ".xls\";");
response.setHeader("Content-Type", "xls/csv");
ServletOutputStream outputStream = response.getOutputStream();
HSSFWorkbook workBook = buildExcelDocument(new HSSFWorkbook(), request, response, commandObject);//this buildExcelDocument mthod is defined in this controller.This is not the method of api.This returns a workbook with required data
workBook.write(outputStream);
outputStream.flush();
outputStream.close();
catch (IOException e)
e.printStackTrace();
catch (Exception e)
e.printStackTrace();
return null;
}But i am getting the excel in the current page only,not in the new one and that also getting in the browser.Please help.
Edited by: amit.goenka on Jul 7, 2009 6:11 AMHey That did It!!!Whoa!
but what was the issue or trick here??
Thanks a lot -
Hi all,
I'm trying to make a package of Vis to easily make Excel reports with Signal Express. I'm working on LabVIEW 8.2.1.
I'm using the report generation toolkit, so I build a .llb from my project which contains all the hierarchy of my steps, but also the hierarchy of dynamic VIs called.
I have made some steps, like "Open Workbook", "Write Data", etc.
My steps run well, excepts one step : "Close Workbook".
If my "Close Workbook" step is firing on "Run" Signal Express event, I have no error, so my reference is properly closed.
But if my "Close Workbook" step is firing on "Stop" Signal Express event, I have an error "1", from "Generate Report Objectrepository.vi".
I feel that I'm trying to use a reference which has been killed in the "Stop" step...
I would like to know what exactly do Signal Express on "Stop" event and why my close function does'nt run well.
Thanks,
CallahanHi Callahan,
SignalExpress (SE for short) does the following on the Stop event:
1. Takes the list of parameters that SE found on your VI's connector pane, and sets the values that the user set from the "Run LabVIEW VI" configuration page, if any.
2. Then tells the VI that SE is running the Stop event by setting the Enum found on your VI's front panel. This in turn should produce some boolean values telling your VI to execute the Stop case.
3. The VI is then run, with those values and states.
4. SE checks to see if any errors where returned.
5. Since this is the Stop event, SE releases the reference to the VI which it possesses.
Questions for you would be, is the reference to your Workbook linked to a control on your connector pane, or held in a uninitialized Shift Register. If it's held in a Shift Register, SE would not be aware of it, and would not be able to affect that reference.
Hope that helps. Feel free to post your LLB if it doesn't.
Phil -
Exception when useing imporrt jxl.*
Hi it is my class i have written
import java.io.*;
import jxl.*;
import java.util.*;
import jxl.Workbook;
import jxl.write.DateFormat;
import jxl.write.Number;
import jxl.write.*;
import java.text.SimpleDateFormat;
class create
public static void main(String[] args)
try
String filename = "input.xls";
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
WritableWorkbook workbook =
Workbook.createWorkbook(new File(filename), ws);
WritableSheet s = workbook.createSheet("Sheet1", 0);
WritableSheet s1 = workbook.createSheet("Sheet1", 0);
writeDataSheet(s);
writeImageSheet(s1);
workbook.write();
workbook.close();
catch (IOException e)
e.printStackTrace();
catch (WriteException e)
e.printStackTrace();
private static void writeDataSheet(WritableSheet s)
throws WriteException
/* Format the Font */
WritableFont wf = new WritableFont(WritableFont.ARIAL,
10, WritableFont.BOLD);
WritableCellFormat cf = new WritableCellFormat(wf);
cf.setWrap(true);
/* Creates Label and writes date to one cell of sheet*/
Label l = new Label(0,0,"Date",cf);
s.addCell(l);
WritableCellFormat cf1 =
new WritableCellFormat(DateFormats.FORMAT9);
DateTime dt =
new DateTime(0,1,new Date(), cf1, DateTime.GMT);
s.adCell(dt);
/* Creates Label and writes float number to one cell of sheet*/
l = new Label(2,0,"Float", cf);
s.addCell(l);
WritableCellFormat cf2 = new WritableCellFormat(NumberFormats.FLOAT);
Number n = new Number(2,1,3.1415926535,cf2);
s.addCell(n);
n = new Number(2,2,-3.1415926535, cf2);
s.addCell(n);
/* Creates Label and writes float number upto 3
decimal to one cell of sheet */
l = new Label(3,0,"3dps",cf);
s.addCell(l);
NumberFormat dp3 = new NumberFormat("#.###");
WritableCellFormat dp3cell = new WritableCellFormat(dp3);
n = new Number(3,1,3.1415926535,dp3cell);
s.addCell(n);
/* Creates Label and adds 2 cells of sheet*/
l = new Label(4, 0, "Add 2 cells",cf);
s.addCell(l);
n = new Number(4,1,10);
s.addCell(n);
n = new Number(4,2,16);
s.addCell(n);
Formula f = new Formula(4,3, "E1+E2");
s.addCell(f);
/* Creates Label and multipies value of one cell of sheet by 2*/
l = new Label(5,0, "Multipy by 2",cf);
s.addCell(l);
n = new Number(5,1,10);
s.addCell(n);
f = new Formula(5,2, "F1 * 3");
s.addCell(f);
/* Creates Label and divide value of one cell of sheet by 2.5 */
l = new Label(6,0, "Divide",cf);
s.addCell(l);
n = new Number(6,1, 12);
s.addCell(n);
f = new Formula(6,2, "F1/2.5");
s.addCell(f);
private static void writeImageSheet(WritableSheet s)
throws WriteException
/* Creates Label and writes image to one cell of sheet*/
Label l = new Label(0, 0, "Image");
s.addCell(l);
WritableImage wi = new WritableImage(0, 3, 5, 7, new File("image.png"));
s.addImage(wi);
/* Creates Label and writes hyperlink to one cell of sheet*/
l = new Label(0,15, "HYPERLINK");
s.addCell(l);
Formula f = new Formula(1, 15,
"HYPERLINK(\"http://www.andykhan.com/jexcelapi\", "+
"\"JExcelApi Home Page\")");
s.addCell(f);
}Hi Shamila,
Pls refer below link:-
jxl.read.biff.BiffException: Unable to recognize OLE stream at jxl.read.bif
The Exception rasied may be due to incompatable version.
Try to save your Excel file in the format 97-2003 and Try.
http://www.archivesat.com/JExcelApi/thread362381.htm
Deepak!!!
Edited by: Deepak Arora on Apr 13, 2010 8:11 AM
Edited by: Deepak Arora on Apr 13, 2010 8:24 AM -
Problem: JSP does not restore after downloading Excel.
I have a "search.jsp" with a commandButton to generate excel. "Report.jsp" opens up in a new window when i click on this button by running below mentioned javascript. I can download Excel successfully by clicking on Download Excel link in report,jsp. Problem is, once i close this new window, I am unable to perform any other action in "search.jsp" even if i do not perform download. If i click on any other button or link "search.jsp", it replaces whole jsp with the Downlaod Excel link. and nothing happens after that . i need to close the seesion and start all over again from login page. Does anyone has solution. It will be big help. Thanks.
JAVASCRIPT:
function aaaa()
mywindow =window.open('report.jsf', 'popupWindow', 'width=400,height=200,left=0,top=100,screenX=0,screenY=100');
Following is report.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://www.backbase.com/2007/jsf" prefix="bjsf" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:view>
<h:form>
<h:commandLink actionListener="#{searchpage.export}" value="Download Excel" />
cancel
</h:form>
</f:view>
</body>
</html>
Following is export function which runs when i click on above commandlink "Download Excel":
public void export(ActionEvent event) {
try {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context
.getExternalContext().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment; filename=report.xls");
ServletOutputStream servletOutputStream = response
.getOutputStream();
WritableWorkbook workbook = Workbook
.createWorkbook(servletOutputStream);
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
WritableFont lfont = new WritableFont(WritableFont.ARIAL, 10);
lfont.setBoldStyle(WritableFont.BOLD);
WritableCellFormat lformat = new WritableCellFormat(lfont);
lformat.setBackground(Colour.DARK_RED2);
lformat.setBorder(Border.ALL, BorderLineStyle.THICK);
WritableFont rfont = new WritableFont(WritableFont.ARIAL, 10);
WritableCellFormat rformat = new WritableCellFormat(rfont);
rformat.setBorder(Border.ALL, BorderLineStyle.THIN);
for (int i = 0; i < this.list.size(); i++) {
HashMap h = (HashMap) this.list.get(i);
if (i == 0) {
Set s = (Set) h.keySet();
Iterator itr = s.iterator();
int j = 1;
while (itr.hasNext()) {
Label label2 = new Label(j, 1, itr.next().toString(),
lformat);
sheet.addCell(label2);
j++;
Collection c = h.values();
Iterator itr = c.iterator();
int j = 1;
while (itr.hasNext()) {
Label label2 = new Label(j, (i + 2), itr.next().toString(),
rformat);
sheet.addCell(label2);
j++;
workbook.write();
workbook.close();
context.responseComplete();
} catch (Exception e) {
e.printStackTrace();
}Try upgrading JSF. I recall a Javascript-specific bug like this in a specific webbrowser. You could try to test in different webbrowsers. The latest JSF 1.2 is currently 1.2_14 which came out just 3 weeks ago. You can get it at [http://javaserverfaces.dev.java.net].
Oh, you certainly need to invoke `FacesContext#responseComplete()` afterwards. This is really not the problem. -
Looking for example to export data from a DynPro table to Excel file
Hello,
I have a certain content in a table.
I would like to export this content to Excel file and let the user save it on his PC. I tried to use the Office Controller but with no success.
Have someone already made something like this and can show me an example?Hi
I already explained this in another post. Anyway i will cut and paste the same for you.Here you go.Sample way to create a Excel file and then download it to a local pc using a FileUI Download element.
We are developing a generic component for the same requirement which will download data to a excel from any table.
Anyway here is something which will give you some kind of idea as to how you can write the data from WebDynpro to a excel file.
For running this application
Ensure that the requisite JAR files are set for the Excel API's. See the blog link below.
Steps :
All your files in the machine running the WAS will be created in the default location
Alias : webdynpro/resources
Path : <Drive>:/usr/sap/J2E/JC00/j2ee/cluster/server0/temp/webdynpro/web
You can open your Visual Administrator and go to HTTP provider service and then create your own Alias. say
Alias : myAlias
Path : <Drive>:/mydirectory/myfiles
Once this is done restart your WebAS.
The code explained will perform the following.
There is a button UI element and a Download UI element. On click of the Action associated with the button ui element
The code below will create a excel file in the location mentioned.
On click of the download UI element you can view the excel file that was created.
Now create a New project in your NWDS
Follow the blog for importing the necessary jar files for Excel
/people/perumal.kanthan/blog/2005/03/21/reading-excel-data-from-java-using-hssf-api
Once that is done you can create say a button in your Webdynpro and associate it with a action.
Then you can write some code like the one below.
//Declare this in the end between the Begin others block.
private FileOutputStream out = null;
private HSSFWorkbook workBook = null;
private HSSFSheet hsSheet = null;
private HSSFRow row = null;
private HSSFCell cell = null;
private HSSFCellStyle cs = null;
private HSSFCellStyle cs1 = null;
private HSSFCellStyle cs2 = null;
private HSSFDataFormat dataFormat = null;
private HSSFFont f = null;
private HSSFFont f1 = null;
//Code to create the Excel.
public void onActionExportToExcel(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
//@@begin onActionExportToExcel(ServerEvent)
try
out = new FileOutputStream("C:/mydirectory/myfiles/testexcel.xls");
workBook = new HSSFWorkbook();
hsSheet = workBook.createSheet("My Sheet");
cs = workBook.createCellStyle();
cs1 = workBook.createCellStyle();
cs2 = workBook.createCellStyle();
dataFormat = workBook.createDataFormat();
f = workBook.createFont();
f1 = workBook.createFont();
f.setFontHeightInPoints((short) 12);
// make it blue
f.setColor( (short)HSSFFont.COLOR_NORMAL );
// make it bold
// arial is the default font
f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// set font 2 to 10 point type
f1.setFontHeightInPoints((short) 10);
// make it red
f1.setColor( (short)HSSFFont.COLOR_RED );
// make it bold
f1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
f1.setStrikeout(true);
cs.setFont(f);
cs.setDataFormat(dataFormat.getFormat("#,##0.0"));
// set a thick border
cs2.setBorderBottom(cs2.BORDER_THICK);
// fill w fg fill color
cs2.setFillPattern((short) HSSFCellStyle.SOLID_FOREGROUND);
cs2.setFillBackgroundColor((short)HSSFCellStyle.SOLID_FOREGROUND);
// set the cell format to text see HSSFDataFormat for a full list
cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
cs2.setFont(f1);
cs2.setLocked(true);
cs2.setWrapText(true);
row = hsSheet.createRow(0);
hsSheet.createFreezePane(0,1,1,1);
for(int i=1; i<10;i++)
cell = row.createCell((short)i);
cell.setCellValue("Excel Column "+i);
cell.setCellStyle(cs2);
workBook.write(out);
out.close();
//Read the file that was created.
FileInputStream fin = new FileInputStream("C:/mydirectory/myfiles/testexcel.xls");
byte b[] = new byte[fin.available()];
fin.read(b,0,b.length);
fin.close();
wdContext.currentContextElement().setDataContent(b);
catch(Exception e)
wdComponentAPI.getComponent().getMessageManager().reportException("Exception while reading file "+e,true);
//@@end
You can now add a Download UI Element to the layout.
Create a Context Attribute say "dataContent" and this should be of Type Binary.
The Data property of the File UI download element should be mapped to dataContent.
In the init method write code like
This is done for the download element.
IWDAttributeInfo attInfo = wdContext.getNodeInfo().getAttribute("dataContent");
IWDModifiableBinaryType binaryType = (IWDModifiableBinaryType) attInfo.getModifiableSimpleType();
//In addition the FileDownload UI element needs for defined resource types
binaryType.setFileName("testexcel.xls");
binaryType.setMimeType(WDWebResourceType.XLS);
Hope that helps you. Anyway its a sample and it should be helpful for you to see how you can modify it and of course maintain some standards in coding unlike the test sample given above :).
Let me know if you require further clarifications
regards
ravi -
How to export data from a Dynpro table to Excel file?
Hi
Here I go again. I read the post <b>Looking for example to export data from a DynPro table to Excel file</b> and put the code lines into a Web Dynpro Project where we need to export a dynpro table to Excel file but exactly at line 23 it doesn't recognize <b>workBook = new HSSFWorkbook();</b>
1 //Declare this in the end between the Begin others block.
2
3 private FileOutputStream out = null;
4 private HSSFWorkbook workBook = null;
5 private HSSFSheet hsSheet = null;
6 private HSSFRow row = null;
7 private HSSFCell cell = null;
8 private HSSFCellStyle cs = null;
9 private HSSFCellStyle cs1 = null;
10 private HSSFCellStyle cs2 = null;
11 private HSSFDataFormat dataFormat = null;
12 private HSSFFont f = null;
13 private HSSFFont f1 = null;
14
15 //Code to create the Excel.
16
17 public void onActionExportToExcel(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
18 {
19 //@@begin onActionExportToExcel(ServerEvent)
20 try
21 {
22 out = new FileOutputStream("C:/mydirectory/myfiles/testexcel.xls");
23 workBook = new HSSFWorkbook();
24 hsSheet = workBook.createSheet("My Sheet");
25 cs = workBook.createCellStyle();
26 cs1 = workBook.createCellStyle();
27 cs2 = workBook.createCellStyle();
28 dataFormat = workBook.createDataFormat();
29 f = workBook.createFont();
30 f1 = workBook.createFont();
31 f.setFontHeightInPoints((short) 12);
32 // make it blue
33 f.setColor( (short)HSSFFont.COLOR_NORMAL );
34 // make it bold
35 // arial is the default font
36 f.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
37
38 // set font 2 to 10 point type
39 f1.setFontHeightInPoints((short) 10);
40 // make it red
41 f1.setColor( (short)HSSFFont.COLOR_RED );
42 // make it bold
43 f1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
44 f1.setStrikeout(true);
45 cs.setFont(f);
46 cs.setDataFormat(dataFormat.getFormat("#,##0.0"));
47
48 // set a thick border
49 cs2.setBorderBottom(cs2.BORDER_THICK);
50
51 // fill w fg fill color
52 cs2.setFillPattern((short) HSSFCellStyle.SOLID_FOREGROUND);
53 cs2.setFillBackgroundColor((short)HSSFCellStyle.SOLID_FOREGROUND);
54 // set the cell format to text see HSSFDataFormat for a full list
55 cs2.setDataFormat(HSSFDataFormat.getBuiltinFormat("text"));
56 cs2.setFont(f1);
57 cs2.setLocked(true);
58 cs2.setWrapText(true);
59 row = hsSheet.createRow(0);
60 hsSheet.createFreezePane(0,1,1,1);
61 for(int i=1; i<10;i++)
62 {
63 cell = row.createCell((short)i);
64 cell.setCellValue("Excel Column "+i);
65 cell.setCellStyle(cs2);
66 }
67 workBook.write(out);
68 out.close();
69
70 //Read the file that was created.
71
72 FileInputStream fin = new FileInputStream("C:/mydirectory/myfiles/testexcel.xls");
73 byte b[] = new byte[fin.available()];
74 fin.read(b,0,b.length);
75 fin.close();
76
77 wdContext.currentContextElement().setDataContent(b);
78 }
79 catch(Exception e)
80 {
81 wdComponentAPI.getComponent().getMessageManager().reportException("Exception while reading file "+e,true);
82 }
83 //@@end
84 }
I don't know why this happen? Any information I will appreciate it.
Thanks in advance!!!
Tokio Franco ChangAfter test the code lines appears this error stacktrace:
[code]
java.lang.NoClassDefFoundError: org/apache/poi/hssf/usermodel/HSSFWorkbook
at com.sap.tc.webdynpro.progmodel.api.iwdcustomevent.ExportToExcel.onActionAct1(ExportToExcel.java:232)
at com.sap.tc.webdynpro.progmodel.api.iwdcustomevent.wdp.InternalExportToExcel.wdInvokeEventHandler(InternalExportToExcel.java:147)
at com.sap.tc.webdynpro.progmodel.generation.DelegatingView.invokeEventHandler(DelegatingView.java:87)
at com.sap.tc.webdynpro.progmodel.controller.Action.fire(Action.java:67)
at com.sap.tc.webdynpro.clientserver.task.WebDynproMainTask.handleAction(WebDynproMainTask.java:101)
at com.sap.tc.webdynpro.clientserver.task.WebDynproMainTask.handleActionEvent(WebDynproMainTask.java:304)
at com.sap.tc.webdynpro.clientserver.task.WebDynproMainTask.execute(WebDynproMainTask.java:649)
at com.sap.tc.webdynpro.clientserver.cal.AbstractClient.executeTasks(AbstractClient.java:59)
at com.sap.tc.webdynpro.clientserver.cal.ClientManager.doProcessing(ClientManager.java:252)
at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doWebDynproProcessing(DispatcherServlet.java:154)
at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:116)
at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doPost(DispatcherServlet.java:55)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:392)
at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:266)
at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:345)
at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:323)
at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:865)
at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:240)
at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:148)
at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:37)
at com.sap.engine.core.cluster.impl6.session.UnorderedChannel$MessageRunner.run(UnorderedChannel.java:71)
at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
at java.security.AccessController.doPrivileged(Native Method)
at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:95)
at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:159)
Thanks in advance!!!
Tokio Franco Chang
[/code] -
Download Excel file through Web dynpro with no windows open?
Can we have a web dynpro application that just returns an Excel file in the response with no open windows? Similar to a java servlet that is used to download a Excel file?
This basically means that I cannot use wdComponentAPI.getWindowManager().createNonModalExternalWindow()
Java Servlet Code
HttpSession session = request.getSession(); // get a handle on the session id
response.setContentType("application/download");
response.setHeader("Content-Disposition", "filename=RTIS_Report.xls");
PrintWriter out = null;
out = response.getWriter();
String report = request.getParameter("REPORT");
JCO.Table lines = download(request, session, report);
for (int i = 0; i < lines.getNumRows(); i++) {
lines.setRow(i);
String content = lines.getString("LINES") + "\n";
out.write(content);
out.flush();
out.flush();
out.close();Hi,
I think you can use IWD Cached Web Resource to achieve this..
See the below code FYI..
public void downloadToExcel( )
String fileName = "Customer" + ".xls";
IWDCachedWebResource cachedExcelResource = null;
try
File f = new File("Customer.xls");
WritableWorkbook workbook = Workbook.createWorkbook(f);
WritableFont black = new WritableFont(WritableFont.createFont("Trebuchet MS"),WritableFont.DEFAULT_POINT_SIZE,WritableFont.BOLD,false,UnderlineStyle.SINGLE,Colour.BLACK);
WritableCellFormat blackFormat = new WritableCellFormat(black);
WritableFont blue = new WritableFont(WritableFont.createFont("Trebuchet MS"),WritableFont.DEFAULT_POINT_SIZE,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLUE);
WritableCellFormat blueFormat = new WritableCellFormat(blue);
WritableSheet sheet = workbook.createSheet("Customer", 0);
Label label;
String[] header={"Corporate Code","Batch ID"};
for (int i=0;i<2;i++)
label = new Label(i,0,header<i>.toString(),blackFormat);
sheet.addCell(label);
WritableCellFormat integerFormat = new WritableCellFormat(NumberFormats.INTEGER);
jxl.write.Number number;
// Reading the contents
for(int i=0;i<wdContext.nodeVn_DownloadToExcel().size();i++)
String strCorpName = wdContext.currentContextElement().getVa_CorpCode();
String strBatchID = wdContext.nodeVn_DownloadToExcel().getVn_DownloadToExcelElementAt(i).getVa_BatchID();
label = new Label(0,i+1,strCorpName,blueFormat);
sheet.addCell(label);
label = new Label(1,i+1,strBatchID,blueFormat);
sheet.addCell(label);
workbook.setColourRGB(Colour.LIME, 0xff, 0, 0);
workbook.write();
FileInputStream excelCSVFile = new FileInputStream(f);
IWDCachedWebResource cachedWebResource = null;
if (excelCSVFile!= null)
cachedWebResource = WDWebResource.getWebResource(excelCSVFile, WDWebResourceType.getWebResourceType("xls","application/ms-excel"));
cachedWebResource.setResourceName(fileName);
cachedExcelResource = cachedWebResource;
wdContext.currentContextElement().setVa_DownloadToExcel(cachedExcelResource.getURL());
workbook.close();
catch (Exception ex)
wdComponentAPI.getMessageManager().reportException("Error in Excel Download"+ex.getMessage(),false);
Regards,
Vijay -
Restrict on a "Date" type (key-figure)
Hello, all
1. I need to define a query, to compare the planed-date and the current-date(today), if planed-date>today, then in the new column, the firstday of the month will be listed
(e.g. 1-12-2005).
could you give me some suggestion, how can I found the functions of reading date in Query Designer.(I didn't find any function in the Form).
2. Any how can I add Macro in the report? is there some document I can read in SDN?
Many thanks
TonyHi Tony,
I dont know details about your infoobjects design tech aspects. Hence, I propose that what will work. You can adjust your design accordingly.
I encountered a problem while working with dates determined as key figure attribute.
But with dates as reference to 0CALDAY attributes everything works.
So, we have a Project infoobject. Create plan-beg-date and plan-end-date characteristics with reference to 0CALDAY. Assign them as attributes to Project. For testing purposes enter manualy several master data for it. Insert it as a data target (RSA1, infoproviders area). If you have a cube with the Project, then you dont need the previous step.
In BEx, create a V1 formula variable for plan-beg-date: replacement path, char = Project, Replace var with = Attribute value, Attribute = plan-beg-date, check To value.
Similarly, create V2 formula variable for plan-end-date.
Create in columns a new structure. If you work with Project infoobjects as infoprovider, put into structure Number of records KF, otherwise the following steps might not work. Add into the structure a new formula = V1, new formula = V2, new formula = V2 - V1. It will give you the the planned duration of the project.
Now, create X1 & X2, two customer exit variables on 0CALDAY. Based on either user entered reporting day or on current sys-day they should return the first and last days of the reporting/current month.
In the structure create another formula for corrected beginning date:
DATE ( ( 'V1' < 'X1' ) * 'X1' + ( 'X1' < 'V1' ) * 'V1' )
and a formula for corrected ending date:
DATE ( ( 'V2' > 'X2' ) * 'X2' + ( 'X2' > 'V2' ) * 'V2' )
Now you can calculate planned days for the reporting month or even the total number of project plan days.
About macro you execute a query, embed it into a workbook, write a macro and save the workbook. Next time youll open the workbook in Analyzer.
Best regards,
Eugene -
I solved excel file download from jsp or javabean
first jexcel api download
i used the jexcel api
here sample ; using jexcel api
This code is servlet
==================================================================
SaleAgent sa = null;
public void init(ServletConfig config) throws ServletException {
super.init(config);
// get Sale List DB Agent Class
// you are modify
sa = new SaleAgent();
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("application/vnd.ms-excel");
res.setHeader("content-disposition", "attachment; filename=datesale.xls");
// to get Sale List Parameter
// you are modify
String biz_id = req.getParameter("biz_id");
String begindate = req.getParameter("begindate");
String enddate = req.getParameter("enddate");
// send parameter , set Parameter to get Data List from Database
// you are modify
sa.processDaySale(biz_id, enddate);
ServletOutputStream out = res.getOutputStream();
try {
WritableWorkbook workbook = Workbook.createWorkbook(out);
WritableSheet sheet = workbook.createSheet("datesale", 0);
// head cell
WritableCellFormat cf = new WritableCellFormat();
cf.setAlignment(Alignment.CENTRE);
cf.setBackground(Colour.LIGHT_GREEN);
cf.setWrap(true);
// data cell
WritableCellFormat cf2 = new WritableCellFormat();
cf2.setAlignment(Alignment.CENTRE);
cf2.setWrap(true);
// total cell
WritableCellFormat cf3 = new WritableCellFormat();
cf3.setAlignment(Alignment.CENTRE);
cf3.setBackground(Colour.LIME);
cf3.setWrap(true);
// etc
WritableCellFormat cf4 = new WritableCellFormat();
cf4.setBackground(Colour.LIME);
cf4.setWrap(true);
// column width setting
sheet.setColumnView(0, 10);
sheet.setColumnView(1, 15);
sheet.setColumnView(2, 15);
sheet.setColumnView(3, 15);
sheet.setColumnView(4, 15);
sheet.setColumnView(5, 15);
sheet.setColumnView(6, 15);
sheet.setColumnView(7, 15);
// head row setting
Label label = new Label(0, 0, "NO.", cf);
sheet.addCell(label);
label = new Label(1, 0, "sale_date", cf);
sheet.addCell(label);
label = new Label(2, 0, "week", cf);
sheet.addCell(label);
label = new Label(3, 0, "total_sale", cf);
sheet.addCell(label);
label = new Label(4, 0, "net_sale", cf);
sheet.addCell(label);
label = new Label(5, 0, "cash", cf);
sheet.addCell(label);
label = new Label(6, 0, "card", cf);
sheet.addCell(label);
label = new Label(7, 0, "merch_bond", cf);
sheet.addCell(label);
// data row setting
int t_total = 0;
int t_net = 0;
Number number = null;
int maxRow = sa.getCount();
for(int i = 0; i < maxRow; i++) {
int t_sales = sa.getTotal_Sales_Price(i);
int n_sales = sa.getTotal_Sales_Price(i) - sa.getTotal_Dc_Price(i);
number = new Number(0, i+1, i + 1, cf2);
sheet.addCell(number);
label = new Label(1, i+1, sa.getSale_Time(i), cf2);
sheet.addCell(label);
number = new Number(2, i+1, t_sales);
sheet.addCell(number);
number = new Number(3, i+1, sa.getTotal_Dc_Price(i));
sheet.addCell(number);
number = new Number(4, i+1, n_sales);
sheet.addCell(number);
number = new Number(5, i+1, sa.getCash(i));
sheet.addCell(number);
number = new Number(6, i+1, sa.getCredit_Card(i));
sheet.addCell(number);
number = new Number(7, i+1, sa.getMerch_bond(i));
sheet.addCell(number);
t_total = t_total + t_sales;
t_net = t_net + n_sales;
// total row setting
label = new Label(0, maxRow + 2, "", cf4);
sheet.addCell(label);
label = new Label(1, maxRow + 2, "Total : ", cf3);
sheet.addCell(label);
number = new Number(2, maxRow + 2, t_total, cf4);
sheet.addCell(number);
label = new Label(3, maxRow + 2, "", cf4);
sheet.addCell(label);
number = new Number(4, maxRow + 2, t_net, cf4);
sheet.addCell(number);
label = new Label(5, maxRow + 2, "", cf4);
sheet.addCell(label);
label = new Label(6, maxRow + 2, "", cf4);
sheet.addCell(label);
label = new Label(7, maxRow + 2, "", cf4);
sheet.addCell(label);
workbook.write();
workbook.close();
} catch(JXLException e) {
e.printStackTrace();humm
may be servlet link's target have to hidden frame
i don't know correctly reason...
Maybe you are looking for
-
I am unable to download iTunes (10.5.2).
I am unable to download iTunes (10.5.2). When I attempt to download I get an error message which reads: "Apple Software Update Errors occured while installing the updates. If the problem persists, choose Tools>Download Only and try installing manuall
-
Traversing the entire nodes of an xml document ?
Hi, I want to traverse through the entire nodes of an if_ixml_document. which is the best way to do this? Please find the sample document. <text> <id> <guid auto="false"> 432543254543 </guid> </id> <title
-
Hi What is difference between pr quantity and pr requested quantity and open pr quantity? Thanks and regards Anil
-
Zoom app for the iphone video cam?
would it be possible to add zoom to the video cam using a 3rd party application?
-
Server Issue with Oracle and ASP Connection
We got a new server and are trying to set it up with Oracle Client to allow our web application to connect to the database server. We are getting connection errors, but on the old server, it works fine. We have Windows 2003 and IIS 6.0 on the new ser