Excel 报表的生成

报表的生成一般从数据库中重新取:
在struts2中action中返回一个InputStream 输入流,方法的名字必须和struts.xml文件中配置的<param name="inputName">downLoadFile</param>中的inputName相对应即get方法,第一个字母大写:
public InputStream getDownLoadFile(){
//create excel report
//first create workbook
HSSFWorkbook workBook = new HSSFWorkbook();
//create sheet
HSSFSheet sheet = workBook.createSheet("UserSheet");
//create row ,
HSSFRow row = sheet.createRow(0);
//create cell
HSSFCell cell = row.createCell((short)0);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("序号");

cell = row.createCell((short)1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("姓名");

cell = row.createCell((short)2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("年龄");

cell = row.createCell((short)3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("电子邮箱");

cell = row.createCell((short)4);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("出生日期");

cell = row.createCell((short)5);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue("地址");

List<User> users = UserUtils.getAllUsers();

for(int i = 0;i<users.size();i++){

User user = users.get(i);
//创建里一行
row = sheet.createRow(i + 1);

cell = row.createCell((short)0);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(i+1);

cell = row.createCell((short)1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getName());

cell = row.createCell((short)2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getAge());

cell = row.createCell((short)3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getEmail());

cell = row.createCell((short)4);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getBirthday());

cell = row.createCell((short)5);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(user.getAddress());
}

ByteArrayOutputStream os = new ByteArrayOutputStream();

try {
//把workBook中的数据以字节数组的形式写进输出流中
workBook.write(os);
} catch (IOException e) {
e.printStackTrace();
}
//获取输出流的内容
byte[] content = os.toByteArray();
//写进输入流中
InputStream is = new ByteArrayInputStream(content);

return is;

}
在struts.xml配置文件中的配置:
<action name="generateExcel" class="com.test.action.GenerateExcelAction">
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-excel</param>
<param name="contentDisposition">filename="UserInformation.xls"</param>
<param name="inputName">downLoadFile</param>
</result>
</action>

本论文仅供个人学习,有感兴趣的可以作为参考。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值