如何将servlet重定向到新选项卡并在新选项卡中打开excel

时间:2014-01-03 20:11:11

标签: java jsp servlets

我正在尝试从我的servlet中生成一个excel文件。

现在,在我的servlet中,我有一个链接点击它将excel表保存在本地文件夹中。现在我想要在新标签页中打开excel表。

我的servlet看起来像这样,

在doPost中我调用的方法是从数据库表中获取值,在这个方法中我调用另一个创建excel的方法,我使用fileOut将数据写入excel。

要打开一个新标签,我在表格标签中添加了traget =“_ blank”。

我的问题是如何在新标签页面中打开生成的Excel工作表?

package com.gulf.frontcontroller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.*;
import com.gulf.common.util.DBUtil;

/**
 * Servlet implementation class ExcelReportServlet
 */
public class ExcelReportServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExcelReportServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

 // ErrorLog eLog = new ErrorLog();
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        if (DBUtil.LOG_REQUIRED)
            DBUtil.log("In JSFront Controller : init..");
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    public void getValues() {
        Connection conn = null;
        System.out.println("Hi from Do Get Valuess");
        try {
            conn = DBUtil.getConnection();

            List<HashMap<String, String>> listOfColVal = new ArrayList<HashMap<String, String>>();
            PreparedStatement selectStmt;
            selectStmt = conn.prepareStatement("select * from LTR");
            ResultSet result = selectStmt.executeQuery();
            while (result.next()) {
                HashMap<String, String> columnValues = new HashMap<String, String>();
                columnValues.put("PARTC_SSN", result.getString("PARTC_SSN"));
                columnValues.put("PARTCIPANT_NAME", result.getString("PARTCIPANT_NAME"));
                columnValues.put("CRTE_DTE", result.getString("CRTE_DTE"));
                columnValues.put("CRTE_BY", result.getString("CRTE_BY"));
                columnValues.put("RE", result.getString("REMARKS"));
                columnValues.put("SP", result.getString("ONSE"));
                columnValues.put("S", result.getString("NSE"));
                columnValues.put("TT", result.getString("TER"));
                columnValues.put("DAY", result.getString("LAPSEDDAY"));
                listOfColVal.add(columnValues);
//              System.out.println(listOfColVal);
            }
            genarateExcel(listOfColVal);

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

    public static void genarateExcel(List<HashMap<String, String>> results)
            throws IOException {
        System.out.println("Hi from Do Get genarateExcel");
        String filename = "C:/EXCEL/Result.xls";
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("FirstSheet");
//      
////        code to make the header bold
//      HSSFFont font = workbook.createFont();
//      font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//      HSSFCellStyle style = workbook.createCellStyle();
////        HSSFCell cell = row.createCell((short)i);
//      style.setFont(font);
//      style.setFillForegroundColor(HSSFColor.YELLOW.index);

//      Set the row cell 
        sheet.setColumnWidth(0, 2500);
        sheet.setColumnWidth(1, 5000);
        sheet.setColumnWidth(2, 5000);
        sheet.setColumnWidth(3, 10000);
        sheet.setColumnWidth(4, 5000);


        HSSFRow rowhead = sheet.createRow((short) 0);
        rowhead.createCell((short) 0).setCellValue("SSN");
        rowhead.createCell((short) 1).setCellValue("PARE");
        rowhead.createCell((short) 2).setCellValue("CREE");
        rowhead.createCell((short) 3).setCellValue("CRY");
        rowhead.createCell((short) 4).setCellValue("RKS");
        rowhead.createCell((short) 5).setCellValue("EMNSE");
        rowhead.createCell((short) 6).setCellValue("SONSE");
        rowhead.createCell((short) 7).setCellValue("DETER");
        rowhead.createCell((short) 8).setCellValue("LAYS");

        int i=2;
        for (HashMap<String, String> val : results) {

//          Formating todays date
            SimpleDateFormat  dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            HSSFRow row = sheet.createRow((short)i);
            row.createCell((short) 0).setCellValue(val.get("PAN"));
            row.createCell((short) 1).setCellValue(val.get("PME"));
            row.createCell((short) 2).setCellValue(val.get("CTE"));
            row.createCell((short) 3).setCellValue(val.get("CRY"));
            row.createCell((short) 4).setCellValue(val.get("RES"));
            row.createCell((short) 5).setCellValue(val.get("EME"));
            row.createCell((short) 6).setCellValue(val.get("SNSE"));
            row.createCell((short) 7).setCellValue(val.get("DTTER"));
            row.createCell((short) 8).setCellValue(val.get("LAY"));
            i++;
        }
        FileOutputStream fileOut;
        try {
            fileOut = new FileOutputStream(filename);
            workbook.write(fileOut);
            fileOut.close();
            System.out.println("Your excel file has been generated!");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Hi from Do post");
        getValues();


    }

}

1 个答案:

答案 0 :(得分:0)

不是通过FileOutputStream写入文件,而是可以写入servlet输出流。

OutputStream servletoutputstream = response.getOutputStream();
response.setContentType("application/msexcel");
response.addHeader("Content-Disposition", "filename=filename.xls");
....
workbook.write(servletoutputstream);

但正如我在评论中所说,Excel在Excel或浏览器中打开是基于您无法控制的用户设置。

相关问题