struts2-POI模板打印

    package cn.itcast.web.action.cargo;


    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.List;

    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellStyle;
    import org.apache.poi.ss.usermodel.Font;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.apache.struts2.ServletActionContext;
    import org.apache.struts2.convention.annotation.Action;
    import org.apache.struts2.convention.annotation.Namespace;
    import org.apache.struts2.convention.annotation.ParentPackage;
    import org.apache.struts2.convention.annotation.Result;
    import org.apache.struts2.convention.annotation.Results;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Controller;

    import cn.itcast.domain.ContractProduct;
    import cn.itcast.service.IContractProductService;
    import cn.itcast.utils.DownloadUtil;
    import cn.itcast.web.action.BaseAction;
    /**
     *
     * <p>Title: OutProductAction</p>
     * <p>Description:出货表打印的动作类</p>
     *
     * @Company: http://www.itheima.com
     * @author: zhy
     * @Date: 2017年9月24日
     */
    @Controller("outProductAction")
    @Scope("prototype")
    @ParentPackage("myDefault")
    @Namespace("/cargo")
    @Results({
        @Result(name="toedit",type="dispatcher",location="/WEB-INF/pages/cargo/outproduct/jOutProduct.jsp")
    })
    public class OutProductAction extends BaseAction {
        
        @Autowired
        private IContractProductService contractProductService;
        
        private String inputDate;
        
        public String getInputDate() {
            return inputDate;
        }
        public void setInputDate(String inputDate) {
            this.inputDate = inputDate;
        }

        
        /**
         * 前往出货表打印页面
         * @return
         */
        @Action("outProductAction_toedit")
        public String toedit(){
            return "toedit";
        }
        
        /**
         * HSSFWorkbook:只支持excel2003,当数据行超过65536之后,他就不能用了。支持模板打印
         * XSSFWorkbook:只支持excel2007及以上,但是如果我们保存成xls文件,也可以打开。它支持的数据行是104万。支持模板打印
         * SXSSFWorkbook:只能作用于excle2007及以上,但是它不能使用模板打印。它支持百万级数据POI导出。该对象只有Poi版本在3.0以上才有。
        
        @Action("outProductAction_print")
        public String print()throws Exception{
            //1.创建工作簿
            //构造函数支持传入一个int类型的参数,该参数的含义是只当内存中创建多少个对象之后,把内存对象转存到硬盘上。
            Workbook wb = new SXSSFWorkbook(100);//默认值是100
            //2.创建工作表
            Sheet sheet = wb.createSheet();
            //3.定义可以复用变量
            int rowNum = 0;
            int cellNum = 1;
            Row nRow = null;
            Cell nCell = null;
            //4.设置列宽
            sheet.setColumnWidth(0, 3*256);
            sheet.setColumnWidth(1, 26*256);
            sheet.setColumnWidth(2, 11*256);
            sheet.setColumnWidth(3, 29*256);
            sheet.setColumnWidth(4, 12*256);
            sheet.setColumnWidth(5, 15*256);
            sheet.setColumnWidth(6, 10*256);
            sheet.setColumnWidth(7, 10*256);
            sheet.setColumnWidth(8, 8*256);
            //5.创建第一行
            nRow = sheet.createRow(rowNum++);//得到的是第一行,索引已经变成了第二行
            //6.设置行高
            nRow.setHeightInPoints(36f);
            //7.合并单元格
            sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));//横向合并单元格
            //8.创建单元格,设置单元格样式和内容
            nCell = nRow.createCell(cellNum);
            String bigTitle = inputDate.replace("-0", "-").replace("-", "年")+"月份出货表";
            nCell.setCellValue(bigTitle);//2015-07  2015-7  2015年07月   
            nCell.setCellStyle(this.bigTitle(wb));
            //9.创建第二行
            nRow = sheet.createRow(rowNum++);//得到的是第二行,索引已经变成了第三行
            nRow.setHeightInPoints(26.25f);//设置行高
            //10.创建小标题的单元格,并设置内容和样式
            String[] titles = new String[]{"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
            for(String title : titles){
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.title(wb));
                nCell.setCellValue(title);
            }
            //11.接下来就是准备数据行的数据
            //from ContractProduct where contract.id in (select id from Contract where to_char(ship_time,'yyyy-MM') = '2015-01')
            String hql = "from ContractProduct where  to_char(contract.shipTime,'yyyy-MM') = ? ";
            List<ContractProduct> cps = contractProductService.find(hql, ContractProduct.class, new Object[]{inputDate});
            //12.遍历结果集,生成数据行和数据单元格
            for(ContractProduct cp : cps){
                for(int i=0;i<2000;i++){
                //创建数据行
                nRow = sheet.createRow(rowNum++);
                //设置行高
                nRow.setHeightInPoints(24f);
                //先重置单元格的索引为1
                cellNum = 1;
                //创建数据单元格(一共8个)
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getCustomName());//"客户"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getContractNo());//"订单号"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getProductNo());//"货号"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getCnumber());//"数量"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getFactoryName());//"工厂"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getDeliveryPeriod());//"工厂交期"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getShipTime());//"船期"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getTradeTerms());//"贸易条款"
                }
            }
            //13.把已经写好的内容生成excel并下载
            DownloadUtil downloadutil = new DownloadUtil();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();//创建对象
            wb.write(baos);//给baos里面写内容
            downloadutil.download(baos, ServletActionContext.getResponse(), bigTitle+".xls");
            return NONE;
        } */
        
        /**
         * 模板打印的思路:
         *      创建工作簿时,不能在直接new,而是要读取模板
         *  大标题我们只需要设置内容,因为每次的打印月份不一样,而不需要再设置行高,设置样式。
         *  小标题行,我们什么都不需要做。所以跳过第二行(下标为1的那行)
         *  读取第三行,取出第三行每个单元格的样式。在生成数据行的时候,每个数据单元格都要使用对应的样式
         */
        @Action("outProductAction_print")
        public String print()throws Exception{
            //1.读取模板文件,构建字节输入流
            String filePath = ServletActionContext.getServletContext().getRealPath("/make/xlsprint/tOUTPRODUCT.xlsx");
            InputStream in = new FileInputStream(filePath);
            //2.根据字节输入流读取模板工作簿
            Workbook wb = new XSSFWorkbook(in);
            //3.读取有模板的工作表,第一张工作表
            Sheet sheet = wb.getSheetAt(0);
            //4.定义可以复用变量
            int rowNum = 0;
            int cellNum = 1;
            Row nRow = null;
            Cell nCell = null;
            //5.读取第一行
            nRow = sheet.getRow(rowNum++);//取出的nRow是第一行,下标为0.同时下标从0变成1,再次获取时是第二行
            //6.读取单元格,设置内容
            nCell = nRow.getCell(cellNum);
            String bigTitle = inputDate.replace("-0", "-").replace("-", "年")+"月份出货表";
            nCell.setCellValue(bigTitle);  
            //7.让行的下标再次往下走一个,跳过第二行
            rowNum++;//让下标再次往下走,我们再使用rowNum获取时,已经是第三行
            //8.取出第三行的样式
            nRow = sheet.getRow(rowNum);
            CellStyle c1 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c2 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c3 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c4 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c5 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c6 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c7 = nRow.getCell(cellNum++).getCellStyle();
            CellStyle c8 = nRow.getCell(cellNum++).getCellStyle();
            //9.接下来就是准备数据行的数据
            String hql = "from ContractProduct where  to_char(contract.shipTime,'yyyy-MM') = ? ";
            List<ContractProduct> cps = contractProductService.find(hql, ContractProduct.class, new Object[]{inputDate});
            //10.遍历结果集,生成数据行和数据单元格
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            for(ContractProduct cp : cps){
                //创建数据行
                nRow = sheet.createRow(rowNum++);
                //设置行高
                nRow.setHeightInPoints(24f);
                //先重置单元格的索引为1
                cellNum = 1;
                //创建数据单元格(一共8个)
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c1);
                nCell.setCellValue(cp.getContract().getCustomName());//"客户"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c2);
                nCell.setCellValue(cp.getContract().getContractNo());//"订单号"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c3);
                nCell.setCellValue(cp.getProductNo());//"货号"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c4);
                nCell.setCellValue(cp.getCnumber());//"数量"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c5);
                nCell.setCellValue(cp.getFactoryName());//"工厂"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c6);
                nCell.setCellValue(df.format(cp.getContract().getDeliveryPeriod()));//"工厂交期"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c7);
                nCell.setCellValue(df.format(cp.getContract().getShipTime()));//"船期"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(c8);
                nCell.setCellValue(cp.getContract().getTradeTerms());//"贸易条款"
            }
            //11.把已经写好的内容生成excel并下载
            DownloadUtil downloadutil = new DownloadUtil();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();//创建对象
            wb.write(baos);//给baos里面写内容
            downloadutil.download(baos, ServletActionContext.getResponse(), bigTitle+".xlsx");
            return NONE;
        }
        
        /**
         * 打印出货表,未使用模板打印
         * @return
         * @throws Exception
        
        @Action("outProductAction_print")
        public String print()throws Exception{
            //1.创建工作簿
            Workbook wb = new HSSFWorkbook();
            //2.创建工作表
            Sheet sheet = wb.createSheet();
            //3.定义可以复用变量
            int rowNum = 0;
            int cellNum = 1;
            Row nRow = null;
            Cell nCell = null;
            //4.设置列宽
            sheet.setColumnWidth(0, 3*256);
            sheet.setColumnWidth(1, 26*256);
            sheet.setColumnWidth(2, 11*256);
            sheet.setColumnWidth(3, 29*256);
            sheet.setColumnWidth(4, 12*256);
            sheet.setColumnWidth(5, 15*256);
            sheet.setColumnWidth(6, 10*256);
            sheet.setColumnWidth(7, 10*256);
            sheet.setColumnWidth(8, 8*256);
            //5.创建第一行
            nRow = sheet.createRow(rowNum++);//得到的是第一行,索引已经变成了第二行
            //6.设置行高
            nRow.setHeightInPoints(36f);
            //7.合并单元格
            sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));//横向合并单元格
            //8.创建单元格,设置单元格样式和内容
            nCell = nRow.createCell(cellNum);
            String bigTitle = inputDate.replace("-0", "-").replace("-", "年")+"月份出货表";
            nCell.setCellValue(bigTitle);//2015-07  2015-7  2015年07月   
            nCell.setCellStyle(this.bigTitle(wb));
            //9.创建第二行
            nRow = sheet.createRow(rowNum++);//得到的是第二行,索引已经变成了第三行
            nRow.setHeightInPoints(26.25f);//设置行高
            //10.创建小标题的单元格,并设置内容和样式
            String[] titles = new String[]{"客户","订单号","货号","数量","工厂","工厂交期","船期","贸易条款"};
            for(String title : titles){
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.title(wb));
                nCell.setCellValue(title);
            }
            //11.接下来就是准备数据行的数据
            //from ContractProduct where contract.id in (select id from Contract where to_char(ship_time,'yyyy-MM') = '2015-01')
            String hql = "from ContractProduct where  to_char(contract.shipTime,'yyyy-MM') = ? ";
            List<ContractProduct> cps = contractProductService.find(hql, ContractProduct.class, new Object[]{inputDate});
            //12.遍历结果集,生成数据行和数据单元格
            for(ContractProduct cp : cps){
                //创建数据行
                nRow = sheet.createRow(rowNum++);
                //设置行高
                nRow.setHeightInPoints(24f);
                //先重置单元格的索引为1
                cellNum = 1;
                //创建数据单元格(一共8个)
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getCustomName());//"客户"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getContractNo());//"订单号"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getProductNo());//"货号"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getCnumber());//"数量"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getFactoryName());//"工厂"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getDeliveryPeriod());//"工厂交期"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getShipTime());//"船期"
                
                nCell = nRow.createCell(cellNum++);
                nCell.setCellStyle(this.text(wb));
                nCell.setCellValue(cp.getContract().getTradeTerms());//"贸易条款"
            }
            //13.把已经写好的内容生成excel并下载
            DownloadUtil downloadutil = new DownloadUtil();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();//创建对象
            wb.write(baos);//给baos里面写内容
            downloadutil.download(baos, ServletActionContext.getResponse(), bigTitle+".xls");
            return NONE;
        }*/
        
        
        
        
        //大标题的样式
        public CellStyle bigTitle(Workbook wb){
            CellStyle style = wb.createCellStyle();
            Font font = wb.createFont();
            font.setFontName("宋体");
            font.setFontHeightInPoints((short)16);
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);                    //字体加粗
            
            style.setFont(font);
            
            style.setAlignment(CellStyle.ALIGN_CENTER);                    //横向居中
            style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //纵向居中
            
            return style;
        }
        //小标题的样式
        public CellStyle title(Workbook wb){
            CellStyle style = wb.createCellStyle();
            Font font = wb.createFont();
            font.setFontName("黑体");
            font.setFontHeightInPoints((short)12);
            
            style.setFont(font);
            
            style.setAlignment(CellStyle.ALIGN_CENTER);                    //横向居中
            style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //纵向居中
            
            style.setBorderTop(CellStyle.BORDER_THIN);                    //上细线
            style.setBorderBottom(CellStyle.BORDER_THIN);                //下细线
            style.setBorderLeft(CellStyle.BORDER_THIN);                    //左细线
            style.setBorderRight(CellStyle.BORDER_THIN);                //右细线
            
            return style;
        }
        
        //文字样式
        public CellStyle text(Workbook wb){
            CellStyle style = wb.createCellStyle();
            Font font = wb.createFont();
            font.setFontName("Times New Roman");
            font.setFontHeightInPoints((short)10);
            
            style.setFont(font);
            
            style.setAlignment(CellStyle.ALIGN_LEFT);                    //横向居左
            style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //纵向居中
            
            style.setBorderTop(CellStyle.BORDER_THIN);                    //上细线
            style.setBorderBottom(CellStyle.BORDER_THIN);                //下细线
            style.setBorderLeft(CellStyle.BORDER_THIN);                    //左细线
            style.setBorderRight(CellStyle.BORDER_THIN);                //右细线
            
            return style;
        }
    }

***********************************************

猜你喜欢

转载自blog.csdn.net/chai1230/article/details/82085722