小谈struts2导出excel表格的思路

如题,实现这个功能(excel2003和2007均适用),使用的第三方jar包是 poi,主要是记录一下做过的东西,以便日后用。

一。jsp页面 :

<form id ="exportExcel" name="exportExcel" action="exportExcel.do" method="post">

<input type="hidden" id ="A" name="param1" >

<input type="hidden" id ="B" name="param2" >

<input type="hidden" id ="C" name="param3" >

</form>

param1,2,3是参数,传到action。

二。struts2的xml配置 :

<!-- 导出Excel -->

<action name="exportExcel" method="exportExcel" class="testAction">

<result name="success" type="stream">

<param name="contentType">application/vnd.ms-excel</param>

<param name="contentDisposition">attachment;filename="${fileName}"</param>

<param name="inputName">excelFile</param>

</result>

</action>

三。 action端,需要两个方法,一个是exportExcel()和struts配置文件指明的stream流方法excelFile().

exportExcel()

public String exportWaitOrderExcel(){

String name ="产品列表.xls";

try {

name = java.net.URLEncoder.encode(name, "UTF-8");

fileName = new String(name.getBytes(), "iso-8859-1");

} catch (UnsupportedEncodingException e) {

log4j.error("字符转码失败");

}

return SUCCESS;

}


excelFile()

public InputStream getExcelFile() //getExcelFile()一定要与excelFile对应,否则会出现异常

{

//第一步:接收参数,查询产品列表信息

String param1= getRequest().getParameter("param1");

String param2= getRequest().getParameter("param2");

String param3= getRequest().getParameter("param3");

List<ProductBean> productList = new ArrayList<ProductBean>();

Map<Object, Object> map = new HashMap<Object, Object>();

if (param1!= null && !param1.equals("")) {

map.put("param1", param1);

}

if (param2!= null && !param2.equals("")) {

map.put("param2", param2);

}

if (param3!= null && !param3.equals("")) {

map.put("param3", param3);

}

productList = productServicr.searchProductList(map);

//第二步:构建excel表格,封装数据到excel

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet sheet = workbook.createSheet("sheet1");

HSSFRow row = sheet.createRow(0);//创建第一行

HSSFCell cell = row.createCell(0);//第一列

cell.setCellValue("产品列表"); //行内容

HSSFCellStyle style = workbook.createCellStyle(); //创建样式

HSSFFont font = workbook.createFont(); //创建字体样式

font.setFontHeight((short)(20*20)); //字体

font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); //加粗

style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //居中

style.setFont(font); //设置字体样式

cell.setCellStyle(style); //设置样式

sheet.addMergedRegion(new org.apache.poi.ss.util.Region(0,(short)0,0,(short)4)); //合并列

//String menus = "产品名称,产品类型,产品描述";

row = sheet.createRow(1);//创建第一行

cell = row.createCell(0); //创建第一列

cell.setCellValue(new HSSFRichTextString("产品名称"));

cell = row.createCell(1);//创建第二列

cell.setCellValue(new HSSFRichTextString("产品类型"));

cell = row.createCell(2);//

cell.setCellValue(new HSSFRichTextString("产品描述"));

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

ProductBean product= list.get(i);

row=sheet.createRow(i+2);//创建第i+1行

cell=row.createCell(0);//创建第一列

cell.setCellValue(product.getName());

cell=row.createCell(1);//创建第二列

cell.setCellValue(product.getCategory()

cell=row.createCell(2);

cell.setCellValue(product.getDescription());

}

//第三步:写入输出流

ByteArrayOutputStream baos = new ByteArrayOutputStream();

try {

workbook.write(baos);//写入

} catch (IOException e) {

e.printStackTrace();

}

byte[] ba = baos.toByteArray();

ByteArrayInputStream bais = new ByteArrayInputStream(ba);

return bais;

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是jsp+struts2框架代码实现的示例: 1. 创建一个DownloadAction类,用于处理下载请求: ```java public class DownloadAction extends ActionSupport { private static final long serialVersionUID = 1L; private String fileName; private String contentType; private InputStream inputStream; private int bufferSize = 1024; public String execute() throws Exception { // 获取数据列表 List<Data> dataList = getDataList(); // 按照50000笔数据分批导出excel表格 int batchCount = (dataList.size() + 49999) / 50000; for (int i = 0; i < batchCount; i++) { int start = i * 50000; int end = Math.min(start + 50000, dataList.size()); List<Data> batchList = dataList.subList(start, end); // 生成excel表格并写入数据 Workbook workbook = createWorkbook(batchList); // 把excel表格写入输出流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); workbook.write(baos); baos.flush(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); // 把输出流赋值给inputStream inputStream = bais; // 设置文件名和Content-Type fileName = "data_" + (i+1) + ".xls"; contentType = "application/vnd.ms-excel"; // 返回下载结果 if (i == batchCount - 1) { return "zip"; } else { return "excel"; } } return null; } // 获取数据列表 private List<Data> getDataList() { // TODO: 获取数据列表的代码 return null; } // 生成excel表格 private Workbook createWorkbook(List<Data> dataList) { // TODO: 生成excel表格的代码 return null; } // Getters and Setters } ``` 2. 创建一个excel.jsp页面,用于导出单个excel表格: ```jsp <%@ page contentType="text/html;charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <s:actionerror /> <s:actionmessage /> <s:form action="download"> <s:submit value="导出Excel" /> </s:form> <%-- 定义下载链接 --%> <a href="<s:url action='download'/>" target="_blank">下载Excel文件</a> ``` 3. 创建一个zip.jsp页面,用于导出多个excel表格的压缩包: ```jsp <%@ page contentType="text/html;charset=UTF-8" %> <%@ taglib prefix="s" uri="/struts-tags" %> <s:actionerror /> <s:actionmessage /> <s:form action="download"> <s:submit value="导出Excel" /> </s:form> <%-- 定义下载链接 --%> <a href="<s:url action='download'/>" target="_blank">下载Zip文件</a> ``` 4. 在struts.xml文件中配置DownloadAction类和对应的结果: ```xml <struts> <package name="default" extends="struts-default"> <action name="download" class="com.example.DownloadAction"> <result name="excel" type="stream"> <param name="contentType">${contentType}</param> <param name="inputName">inputStream</param> <param name="bufferSize">${bufferSize}</param> <param name="contentDisposition">attachment;filename="${fileName}"</param> </result> <result name="zip" type="stream"> <param name="contentType">application/zip</param> <param name="inputName">inputStream</param> <<param name="bufferSize">${bufferSize}</param> <param name="contentDisposition">attachment;filename="data.zip"</param> </result> </action> </package> </struts> ``` 5. 编写一个压缩文件的工具类: ```java public class ZipUtils { public static void zipFiles(List<File> fileList, String zipFilePath) throws IOException { // 创建ZipOutputStream对象 ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath)); // 遍历文件列表并添加到zip文件中 for (File file : fileList) { // 创建ZipEntry对象 ZipEntry zipEntry = new ZipEntry(file.getName()); zipOutputStream.putNextEntry(zipEntry); // 读取文件并写入ZipOutputStream FileInputStream fileInputStream = new FileInputStream(file); byte[] buffer = new byte[1024]; int length = 0; while ((length = fileInputStream.read(buffer)) > 0) { zipOutputStream.write(buffer, 0, length); } // 关闭ZipEntry和FileInputStream zipOutputStream.closeEntry(); fileInputStream.close(); } // 关闭ZipOutputStream zipOutputStream.close(); } } ``` 6. 在DownloadAction类中调用ZipUtils类生成压缩包: ```java public class DownloadAction extends ActionSupport { private static final long serialVersionUID = 1L; private String fileName; private String contentType; private InputStream inputStream; private int bufferSize = 1024; public String execute() throws Exception { // 获取数据列表 List<Data> dataList = getDataList(); // 按照50000笔数据分批导出excel表格 List<File> fileList = new ArrayList<>(); int batchCount = (dataList.size() + 49999) / 50000; for (int i = 0; i < batchCount; i++) { int start = i * 50000; int end = Math.min(start + 50000, dataList.size()); List<Data> batchList = dataList.subList(start, end); // 生成excel表格并写入数据 Workbook workbook = createWorkbook(batchList); // 把excel表格写入文件 File file = new File("data_" + (i+1) + ".xls"); FileOutputStream fileOutputStream = new FileOutputStream(file); workbook.write(fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); // 把文件添加到文件列表中 fileList.add(file); } // 生成压缩包并赋值给inputStream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipUtils.zipFiles(fileList, baos); baos.flush(); baos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); inputStream = bais; // 设置文件名和Content-Type fileName = "data.zip"; contentType = "application/zip"; // 返回下载结果 return "zip"; } // 获取数据列表 private List<Data> getDataList() { // TODO: 获取数据列表的代码 return null; } // 生成excel表格 private Workbook createWorkbook(List<Data> dataList) { // TODO: 生成excel表格的代码 return null; } // Getters and Setters } ``` 这样就完成了导出千万级数据量、分批导入到excel表格、压缩多个excel表格为zip包、最后导出为一个压缩包的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值