struts2 freemarker 导出word

[color=green]
1.最近忙于锻炼身体,好久不写文章了,简单写一个导出word的例子,很多管理系统中会有一个常用的功能就是导出word文件,excel文件,pdf文件等,不必多说,好处您懂的。
直接上代码了,不写文字描述了。
[/color]

public class UserAction extends ActionSupport {

private User user;//省略get和set
/**
* 导出word
*/
public void exportObj() {
if (null != pkId && pkId.trim().length() > 0) {
user = this.userService.getById(User.class,pkId);
}
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
Map data = new HashMap();
data.put("user", this.getUser());
configuration.setClassForTemplateLoading(getClass(),
"/com/test/yale/template");
Template t = null;
try {
t = configuration.getTemplate("user.ftl");//载入模版文件(把要导出的word模版另存为word xml就可以了)
t.setEncoding("utf-8");
} catch (IOException e) {
e.printStackTrace();
}
String fileName = "人员确认书.doc";
//人员头像导出
if(null!=this.getUser().getPhoto()){
try {
String address = ServletActionContext.getServletContext()
.getRealPath("/");
String dir = address + "images/orgseal/"
+ this.getUser().getPhoto();//获得图片位置包括图片全名
String image = getImageBase64Data(dir);//把图片转换成BASE64形式
if (image == null) {
data.put("photo","无头像");
} else {
data.put("photo", image);
}
} catch (Exception e) {
data.put("stuphoto", "无头像");
}
}

ActionContext ctx = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) ctx
.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse");
response.setContentType("application/msword");
try {
response.addHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode(fileName, "UTF-8"));

response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
t.process(data, out);
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}

}
}

下面看图片转换BASE64方法:

/**
* 获得图片64位编码数据
* @param imgSrc
* @return
*/
private String getImageBase64Data(String imgSrc){
InputStream in =null;
byte[] data = null;
try{
in = new FileInputStream(imgSrc);
data = new byte[in.available()];
in.read(data);
in.close();
}catch(IOException ex){
ex.printStackTrace();
}
Base64EncoderNew encoder = new Base64EncoderNew();
return encoder.encode(data);
}

其中Base64EncoderNew 在网上可以找到 是重写sun 的

public class Base64EncoderNew {

private static char[] codec_table = { 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '+', '/' };

public Base64EncoderNew() {

}

public String encode(byte[] a) {
int totalBits = a.length * 8;
int nn = totalBits % 6;
int curPos = 0;// process bits
StringBuffer toReturn = new StringBuffer();
while (curPos < totalBits) {
int bytePos = curPos / 8;
switch (curPos % 8) {
case 0:
toReturn.append(codec_table[(a[bytePos] & 0xfc) >> 2]);
break;
case 2:

toReturn.append(codec_table[(a[bytePos] & 0x3f)]);
break;
case 4:
if (bytePos == a.length - 1) {
toReturn
.append(codec_table[((a[bytePos] & 0x0f) << 2) & 0x3f]);
} else { int pos = (((a[bytePos] & 0x0f) << 2) | ((a[bytePos + 1] & 0xc0) >> 6)) & 0x3f;
toReturn.append(codec_table[pos]);
}
break;
case 6:
if (bytePos == a.length - 1) {
toReturn
.append(codec_table[((a[bytePos] & 0x03) << 4) & 0x3f]);
} else {
int pos = (((a[bytePos] & 0x03) << 4) | ((a[bytePos + 1] & 0xf0) >> 4)) & 0x3f;
toReturn.append(codec_table[pos]);
}
break;
default:
//never hanppen
break;
}
curPos+=6;
}
if(nn==2)
{
toReturn.append("==");
}
else if(nn==4)
{
toReturn.append("=");
}
return toReturn.toString();

}

}

use.ftl 主要内容

<#--定义变量 赋值-->
<#assign euserdata={}/>
<#assign img={}/>
<#if user??>
<#assign userdata=user/>
</#if>
<#if photo??>
<#assign img=photo/>
</#if>
<#--显示数据-->
用户名:${userdata.userName!''}
注册时间:${userdata.regDate?string('yyyy-MM-dd')}
用户头像:
<w:pict>
<v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f">
<v:stroke joinstyle="miter"/>
<v:formulas>
<v:f eqn="if lineDrawn pixelLineWidth 0"/>
<v:f eqn="sum @0 1 0"/>
<v:f eqn="sum 0 0 @1"/>
<v:f eqn="prod @2 1 2"/>
<v:f eqn="prod @3 21600 pixelWidth"/>
<v:f eqn="prod @3 21600 pixelHeight"/>
<v:f eqn="sum @0 0 1"/>
<v:f eqn="prod @6 1 2"/>
<v:f eqn="prod @7 21600 pixelWidth"/>
<v:f eqn="sum @8 21600 0"/>
<v:f eqn="prod @7 21600 pixelHeight"/>
<v:f eqn="sum @10 21600 0"/>
</v:formulas>
<v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/>
<o:lock v:ext="edit" aspectratio="t"/>
</v:shapetype>
<w:binData w:name="wordml://03000001.png" xml:space="preserve">${img}</w:binData>
<v:shape id="_x0000_i1025" type="#_x0000_t75" style="width:68.25pt;height:62.25pt">
<v:imagedata src="wordml://03000001.png" o:title="seal"/>
</v:shape>
</w:pict>

简单说这些吧,对了,还有一个重点,就是word模版另存为xml的时候,记得用office2003,要不然图片无法显示,07的word xml格式有改动!!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值