I have managed to export an Excel report with POI, but I want to do with Word can guide me on the parameters in the export.
My code java:
public void generarExcel() {
try{
LOGGER.info("Entro a Generar Excel de los Sistemas Asociados");
Reporteador reporteador = new Reporteador();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String ruta = servletContext.getRealPath("/");
reporteador.generaExcelSistema("ReporteSistemas", ruta, sists);
} catch (Exception e) {
LOGGER.debug(Constante.EXECPCION_ENCONTRADA + e.toString(), e);
}
}
------------------
public void generaExcelSistema(String nombre, String ruta, List<Sistema> sists) {
try{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Sistema");
sheet.addMergedRegion(new CellRangeAddress(6,6,3,5));
sheet.setColumnWidth(1, 1500);
sheet.setColumnWidth(2, 4000);
sheet.setColumnWidth(3, 9000);
sheet.setColumnWidth(4, 6000);
sheet.setColumnWidth(5, 6000);
sheet.setColumnWidth(6, 4500);
sheet.setColumnWidth(7, 3000);
cabeceraReportExcel(wb, sheet, ruta);
encabezadoColumnaSistema(wb, sheet, sists);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseContentType("application/vnd.ms-excel");
externalContext.setResponseHeader("Content-Disposition", "attachment; filename=\""+nombre+".xls\"");
wb.write(externalContext.getResponseOutputStream());
facesContext.responseComplete();
} catch(Exception e){
LOGGER.debug(Constante.EXECPCION_ENCONTRADA + e.toString(), e);
}
}
I hope you can guide me using the HWPFDocument class.
Related
How to write data from edit text into excel file in android?
I want to bypass data from editText into excel file without opening it from storage. Can i know how to do it?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Activity activity = this;
scanBtn = (Button) findViewById(R.id.BtnScn);
resultSC = (TextView) findViewById(R.id.SC_text);
ExelWrite = (Button) findViewById(R.id.ExelWrite);
SetTemp = (EditText) findViewById(R.id.SetTemp);
scanBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
startActivity(new Intent(getApplicationContext(),ScanCodeActivity.class));
}
});
ExelWrite.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.ExelWrite:
saveExcelFile(this,"Staff_Temperature.xls");
break;
}
}
private static boolean saveExcelFile(MainActivity context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
return false;
}
boolean success = false;
This is where I create The workbook for the excel
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
//Cell style for header row'
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("RiSE");
// Generate column headings
Row row = sheet1.createRow(0);
c = row.createCell(0);
c.setCellValue("Staff Credential");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Staff Temperature");
c.setCellStyle(cs);
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
This is where I create Path for the file. I think It should be here, but I dont know how to call it
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
public static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
public static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
addInterceptor ->HttpLoggingInterceptor bug-->OOM
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
File httpCacheDirectory = new File(MyApplication.mContext.getCacheDir(), "responses");
//设置缓存 10M
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
OkHttpClient client = null;
final TrustManager[] trustManager = new TrustManager[]{
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
}
};
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManager, new SecureRandom());
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
client = new OkHttpClient.Builder().addInterceptor(interceptor).sslSocketFactory(sslSocketFactory).addInterceptor(new BaseInterceptor()).hostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).cache(cache).build();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
_instance = new Retrofit.Builder().baseUrl(ConstantUtils.HOST)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).client(client).build();
}
return _instance.create(ICommonService.class);
RetrofitUtils.generateCommonService().down().subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ResponseBody>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
LogUtils.e("errorrrrrrrrrr");
}
#Override
public void onNext(ResponseBody responseBody) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
byte[] by = responseBody.bytes();
File file = new File(BaseApplication.getContext().getFilesDir(), "download.apk");
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(by);
LogUtils.e("length=======>",file.length()+"");
mainView.updateApk(file);
}catch (IOException e){
e.printStackTrace();
}finally {
if (bos != null)
{
try
{
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
if (fos != null)
{
try
{
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
LogUtils.e("success=========");
}
});
When you use HttpLoggingInterceptor.Level.BODY , then you try to download large file , will save all body in memory for log.
That's easy let to OOM .
Try to remove log body or just logging NONE , basic or header and try again.
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径
Try this .
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
//设置缓存路径
I have a jsf form that takes an email address, brief description, and image from the user. The else statement below is completely ignored when file==null. If a picture isn't uploaded I want an error telling the user they have to upload a image. How do I accomplish this?
import org.primefaces.model.UploadedFile;
private UploadedFile file;
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
}
public String upload() {
if (file!=null ) {
try {
System.out.println(file.getFileName());
InputStream fin2 = file.getInputstream();
Connection con = DataConnect.getConnection();
PreparedStatement pre = con.prepareStatement("insert into PICTURE_TABLE (EMAIL_ADDRESS,PRICE,ITEM_DESC,PICTURES,DATE) values(?,?,?,?,?)");
pre.setString(1, email);
pre.setString(2, price);
pre.setString(3,itemDesc);
pre.setBinaryStream(4, fin2, file.getSize());
pre.setString(5,time);
pre.executeUpdate();
System.out.println("Inserting Successfully!");
}
catch (Exception e) {
System.out.println("Exception-File Upload." + e.getMessage());
return "imageFail";
}
}
else{
FacesMessage msg = new FacesMessage("Please select image!!");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
this is the jsf tag I'm using.
<h:form enctype="multipart/form-data"
I set filename in the HttpServletResponse header but when I download it has not this filename
FileInputStream fis = new FileInputStream(fileDocumento);
PortletResponse portletResponse=(PortletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
HttpServletResponse res = PortalUtil.getHttpServletResponse(portletResponse);
res.setHeader("Content-Disposition", "attachment; filename=schedaObiettivoTAC_.docx");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
res.flushBuffer();
OutputStream out=res.getOutputStream();
out.write(IOUtils.toByteArray(fis));
out.close();
fis.close();
You should not use the HttpServletResponse. Instead you should create a custom Resource and ResourceHandler:
CustomResourceHandler.java:
public final class CustomResourceHandler extends ResourceHandlerWrapper {
// Public Constants
public static final String LIBRARY_NAME = "exampleLib";
public static final String RESOURCE_NAME = "exampleName";
// Private Data Members
private ResourceHandler wrappedResourceHandler;
public CustomResourceHandler(ResourceHandler resourceHandler) {
this.wrappedResourceHandler = resourceHandler;
}
#Override
public Resource createResource(String resourceName, String libraryName) {
if (LIBRARY_NAME.equals(libraryName)) {
if (RESOURCE_NAME.equals(resourceName)) {
return new CustomResource(libraryName, resourceName,
"exampleFileName.txt", "Example Content");
}
else {
return super.createResource(resourceName, libraryName);
}
}
else {
return super.createResource(resourceName, libraryName);
}
}
#Override
public ResourceHandler getWrapped() {
return wrappedResourceHandler;
}
#Override
public boolean libraryExists(String libraryName) {
if (LIBRARY_NAME.equals(libraryName)) {
return true;
}
else {
return super.libraryExists(libraryName);
}
}
/* package-private */ static final class CustomResource extends Resource {
private final String content;
private final Map<String, String> responseHeaders;
private final String requestPath;
private final URL url;
public CustomResource(String libraryName, String resourceName,
String fileName, String content) {
super.setLibraryName(libraryName);
super.setResourceName(resourceName);
super.setContentType("text/plain");
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put("Content-Disposition",
"attachment; filename=" + fileName + ";");
this.responseHeaders = Collections.unmodifiableMap(responseHeaders);
StringBuilder sb = new StringBuilder();
sb.append(ResourceHandler.RESOURCE_IDENTIFIER);
sb.append("/");
sb.append(super.getResourceName());
sb.append("?ln=");
sb.append(super.getLibraryName());
this.requestPath = sb.toString();
URL url;
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
url = new URL(externalContext.encodeResourceURL(this.requestPath));
}
catch (MalformedURLException e) {
url = null;
}
this.url = url;
this.content = content;
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(
content.getBytes(StandardCharsets.UTF_8));
}
#Override
public String getRequestPath() {
return requestPath;
}
#Override
public Map<String, String> getResponseHeaders() {
return responseHeaders;
}
#Override
public URL getURL() {
return url;
}
#Override
public boolean userAgentNeedsUpdate(FacesContext facesContext) {
// Return false if the content cannot change dynamically.
return true;
}
}
}
WEB-INF/faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<!-- ... -->
<resource-handler>custom.resource.handler.CustomResourceHandler</resource-handler>
</application>
<!-- ... -->
</faces-config>
Here's some example code for downloading the resource:
<h:outputLink target="_blank" value="#{bean.getDownloadURL(facesContext)}">
<h:outputText value="download" />
</h:outputLink>
public String getDownloadURL(FacesContext facesContext) {
return facesContext.getApplication().getResourceHandler()
.createResource(CustomResourceHandler.RESOURCE_NAME,
CustomResourceHandler.LIBRARY_NAME)
.getURL().toString();
}
You can also look at the Liferay Faces JSF Export PDF for a full portlet example to download/export a file.
If you are in the action or render phase of your portlet (what I would guess for a JSF portlet): there is a ResponseWrapper which will suppress any header. I'm using this method to find the response for sending binary data during the JSF lifecycle:
public static HttpServletResponse getHttpServletResponse() {
final FacesContext facesContext = FacesContext.getCurrentInstance();
if (facesContext == null) {
throw new IllegalStateException("Not inside a JSF request");
}
final Object responseObject = facesContext.getExternalContext().getResponse();
if (responseObject instanceof HttpServletResponse) {
return (HttpServletResponse) responseObject;
}
if (responseObject instanceof PortletResponse) {
// Use Liferays util to find the real response
HttpServletResponse response = PortalUtil.getHttpServletResponse((PortletResponse) responseObject);
// Find the outer most response (setting the headers would have no effect, as we are included)
while (response instanceof ServletResponseWrapper) {
final ServletResponse servletResponse = ((ServletResponseWrapper) response).getResponse();
if (!(servletResponse instanceof HttpServletResponse)) {
break;
}
response = (HttpServletResponse) servletResponse;
}
return response;
}
throw new IllegalStateException("Unknown type of response object: " + responseObject);
}
UPDATE:
My Requirement is to display two Rss files as Tabs on my LWUIT Form
Initially by default first Rss file titles and images should be displayed on first tab
if an end user click on second tab,we should be able to load the second rss file titles and images
I am able to load first Rss File titles,but i am not able to load the second tab if i click on it
How to capture the click event for LWUIT Tab?
Here my code which is not working:
String topNewsurl="TopNews.rss";
String topStoryurl="TopStory.rss";
public class XMLMidlet extends MIDlet{
public void startApp() {
Display.init(this);
Process p;
try {
p = new Process(this);
p.process();
} catch (IOException ex) {
ex.printStackTrace();
}
}
public class Process extends Form {
Process(XMLMidlet midlet) throws IOException {
this.midlet=midlet;
topnews = new Vector();
topstory = new Vector();
tabs = new Tabs();
form1 = new Form();
form2=new Form();
form1.setLayout(new BorderLayout());
form1.setScrollable(false);
image = Image.createImage("/res/Tone.jpg");
Label icon = new Label(image);
form1.setTitleComponent(icon);
form2.setTitleComponent(icon);
form1.setTransitionInAnimator(Transition3D.createRotation(250, true));
try {
newsList = new List(topnews);
newsList.setScrollVisible(false);
newsList.setRenderer(new NewsListCellRenderer());
myNewsList = new List(topstory);
myNewsList.setScrollVisible(false);
myNewsList.setRenderer(new NewsListCellRenderer());
tabs.addTab("Topstory", newsList);
tabs.addTab("TopNews", myNewsList);
tabs.setChangeTabOnFocus(true);
form1.addComponent(BorderLayout.CENTER, tabs);
}
try{
String url = "http:topnews-20.rss";
form1.show();
ParseThread myThread = new ParseThread(this);
myThread.getXMLFeed(url);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addNews(News newsItem) {
//log.debug("addnews");
//System.out.println("addNews");
topnews.addElement(newsItem);
newsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
List source = (List) ae.getSource();
News selectedNewsItem = (News) source.getSelectedItem();
if (selectedNewsItem != null) {
displayCompleteNewsScreen(selectedNewsItem);
}
}
});
form1.show();
}
public void keyReleased(int keyCode) {
System.out.println("str");
Component p=this.getFocused();
String str= p.getClass().getName();
if(str.toLowerCase().indexOf("radiobutton")!=-1){
process();
}
From the very vague question it seems you want to capture key presses on a LWUIT Form.
jobsForm.addGameKeyListener(Display.GAME_FIRE,
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//do something here
}
});
jobsForm.addPointerPressedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
pointer_click = true;
}
});
jobsForm.addPointerReleasedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (pointer_click) {
//
}
pointer_click = false;
}
});
jobsForm.addPointerDraggedListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//System.out.println("POINTER DRAGGED");
pointer_click = false;
}
});