UseServlet.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@WebServlet("/user.do")
public class UseServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//设置字符集格式为utf-8
//req.setCharacterEncoding("UTF-8");
req.setCharacterEncoding("UTF-8");
resp.setContentType("application/vnd.ms-excel");
resp.addHeader("Content-Disposition", "attachment;filename=logininfo.xls");
String name= req.getParameter("name");
String pwd=req.getParameter("pwd");
String sex= req.getParameter("sex");
String age= req.getParameter("age");
String email= req.getParameter("email");
ServletOutputStream out = resp.getOutputStream();//响应输出流对象
HSSFWorkbook wb= new HSSFWorkbook();//创建Excel表格
HSSFSheet sheet = wb.createSheet("用户注册信息");//创建工作簿
sheet.setColumnWidth(4, 5000);//设置列宽
HSSFRow titleRow = sheet.createRow(0);//创建Excel中的标题行
HSSFCell titleCell1= titleRow.createCell(0);//在行中创建第一个单元格
titleCell1.setCellValue("用户姓名");//设置第一个单元格的值
HSSFCell titleCell2 = titleRow.createCell(1);
titleCell2.setCellValue("密码");
HSSFCell titleCell3 = titleRow.createCell(2);
titleCell3.setCellValue("性别");
HSSFCell titleCell4 = titleRow.createCell(3);
titleCell4.setCellValue("年龄");
HSSFCell titleCell5 = titleRow.createCell(4);
titleCell5.setCellValue("Email");
HSSFRow valueRow = sheet.createRow(1);//在第二行中创建单元格
HSSFCell nameCell= valueRow.createCell(0);
nameCell.setCellValue(name);
HSSFCell pwdCell= valueRow.createCell(1);
pwdCell.setCellValue(pwd);
HSSFCell sexCell= valueRow.createCell(2);
sexCell.setCellValue(sex);
HSSFCell ageCell= valueRow.createCell(3);
ageCell.setCellValue(age);
HSSFCell emailCell= valueRow.createCell(4);
emailCell.setCellValue(email);
//HSSFCellStyle cellStyle = wb.createCellStyle();
wb.write(out);//将响应流输入到表格中
out.flush();
out.close();
index.jsp
<form action="user.do" method="post">
<table align="center">
<tr>
<td>用户名:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
</td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"/></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="输入到表格"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
输出到表格时是从浏览器下载下来的,具体的我也不知道是什么原理...