需要jxl.jar包
java:
ToExcel.java----servlet
public class ToExcel extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8"); //防止乱码
String fileName ="test"; //设置导出的文件名称
String contextType="application/vnd.ms-excel"; //定义导出文件格式的字符串
String recommendName =new String(fileName.getBytes(),"utf-8"); //设置文件名称的编码格式
response.setHeader("Content-Disposition","attachment;filename="+recommendName+".xls");
response.setCharacterEncoding(contextType); //设置导出文件格式
String[] str1 =request.getParameterValues("name");
String[] str2 = request.getParameterValues("age");
String[] name =new String[100];
name[0]="姓名";
System.arraycopy(str1, 0, name, 1, str1.length); //将str1数组拷贝到name中
String[] age =new String[100];
age[0]="年龄";
System.arraycopy(str2,0, age, 1, str2.length);
List list = new ArrayList();
list.add(name);
list.add(age);
OutputStream os = response.getOutputStream();
WritableWorkbook wwb = null;
WritableSheet sheet = null;
Label label = null;
try{
wwb = Workbook.createWorkbook(os);
}catch(IOException e){
e.printStackTrace();
}
if(wwb != null){
sheet = wwb.createSheet("sheet1",0);
}
for(int i =0;i<list.size();i++){
System.out.println(list.get(i));
String[] str =(String [])list.get(i);
for(int j=0;j<str.length;j++){
label=new Label(i,j,str[j]); //竖着排列
// label=new Label(j,i,str[j]); //横着排列
try {
sheet.addCell(label);
} catch (Exception e) {
e.printStackTrace();
}
}
}
response.resetBuffer();
wwb.write();
try {
wwb.close();
} catch (WriteException e) {
e.printStackTrace();
}
os.flush();
os.close();
}
}
jsp:
<body>
<form action="/MyDesign/ToExcel" method="post" >
<table>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name"></td>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
</table>
<input type="submit" value="提交" >
</form>
</body>
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。