|
|
|
![]() |
|
Strumenti |
![]() |
#1 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
[JAVA] esportare in xls
Salve ragazzi, sono nuovo di questo forum e spero di trovare quello che mi serve. Prima di tutto mi scuso se questa non è la sessione adatta dove inserire questa discussione, ma nn ho trovato niente di meglio.
Vi spiego brevemente il mio problema. Ho una pagina jsp caricata da una servlet apposita che prende dei valori da un DB Mysql e li mostra nel browser. Alla fine di questa pagina ho un bottone che serve per salvare la pagina così com'è in un file Excel utilizzando le librerie jxl.jar (mi hanno messo solo queste a disposizione!!) Adesso il problema è: come faccio?? Io so creare un nuovo foglio di lavoro excel...ma per settare tutti i campi della pagina al posto giusto?? Se qualcuno è in grado di aiutarmi gli mando senza problemi il codice relativo alla pagina e alla servlet fatte finora!! Vi ringrazio moltissimo in anticipo!!! Daniele |
![]() |
![]() |
![]() |
#2 |
Senior Member
Iscritto dal: Feb 2002
Città: Trento
Messaggi: 962
|
__________________
"Et Eärallo Endorenna utúlien. Sinome maruvan ar Hildinyar tenn' Ambar-metta!" -- Aragorn Elessar, Heir of Isildur Mixmar -- OpenSuSE 11.1 on AMD 64 3000+ on DFI LanParty nF4-D | GeForce 6600 GT + Thermaltake Schooner on Samsung 710N Storage -- ( 2 x Hitachi Deskstar 80 Gb + 1 x Hitachi 250 Gb ) = 1 RAID 5 + 1 Storage space LaCie Ethernet Disk Mini 250 Gb | HP - DV2150 EL MILAN CLAN |
![]() |
![]() |
![]() |
#3 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
Innanzi tutto ti ringrazio per la tua risposta. Il problema è che devo utilizzare la libreria jxl.jar che è quella che mi hanno detto di usare.
Sinceramente non so se le due librerie hanno qualche differenza tra loro, ma questa è quella che ho. ![]() Se hai bisogno del codice di quello che ho fatto per potermi aiutare più facilmente ti mando i file interessati. Ti ringrazio moltissimo per la disponibilità... |
![]() |
![]() |
![]() |
#4 |
Senior Member
Iscritto dal: Nov 2003
Messaggi: 980
|
Excel può leggere una tabella html. Quindi se tu mandi in output una tabella html e usi i giusti header (content-type: application/excel o qualcosa di simile e content-disposition:attachment) puoi scaricare un bel file excel.
![]() |
![]() |
![]() |
![]() |
#5 | |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
Quote:
Questa è un'ottima cosa.... ![]() <form action="Export" method="get"> <input type ="submit" name="main" value="Export in .XLS" /> </form> la nuova servlet Export nel metodo doGet(...) può fare quello che ho detto semplicemente mandando in output la tabella html?? Mi potresti dire brevemente le operazioni da fare all'interno del metodo doGet?... Scusa per la mia ignoranza in materia, ma è la prima volta che mi capita una cosa del genere ed ho pochissimo tempo per farla...una volta che riesco nel mio intento studierò meglio le cose in modo da capirci anche qualcosa visto che è una cosa che mi piace pure molto... |
|
![]() |
![]() |
![]() |
#6 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
UP
![]() ![]() |
![]() |
![]() |
![]() |
#7 |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
|
![]() |
![]() |
![]() |
#8 | |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
Quote:
Grazie dell'interessamento...le POI non le ho mai utilizzate e non saprei come fare...mi hanno dato questa libreria jxs.jar e mi sono attenuto alle specifiche. Il fatto è che non è proprio così semplice (o forse io non ci arrivo proprio!!) Se ti va di farmi vedere un esempio con un po' di codice per capire come utilizzare queste POI e soprattutto da dove scaricarle per poterle aggiungere al mio progetto te ne sarei davvero grato... Daniele |
|
![]() |
![]() |
![]() |
#9 | |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
Quote:
Codice:
try { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("pagina 1"); HSSFRow row = null; row = sheet.createRow(0); row.createCell((short)0).setCellValue("xyz1"); row.createCell((short)1).setCellValue("xyz2"); HSSFSheet sheets = wb.createSheet("pagina 2"); HSSFRow rows = null; rows = sheets.createRow(0); rows.createCell((short)0).setCellValue("xyz1"); rows.createCell((short)1).setCellValue("xyz2"); FileOutputStream fileOut = new FileOutputStream("filetest.xls"); wb.write(fileOut); fileOut.close(); } catch ( Exception ex ) { ex.printStackTrace(); } ...ciao Andrea... |
|
![]() |
![]() |
![]() |
#10 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
Grazie per l'aiuto, ma il mio problema è un altro. Sicuramente non mi sono spiegato bene. Cercherò di farlo adesso.
Io ho una pagina jsp chiamata "riepilogo" all'interno della quale ho un button al cliccare del quale mi deve far avere l'intera pagina riepilogo su un foglio Excel. Cliccando questo bottone il controllo passa a una servlet "Export" nel metodo doGet. Fin qui credo di essere stato chiaro. Adesso il metodo doGet mi deve dare modo di creare tale pagina excel. Nel modo che mi hai detto te dovrei settare cella per cella dell'intera pagina e credo sia un lavoro molto lungo visto che la pagina "riepilogo" non consta di poche righe. Mi chiedevo se ci fosse un modo per poter mandare in Input al Workbook la pagina riepilogo all'interno del metodo doGet della servlet che ti ho appena detto. Spero di essere stato sufficientemente chiaro adesso ![]() Daniele |
![]() |
![]() |
![]() |
#11 | |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
Quote:
...ciao Andrea... |
|
![]() |
![]() |
![]() |
#12 | |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
Quote:
![]() ![]() ![]() |
|
![]() |
![]() |
![]() |
#13 |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
|
![]() |
![]() |
![]() |
#14 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
i dati alla jsp me li vado a prendere da DB mysql...nella servlet poi uso la getParameter...
|
![]() |
![]() |
![]() |
#15 |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
|
![]() |
![]() |
![]() |
#16 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
si...io non ho fatto tutto questo....mi hanno dato le pagine jsp già fatte....e dovevo connetterle fra loro con delle servelt. Nelle servelt ho fatto tutti i controlli sulla correttezza dei dati inseriti nel DB e il passaggio da una pagina all'altra.
Nell'ultima pagina devo annettere a quel bottone quello che ti ho spiegato prima e non ho proprio idea di come fare perchè non riesco in nessun modo a salvarmi la pagina per poi "passarla in Input" alla pagina Excel. |
![]() |
![]() |
![]() |
#17 | |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
Quote:
Codice:
request.getSession().setAttribute("oggettone",oggetto); |
|
![]() |
![]() |
![]() |
#18 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
quindi te mi dici di fare nella servlet Export una
request.getSession().... e quello che mi restituisce lo passo come parametro ai dati della pagina excel?? Scusa la mia ignoranza ma queste librerie che non sono di default di JDK non le ho proprio mai usate e mi restano ignote.... |
![]() |
![]() |
![]() |
#19 | |
Bannato
Iscritto dal: Jan 2003
Città:
Messaggi: 4421
|
Quote:
...ciao Andrea... |
|
![]() |
![]() |
![]() |
#20 |
Junior Member
Iscritto dal: Mar 2010
Messaggi: 16
|
ok....allora
Questa è la pagina jsp: Codice:
<%-- Document : paginaRiepilogo Created on : 23-set-2009, 16.15.20 Author : Daniele Bertelli --%> <html> <%@page import="java.sql.*, java.text.DecimalFormat, java.util.GregorianCalendar, java.text.SimpleDateFormat, java.util.Calendar" %> <head> <title> WEST SYSTEMS </title> <script type="text/javascript"> function SelectPost() { document.reload.method = "post"; document.reload.action = "Riepilogo"; document.reload.submit(); } </script> </head> <body> <%!private static final String DATE_FORMAT = "dd MMMMMMMMM yyyy";%> <% String par = (String) request.getAttribute("parametro"); String url = "com.mysql.jdbc.Driver"; Connection conn = null; try { Class.forName(url); conn = DriverManager.getConnection("jdbc:mysql://localhost/tirocinio?user=root&password=10a5gr8b"); } catch (Exception exc) { out.println(exc.toString()); } %> <div align="center"> <strong> <label for="Intestazione"> RIEPILOGO DATI PREVENTIVO </label><br><br> </strong> <form name="myform" action="PrimaPagina" method="get"> <p> </p> <table width="688" border="0" cellspacing="1" cellpadding="2"> <%Statement stm = null, stm2 = null; ResultSet rst = null; String queryPrev = ""; int ID = 0; stm = conn.createStatement(); stm2 = conn.createStatement(); if (par.equalsIgnoreCase("nessun_parametro")) { queryPrev = "SELECT * FROM preventivo"; } else { String[] tmp = par.split(","); ID = Integer.parseInt(tmp[0]); queryPrev = "SELECT * FROM preventivo WHERE IDpreventivo=" + ID + ";"; } rst = stm.executeQuery(queryPrev); ResultSet prev = stm2.executeQuery("SELECT * FROM preventivo"); rst.last(); ID = Integer.parseInt(rst.getString("IDpreventivo")); %> <tr> <td width="154"><label for="Nome" >Nome: </label></td> <td width="523" bgcolor="#EAEAEA"><input type="text" name="nome" size="50" value="<%=rst.getString("Nome")%>" readonly/></td> </tr> <tr> <td><label for="Descrizione" >Descrizione:</label></td> <td bgcolor="#DBDBDB"><input type="text" name="descrizione" size="50" value="<%=rst.getString(3)%>" readonly/></td> </tr> <tr> <%Statement temp = null; ResultSet rstTemp = null; temp = conn.createStatement(); rstTemp = temp.executeQuery("SELECT Nome FROM clienti WHERE IDcliente=" + Integer.parseInt(rst.getString(6)) + ";"); rstTemp.next(); %> <td><label for="Committente" >Committente:</label></td> <td bgcolor="#DBDBDB"><input type="text" name="committente" size="50" value="<%=rstTemp.getString("Nome")%>" readonly/></td> </tr> <tr> <%temp = null; rstTemp = null; temp = conn.createStatement(); rstTemp = temp.executeQuery("SELECT Nome, Cognome FROM utenti WHERE IDutente=" + Integer.parseInt(rst.getString(7)) + ";"); rstTemp.next(); %> <td><label for="Responsabile" >Responsabile:</label></td> <td bgcolor="#DBDBDB"><input type="text" name="responsabile" size="50" value="<%=rstTemp.getString("Nome") + " " + rstTemp.getString("Cognome")%>"readonly/></td> </tr> <tr> <%String[] data = rst.getString(4).split("-"); GregorianCalendar gc = new GregorianCalendar(Integer.parseInt(data[0]), Integer.parseInt(data[1]) - 1, Integer.parseInt(data[2])); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT); %> <td><label for="Inizio" >Data di inizio:</label></td> <td bgcolor="#DBDBDB"><input type="text" name="inizio" size="50" value="<%=sdf.format(gc.getTime())%>" readonly/></td> </tr> <tr> <td><label for="Durata">Durata Preventivata:</label></td> <td bgcolor="#DBDBDB"><input type="text" name="durata" size="50" value="<%=rst.getString(5)%> mesi" readonly/></td> </tr> <tr><td></td></tr> <tr><td></td></tr> <tr> <%gc.add(Calendar.MONTH, Integer.parseInt(rst.getString(5)));%> <td><label for="Fine"><b>Fine prevista per il:</b></label></td> <td bgcolor="#DBDBDB"><b><input type="text" name="fine" size="50" value="<%=sdf.format(gc.getTime())%>" readonly/></b></td> </tr> </table> <br><br> <% /* Calcolo il COSTO TOTALE MANODOPERA */ temp = null; rstTemp = null; temp = conn.createStatement(); rstTemp = temp.executeQuery("SELECT IDqualifica, NumeroOre FROM preventivoqualifica WHERE IDpreventivo=" + Integer.parseInt(rst.getString(1)) + ";"); double costo = 0.00; Statement in = null; while (rstTemp.next()) { in = conn.createStatement(); ResultSet s = in.executeQuery("SELECT CostoOrario FROM qualifica WHERE IDqualifica=" + rstTemp.getString("IDqualifica") + ";"); s.next(); costo += Double.parseDouble(s.getString("CostoOrario")) * Double.parseDouble(rstTemp.getString("NumeroOre")); in.close(); } DecimalFormat format = new DecimalFormat("0.00"); %> <label for="Costo"> <b><font color="blue">Costo della manodopera qualificata utilizzata:</font></b> </label> <input type="text" name="durata" size="20" value="<%=format.format(costo)%>" readonly/> <label for="euro">Euro</label><br><br> <table width="500" border="0" cellspacing="1" cellpadding="2"> <% Statement att = null, att2 = null, att3 = null, inQ = null; ResultSet rstAtt = null, rstQual = null; att = conn.createStatement(); att2 = conn.createStatement(); att3 = conn.createStatement(); inQ = conn.createStatement(); rst = att.executeQuery("SELECT * FROM preventivo;"); rst.last(); rstAtt = att2.executeQuery("SELECT * FROM attivitapreventivo WHERE IDpreventivo=" + ID + ";"); while (rstAtt.next()) { rstQual = inQ.executeQuery("SELECT * FROM preventivoqualifica WHERE IDpreventivo=" + ID + " AND IDattivita=" + Integer.parseInt(rstAtt.getString("IDattivita")) + ";"); rstTemp = att3.executeQuery("SELECT Nome FROM attivita WHERE IDattivita=" + Integer.parseInt(rstAtt.getString("IDattivita")) + ";"); rstTemp.next(); %> <tr> <td></td> <td><hr noshade size="1" style="color:black"></td> <td><hr noshade size="1" style="color:black"></td> <td></td> </tr> <tr> <td width="150"><label for="Attività" style="color:blue">Attività</label></td> <td width="150"><label for="Durata" style="color:blue">Durata</label></td> <td width="150"><label for="Numero Ore" style="color:blue">Numero di ore</label></td> <td width="50"><label for="Shift" style="color:blue" >Shift</label></td> </tr> <tr> <td width="150"> <%=rstTemp.getString("Nome")%></td> <td width="150"><%=rstAtt.getString("Durata")%> mese/i</td> <td width="150"><%=rstAtt.getString("NumeroOre")%></td> <td width="50"><%=rstAtt.getString("ShiftTemporale")%></td> </tr> <% while (rstQual.next()) { rstTemp = att3.executeQuery("SELECT Descrizione FROM qualifica WHERE IDqualifica=" + Integer.parseInt(rstQual.getString("IDqualifica")) + ";"); rstTemp.next(); %> <tr> <td width="150"></td> <td width="150"><label for="Durata" style="color:red">Qualifica</label></td> <td width="150"><label for="Numero Ore" style="color:red">Numero di ore</label></td> <td width="50"><label for="Shift" style="color:red" >Shift</label></td> </tr> <tr> <td width="150"></td> <td width="150"><%=rstTemp.getString("Descrizione")%></td> <td width="150"><%=rstQual.getString("NumeroOre")%></td> <td width="50"><%=rstQual.getString("ShiftTemporale")%></td> </tr> <% } }%> </table> <br><br><input type="submit" name="submit" value="Inserisci altri preventivi"/> </form> </div> <p></p> <div align="center"> <table border="0"> <tr> <td width="100" align="center" valign="middle"> <form action="Start" method="get"> <input type ="submit" name="main" value="Torna alla HomePage" /> </form> </td> <td width="100" align="center" valign="middle"> <p> <label for=spazio" ></label> </p> </td> <td width="100" align="center" valign="middle"> <p> <label for=Scelta" >Scegli il preventivo da visualizzare</label> </p> </td> <td width="100" align="center" valign="middle"> <form action="Riepilogo" name="reload" method="get"> <select name="Prev" id="Prev" onchange="SelectPost()"> <option selected> <%=" "%></option> <% while (prev.next()) {%> <option> <%=prev.getString("IDpreventivo") + ", " + prev.getString("Nome")%> </option> <%}%> </select> </form> </td> </tr> <tr> <td></td> <td></td> </tr> </table> </div> <p></p> <div align="center"> <table border="0"> <tr> <td width="100" align="center" valign="middle"> <form action="Export" method="get"> <input type ="submit" name="main" value="Export in .XLS" /> </form> </td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> </tr> </table> </div> </body> </html> Codice:
import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class Export extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = null; try { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-Disposition", "attachment"); WritableWorkbook w = Workbook.createWorkbook(response.getOutputStream()); WritableSheet s = w.createSheet("Demo", 0); s.addCell(new Label(0, 0, "Hello World")); w.write(); w.close(); } catch (Exception e) { throw new ServletException("Exception in Excel Sample Servlet", e); } finally { if (out != null) { out.close(); } } } } Grazie ancora per l'immensa disponibilità.... |
![]() |
![]() |
![]() |
Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 05:50.