利用Servlet导出Excel

时间:2021-07-20 14:02:03

-----因为Excel可以打开HTML文件,因此可以利用页面的Form表单把页面中的table内容提交给Servlet,然后后台把提交上来的table内容转换成文件流的形式,并以下载的形式转给客户端,由此完成导出Excel功能。

效果:

利用Servlet导出Excel

<!--[endif]-->

Java代码

package com.mr;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* 利用Servlet导出Excel

* @author AndyChen

*

*/

public class ExportExcelServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");//设置request的编码方式,防止中文乱码

String fileName ="导出数据";//设置导出的文件名称

StringBuffer sb = new StringBuffer(request.getParameter("tableInfo"));//将表格信息放入内存

String contentType = "application/vnd.ms-excel";//定义导出文件的格式的字符串

String recommendedName = new String(fileName.getBytes(),"iso_8859_1");//设置文件名称的编码格式

response.setContentType(contentType);//设置导出文件格式

response.setHeader("Content-Disposition", "attachment; filename=" + recommendedName + "\"");//

response.resetBuffer();

//利用输出输入流导出文件

ServletOutputStream sos = response.getOutputStream();

sos.write(sb.toString().getBytes());

sos.flush();

sos.close();

}

}

Jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>导出Excel</title>

<script type="text/javascript">

function test(){

document.getElementById("tableInfo").value=document.getElementById("table").innerHTML;

}

</script>

<style>

body{font-family:宋体;font-size:11pt}

</style>

</head>

<body>

<form action="<%=request.getContextPath()%>/servlet/ExportExcelServlet" method="post">

<span id="table">

<table bgcolor="#EEECF2" bordercolor="#A3B2CC" border="1" cellspacing="0">

<tr><th>学号</th><th>姓名</th><th>科目</th><th>分数</th></tr>

<tr><td>10001</td><td>赵二</td><td>高数</td><td>82</td></tr>

<tr><td>10002</td><td>张三</td><td>高数</td><td>94</td></tr>

<tr><td>10001</td><td>赵二</td><td>线数</td><td>77</td></tr>

<tr><td>10002</td><td>张三</td><td>线数</td><td>61</td></tr>

</table>

</span><br/>

<input type="submit" name="Excel" value="导出表格" onclick="test()"/>

<input type="hidden" id="tableInfo" name="tableInfo" value=""/>

</form>

</body>

</html>