struts2中excel下载的两种方式,同样使用于文件下载

一、直接通过response下载

1.页面请求

window.location.href = CONTEXT_PATH + '/exportWmOrder.do'+url;

2.struts中配置文件定义

        <!-- 网上订单详情 -->
        <action name="*WmOrder" class="WmOrderAction" method="{1}">
            <result type="json">
                <param name="root">jsonData</param>
            </result>
        </action>

3.action中的方法

    public void export() throws UnsupportedEncodingException {
        productName =  java.net.URLDecoder.decode(productName, "UTF-8");
        receiverName =  java.net.URLDecoder.decode(receiverName, "UTF-8");
        receiverAddress =  java.net.URLDecoder.decode(receiverAddress, "UTF-8");
        
        ServletContext sc = ServletActionContext.getServletContext();
        String modelPath = sc.getRealPath("WEB-INF\\app\\base\\model");
        String templatefile = modelPath + "\\ddxx.xls"; //
        String filename = sc.getRealPath("chartTemp") + "\\订单详细信息.xls"; // 临时文件
        try {
            Workbook workbook = Workbook.getWorkbook(new File(templatefile));
            WritableWorkbook copy = Workbook.createWorkbook(new File(filename),workbook);
            WritableSheet sheet1 = copy.getSheet(0);
            
            // 设置字体
            WritableFont font1 = new WritableFont(WritableFont.TIMES, 12);
            WritableCellFormat format1 = new WritableCellFormat(font1);
            format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            format1.setAlignment(jxl.format.Alignment.LEFT);
            format1.setBorder(jxl.format.Border.TOP,jxl.format.BorderLineStyle.THIN);
            format1.setBorder(jxl.format.Border.BOTTOM,jxl.format.BorderLineStyle.THIN);
            format1.setBorder(jxl.format.Border.LEFT,jxl.format.BorderLineStyle.THIN);
            format1.setBorder(jxl.format.Border.RIGHT,jxl.format.BorderLineStyle.THIN);
            
            List<HashMap<String, String>> list1 = new ArrayList<HashMap<String,String>>();
            HashMap<String, Object> params = new HashMap<String, Object>();
            IBaseService service = getService();
            list1 = service.queryListBySql("order.queryWmGoodsOrderByExcel",params);
            
            // 写入数据
            for (int i = 0; i < list1.size(); i++) {
                sheet1.addCell(new Label(0, i+2, list1.get(i).get("receiverProvince"), format1));//订单汇总单号ID
                sheet1.addCell(new Label(1, i+2, list1.get(i).get("orderId"), format1));//订单ID
                sheet1.addCell(new Label(2, i+2, list1.get(i).get("orderStatus"), format1));//订单状态
                sheet1.addCell(new Label(3, i+2, list1.get(i).get("returnId"), format1));//是否退单
                sheet1.addCell(new Label(4, i+2, list1.get(i).get("sendPerson"), format1));//发货人
                sheet1.addCell(new Label(5, i+2, list1.get(i).get("productName"), format1));//商品名称
                sheet1.addCell(new Label(6, i+2, list1.get(i).get("productCode"), format1));//商品条码
                sheet1.addCell(new Label(7, i+2, list1.get(i).get("productSku"), format1));//商品规格
                sheet1.addCell(new Label(8, i+2, list1.get(i).get("productCount"), format1));//商品数

            }
            copy.write();
            copy.close();
            downExcel(filename); // 下载文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        /**
     * 下载文件
     * @param filename
     * @throws IOException
     * @throws ServletException
     */
    @SuppressWarnings("unused")
    private void downExcel(String filename) throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        if (filename == null || ("").equals(filename)) {
            try {
            } catch (Exception e) {
                System.out.println("系统忙。。。稍后再试" + e.toString());
            }
        } else {
            // 文件名称
            String name = filename.substring(filename.lastIndexOf("\\") + 1);
            InputStream inputStream = new FileInputStream(filename);
            OutputStream outputStream = response.getOutputStream();
            try {
                // 判断文件是否存在
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition","attachment;filename="+ new String(name.getBytes(), "ISO8859-1"));
                byte[] buffer = new byte[1024];
                int i = -1;
                while ((i = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, i);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                new File(filename).delete(); // 删除文件
            }
        }
    }

二、通过struts2配置进行下载

此方法摘自 https://blog.csdn.net/zht666/article/details/11091505

1.struts配置

<struts>
    <package name="export" namespace="/export" extends="struts-default">
        <action name="*" class="excelExportAction" method="{1}"/>
 
        <!--测试Excel下载-->
        <action name="exportExcel" class="excelExportAction" method="exportExcel">
            <result name="success" type="stream">
                <!-- 下载文件的类型,如果你不知道是什么格式,可以去 tomcat\conf\web.xml下找 -->
                <param name="contentType">application/vnd.ms-excel</param>
                <!-- 返回流 excelStream为action中的流变量名称 -->
                <param name="inputName">excelStream</param>
                <!-- attachment 这个位置的参数挺特殊的,可以设置成下载时,是否出现个下载提示框,或者直接下载之类的。
                fileName指定生成的文件名字(适合动态生成文件名,比如做报表时,一般都要说是几月的统计数据之类)为action中变量-->
                <param name="contentDisposition">attachment;filename=${excelFileName}</param>
                <param name="bufferSize">1024</param>
            </result>
        </action>
    </package>
</struts>

 

2.action类

import org.apache.poi.hssf.usermodel.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class ExcelExportAction extends ActionSupport {
 
    /** 导出Excel测试 */
    public String exportExcel() {
        try {
            //第一步,创建一个webbook,对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            //第二步,在webbook中添加一个sheet,对应Excel文件中的 sheet
            HSSFSheet sheet = wb.createSheet("测试表格1");
            //第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
            HSSFRow row = sheet.createRow(0);
            //第四步,创建单元格样式:居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //第五步,创建表头单元格,并设置样式
            HSSFCell cell;
 
            cell = row.createCell(0);
            cell.setCellValue("员工工号");
            cell.setCellStyle(style);
 
            cell = row.createCell(1);
            cell.setCellValue("员工姓名");
            cell.setCellStyle(style);
 
            cell = row.createCell(2);
            cell.setCellValue("所属部门");
            cell.setCellStyle(style);
 
            cell = row.createCell(3);
            cell.setCellValue("职位");
            cell.setCellStyle(style);
 
            cell = row.createCell(4);
            cell.setCellValue("入职日期");
            cell.setCellStyle(style);
 
            cell = row.createCell(5);
            cell.setCellValue("备注");
            cell.setCellStyle(style);
 
            //第六步,写入实体数据,实际应用中这些数据从数据库得到
            Date today = new Date();
            long aDay = 1000L*60*60*24;
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 1; i <= 10; i++) {
                row = sheet.createRow(i);
                row.createCell(0).setCellValue(i);
                row.createCell(1).setCellValue("员工" + i);
                row.createCell(2).setCellValue("总公司");
                row.createCell(3).setCellValue("普通员工");
                row.createCell(4).setCellValue(fmt.format(new Date(today.getTime() + i * aDay)));
                row.createCell(5).setCellValue("员工备注");
            }
 
            //第七步,将文件存到流中
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            byte[] fileContent = os.toByteArray();
            ByteArrayInputStream is = new ByteArrayInputStream(fileContent);
 
            excelStream = is;             //文件流
            excelFileName = "report.xls"; //设置下载的文件名
        }
        catch(Exception e) {
            e.printStackTrace();
        }
 
        return "success";
    }
 
 
    //-------------------------------------------------------------
    private InputStream excelStream;  //输出流变量
    private String excelFileName; //下载文件名
 
    public InputStream getExcelStream() {
        return excelStream;
    }
    public void setExcelStream(InputStream excelStream) {
        this.excelStream = excelStream;
    }
    public String getExcelFileName() {
        return excelFileName;
    }
    public void setExcelFileName(String excelFileName) {
        this.excelFileName = excelFileName;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值