java 代码
- downloadaction.java
- //--------------------------------------------------------------------------------
- import org.apache.struts.action.*;
- import javax.servlet.http.*;
- import java.io.outputstream;
- public class downloadaction extends action {
- public actionforward execute(actionmapping mapping,
- actionform form, httpservletrequest request,
- httpservletresponse response)
- throws exception {
- try{
- string fname = "test";//excel文件名
- outputstream os = response.getoutputstream();//取得输出流
- response.reset();//清空输出流
- response.setheader("content-disposition", "attachment; filename=" + fname + ".xls");//设定输出文件头
- response.setcontenttype("application/msexcel");//定义输出类型
- excelbean eb = new excelbean();
- eb.expordexcel(os);//调用生成excel文件bean
- }catch(exception e){
- system.out.println(e);
- }
- return mapping.findforward("display");
- }
- }
生成excel文件的类:
java 代码
- Excelbean.java
- //--------------------------------------------------------------------------------
- import java.io.*;
- import jxl.*;
- import jxl.write.*;
- import jxl.format.*;
- import java.util.*;
- import java.awt.color;
- public class Excelbean {
- public Excelbean(){}
- public string expordexcel(outputstream os)throws exception{
- jxl.write.writableworkbook wbook = workbook.createworkbook(os); //建立excel文件
- string tmptitle = "测试文件"; //标题
- jxl.write.writablesheet wsheet = wbook.createsheet("第一页", 0); //sheet名称
- //设置excel标题
- jxl.write.writablefont wfont = new jxl.write.writablefont(
- writablefont.arial, 16,
- writablefont.bold, false, jxl.format.underlinestyle.no_underline,
- jxl.format.colour.black);
- jxl.write.writablecellformat wcffc = new jxl.write.writablecellformat(
- wfont);
- jxl.write.label wlabel1;
- wlabel1 = new jxl.write.label(5, 0, tmptitle, wcffc);
- wsheet.addcell(wlabel1);
- wfont = new jxl.write.writablefont(
- writablefont.arial, 14,
- writablefont.bold, false, jxl.format.underlinestyle.no_underline,
- jxl.format.colour.black);
- wcffc = new jxl.write.writablecellformat(
- wfont);
- jxl.write.label wlabel;
- wlabel = new jxl.write.label(0, 0, "写入内容");
- wsheet.addcell(wlabel); //
- wbook.write(); //写入文件
- wbook.close();
- os.close();
- return "success";
- }
- }