如何将JSP excel生成器转换为Servlet

时间:2012-11-20 11:54:13

标签: java jsp

我能够在服务器系统中生成excel文件,但问题是每当我尝试从客户端系统访问它时,它只在服务器系统中生成,而不是在客户端系统中生成。以下代码用于生成excel文件:

<%@ page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<%@ page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%@ page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%@ page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.swing.JFileChooser" %>
<%@ page import="java.awt.Desktop"%>
<%@ page isErrorPage='true' %>


<%! 
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "s";
    String driver = "com.mysql.jdbc.Driver";
    String username = "root"; 
    String userPassword = "s";

%>
<br><br>
<%

    java.util.Date date = new java.util.Date();

    JFileChooser chooseFile=new JFileChooser();

    chooseFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooseFile.setDialogTitle("Select a Directory");

    chooseFile.showDialog(null,"Click Me to Save the Folder");
    //String filename = "/tmp/Excel "+System.currentTimeMillis() +".xls" ;




try
{

     Class.forName(driver).newInstance();
         conn = DriverManager.getConnection(url+dbName,username,userPassword);

      Statement stmt = conn.createStatement();
      String strQuery = "select * from  Meter_List";

      ResultSet rs = stmt.executeQuery(strQuery);


          HSSFWorkbook hwb = new HSSFWorkbook();
          HSSFSheet sheet = hwb.createSheet("new sheet");

          HSSFRow rowhead = sheet.createRow((short)2);
          rowhead.createCell(0).setCellValue("SNo");
          rowhead.createCell(1).setCellValue("Meterid");
          rowhead.createCell(2).setCellValue("Consumerid");
          rowhead.createCell(3).setCellValue("Consumername");
          rowhead.createCell(4).setCellValue("LastReading");
          rowhead.createCell(5).setCellValue("Date");
          rowhead.createCell(6).setCellValue("Time");
          rowhead.createCell(7).setCellValue("Status");
          rowhead.createCell(8).setCellValue("Subzone");
          rowhead.createCell(9).setCellValue("Zone");

          int index=3;
          int sno=0;
          String name="";
           while(rs.next()) 
       {
                sno++;

                HSSFRow row = sheet.createRow((short)index);
                row.createCell(0).setCellValue(sno);
                row.createCell(1).setCellValue(rs.getInt("Meterid"));
                row.createCell(2).setCellValue(rs.getInt("Consumerid"));
                row.createCell(3).setCellValue(rs.getString("Consumername"));
                row.createCell(4).setCellValue(rs.getInt("lastreading"));
                row.createCell(5).setCellValue(rs.getDate("Date"));
                row.createCell(6).setCellValue(rs.getTime("Time"));
                row.createCell(7).setCellValue(rs.getString("Status"));
                row.createCell(8).setCellValue(rs.getString("Subzone"));
                row.createCell(9).setCellValue(rs.getString("Zone"));
                index++;
       }

          FileOutputStream fileOut = new FileOutputStream(filename);
          hwb.write(fileOut);
          fileOut.close();
          out.println("<b>Opening worksheet, please wait......</b><br>");

          Desktop dt=Desktop.getDesktop();
          dt.open(new File(filename));
          out.println("<b>Worksheet opened. It is saved as -\n\t\t </b><br>"+filename);
} 
catch ( Exception ex ) 
{  
    //out.println("Error :: "+ex);
    out.println("");
} 
%>
can you please help to solve this.

2 个答案:

答案 0 :(得分:0)

要创建用户将下载的动态Excel文件,以下是基于您的代码的示例servlet:

import javax.servlet.ServletConfig;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;

/**
 *
 * @author Alexandre Lavoie
 */
@WebServlet(name = "ExcelServlet", urlPatterns = { "/servlets/excel" })
public class ExcelServlet implements HttpServlet
{
    @Override
    public void doGet(HttpServletRequest p_oRequest, HttpServletResponse p_oResponse) throws IOException, ServletException
    {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "s";
        String driver = "com.mysql.jdbc.Driver";
        String username = "root"; 
        String userPassword = "s";

        java.util.Date date = new java.util.Date();

        try
        {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url+dbName,username,userPassword);

            Statement stmt = conn.createStatement();
            String strQuery = "select * from  Meter_List";

            ResultSet rs = stmt.executeQuery(strQuery);


            HSSFWorkbook hwb = new HSSFWorkbook();
            HSSFSheet sheet = hwb.createSheet("new sheet");

            HSSFRow rowhead = sheet.createRow((short)2);
            rowhead.createCell(0).setCellValue("SNo");
            rowhead.createCell(1).setCellValue("Meterid");
            rowhead.createCell(2).setCellValue("Consumerid");
            rowhead.createCell(3).setCellValue("Consumername");
            rowhead.createCell(4).setCellValue("LastReading");
            rowhead.createCell(5).setCellValue("Date");
            rowhead.createCell(6).setCellValue("Time");
            rowhead.createCell(7).setCellValue("Status");
            rowhead.createCell(8).setCellValue("Subzone");
            rowhead.createCell(9).setCellValue("Zone");

            int index=3;
            int sno=0;
            String name="";

            while(rs.next()) 
            {
                sno++;

                HSSFRow row = sheet.createRow((short)index);
                row.createCell(0).setCellValue(sno);
                row.createCell(1).setCellValue(rs.getInt("Meterid"));
                row.createCell(2).setCellValue(rs.getInt("Consumerid"));
                row.createCell(3).setCellValue(rs.getString("Consumername"));
                row.createCell(4).setCellValue(rs.getInt("lastreading"));
                row.createCell(5).setCellValue(rs.getDate("Date"));
                row.createCell(6).setCellValue(rs.getTime("Time"));
                row.createCell(7).setCellValue(rs.getString("Status"));
                row.createCell(8).setCellValue(rs.getString("Subzone"));
                row.createCell(9).setCellValue(rs.getString("Zone"));
                index++;
            }

            // Maybe I'm wrong on that exact mime type
            p_oResponse.setContentType("application/vnd.ms-excel");
            ServletOutputStream out = p_oResponse.getOutputStream();

            hwb.write(out);

            out.flush();
            out.close();
        } 
        catch(Exception ex) 
        {  
            ex.printStackTrace();
        } 
    }

    @Override
    public void init(ServletConfig sc) throws ServletException {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ServletConfig getServletConfig() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void service(ServletRequest sr, ServletResponse sr1) throws ServletException, IOException {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getServletInfo() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void destroy() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }
}

添加到项目后,您可以使用以下网址访问此文件:

http://yourserver.com/<context-name>/servlets/excel

希望这有帮助!

答案 1 :(得分:0)

<%@ page language="java" import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.swing.JFileChooser" %>
<%@ page import="java.awt.Desktop"%>
<%@ page isErrorPage='true' %>
<%@ page import="java.text.SimpleDateFormat"%>
<%! 
    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "su";
    String driver = "com.mysql.jdbc.Driver";
    String username = "root"; 
    String userPassword = "s";

%>



<%
    String filename="";
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition","inline;filename=" + "excel_sheet"+".xls");
    response.setHeader("Cache-Control","no-cache");
    PrintWriter pout = response.getWriter();
    String date1="";
    String time="";
try
{

        Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url+dbName,username,userPassword);
            Statement stmt = conn.createStatement();
        String strQuery = "select * from  Meter_List";
        ResultSet rs = stmt.executeQuery(strQuery);
        int index=3;
            int sno=0;
            String name="";
                pout.print("SNo\t");
                pout.print("MeterID\t"  );
                pout.print("ConsumerID\t" );
                pout.print("ConsumerName\t" );

                pout.println();
            while(rs.next()) 

                     {
                                int meterid = rs.getInt("Meterid");
                        int consumerid=rs.getInt("Consumerid");
                        String consumername = rs.getString("Consumername");

                                sno++;
                        pout.print(sno + "\t");
                        pout.print(meterid + "\t" );
                        pout.print(consumerid + "\t" );
                                pout.print(consumername + "\t");

                        index++;
                        pout.println();

                     }

} 
catch ( Exception ex ) 
{  
    //out.println("Error :: "+ex);
    out.println("");
} 
%>