POI模版列印

來源:互聯網
上載者:User

步驟: 製作模版檔案(模版檔案的路徑) 匯入(載入)模版檔案,從而得到一個活頁簿 讀取工作表 讀取行 讀取儲存格 讀取儲存格樣式 設定儲存格內容 其他儲存格就可以使用讀到的樣式了

package cn.xxxxxx.jk.action.cargo;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.util.List;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.CellRangeAddress;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.struts2.ServletActionContext;import cn.xxxxxx.jk.action.BaseAction;import cn.xxxxxx.jk.domain.ContractProduct;import cn.xxxxxx.jk.service.ContractProductService;import cn.xxxxxx.jk.util.DownloadUtil;import cn.xxxxxx.jk.util.UtilFuns;public class OutProductAction extends BaseAction {    //注入日期    private String inputDate;    public void setInputDate(String inputDate) {        this.inputDate = inputDate;    }    //注入Service    private ContractProductService contractProductService;    public void setContractProductService(ContractProductService contractProductService) {        this.contractProductService = contractProductService;    }    /**     * 進入出貨的表的列印頁面     */    public String toedit() throws Exception {        return "toedit";    }    /**     * 列印     */    public String print() throws Exception {        //1.建立活頁簿        String path = ServletActionContext.getServletContext().getRealPath("/");        path = path+"/make/xlsprint/tOUTPRODUCT.xls";   //得到模板檔案所在位置        InputStream is = new FileInputStream(path);     //根據檔案路徑,得到指定的檔案流        Workbook wb = new HSSFWorkbook(is);//根據檔案流,載入指定的活頁簿                        它只能操作excel2003版本        //2.讀取工作表        Sheet sheet = wb.getSheetAt(0);   //0代表工作表的下標        //抽取出一些公用變數        Row nRow=null;        Cell nCell = null;        int rowNo=0;//行號        int cellNo=1;//列號        //3.建立行對象        //==========================================大標題的製作        nRow = sheet.getRow(rowNo++);//讀取行對象        nCell = nRow.getCell(cellNo);//讀取儲存格        //設定儲存格的內容         nCell.setCellValue(inputDate.replace("-0", "-").replace("-", "年")+"月份出貨表");  //2015-10      2015-01----->2015-1----->2015年1        //============================================ 小標題        rowNo++;   //跳過第二行,進入第三行(rowNo=2)        //===========================================資料內容        //先將第三行的樣式讀取出來        nRow = sheet.getRow(rowNo);//讀取第三行        //客人    訂單號 貨號  數量  工廠  工廠交期    船期  貿易條款        CellStyle customerCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        String str = nRow.getCell(cellNo).getStringCellValue();//讀取儲存格的內容        System.out.println(str);        CellStyle orderNoCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        CellStyle productNoCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        CellStyle cNumberCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        CellStyle factoryCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        CellStyle deliveryPeriodCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        CellStyle shipTimeCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        CellStyle tradeTermsCellStyle = nRow.getCell(cellNo++).getCellStyle();//讀取儲存格的樣式        String hql = "from ContractProduct where to_char(contract.shipTime,'yyyy-MM') = '"+inputDate+"'";   //2015-01        List<ContractProduct> list = contractProductService.find(hql, ContractProduct.class, null);//載入指定船期下的貨物列表        //遍曆貨物列表        for(ContractProduct cp :list){            //產生一個新行            nRow = sheet.createRow(rowNo++);            nRow.setHeightInPoints(24f);//設定行高            cellNo=1;            //產生儲存格   客戶                nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getContract().getCustomName());//設定儲存格內容             nCell.setCellStyle(customerCellStyle);    //設定儲存格樣式            //產生儲存格訂單號            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getContract().getContractNo());//設定儲存格內容             nCell.setCellStyle(orderNoCellStyle);    //設定儲存格樣式            //產生儲存格貨號            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getProductNo());//設定儲存格內容             nCell.setCellStyle(productNoCellStyle);    //設定儲存格樣式            //產生儲存格數量            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getCnumber());//設定儲存格內容             nCell.setCellStyle(cNumberCellStyle);    //設定儲存格樣式            //產生儲存格工廠            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getFactoryName());//設定儲存格內容             nCell.setCellStyle(factoryCellStyle);    //設定儲存格樣式            //產生儲存格工廠交期             nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getDeliveryPeriod()));//設定儲存格內容             nCell.setCellStyle(deliveryPeriodCellStyle);    //設定儲存格樣式            //產生儲存格船期            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getShipTime()));//設定儲存格內容             nCell.setCellStyle(shipTimeCellStyle);    //設定儲存格樣式            //產生儲存格貿易條款            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getContract().getTradeTerms());//設定儲存格內容             nCell.setCellStyle(tradeTermsCellStyle);    //設定儲存格樣式        }        //輸出        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//記憶體的緩衝區        wb.write(byteArrayOutputStream);        //提供response對象        HttpServletResponse response = ServletActionContext.getResponse();        DownloadUtil downloadUtil = new DownloadUtil();        downloadUtil.download(byteArrayOutputStream, response, "出貨表.xls");        return NONE;    }    /***     * 沒有使用模板進行列印     * @return     * @throws Exception     */    public String printNotTemplate() throws Exception {        //1.建立活頁簿        Workbook wb = new HSSFWorkbook();//它只能操作excel2003版本        //2.建立工作表        Sheet sheet = wb.createSheet();        //設定列寬   本身就是bug        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);        //抽取出一些公用變數        Row nRow=null;        Cell nCell = null;        int rowNo=0;//行號        int cellNo=1;//列號        //3.建立行對象        //==========================================大標題的製作        nRow = sheet.createRow(rowNo++);//建立行對象        nRow.setHeightInPoints(36.26f);//設定行高        nCell = nRow.createCell(cellNo);        //設定儲存格的內容         nCell.setCellValue(inputDate.replace("-0", "-").replace("-", "年")+"月份出貨表");  //2015-10      2015-01----->2015-1----->2015年1        //設定儲存格樣式        nCell.setCellStyle(bigTitle(wb));        //合併儲存格        sheet.addMergedRegion(new CellRangeAddress(0,0,1,8));        //============================================ 小標題        nRow = sheet.createRow(rowNo++);//建立行對象        nRow.setHeightInPoints(26f);//設定行高        String titles [] = {"客戶","訂單號","貨號","數量","工廠","工廠交期","船期","貿易條款"};        for(String title :titles){            nCell = nRow.createCell(cellNo++);//建立小標題上的儲存格            nCell.setCellValue(title);//設定儲存格內容             nCell.setCellStyle(this.title(wb));//小標題樣式的設定        }        //===========================================資料內容        String hql = "from ContractProduct where to_char(contract.shipTime,'yyyy-MM-dd')  like '"+inputDate+"%'";   //2015-01%        List<ContractProduct> list = contractProductService.find(hql, ContractProduct.class, null);//載入指定船期下的貨物列表        //遍曆貨物列表        for(ContractProduct cp :list){            //產生一個新行            nRow = sheet.createRow(rowNo++);            nRow.setHeightInPoints(24f);//設定行高            cellNo=1;            //產生儲存格   客戶                nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getContract().getCustomName());//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格訂單號            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getContract().getContractNo());//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格貨號            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getProductNo());//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格數量            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getCnumber());//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格工廠            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getFactoryName());//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格工廠交期             nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getDeliveryPeriod()));//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格船期            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(UtilFuns.dateTimeFormat(cp.getContract().getShipTime()));//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式            //產生儲存格貿易條款            nCell = nRow.createCell(cellNo++);//建立儲存格            nCell.setCellValue(cp.getContract().getTradeTerms());//設定儲存格內容             nCell.setCellStyle(text(wb));    //設定儲存格樣式        }        //輸出        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//記憶體的緩衝區        wb.write(byteArrayOutputStream);        //提供response對象        HttpServletResponse response = ServletActionContext.getResponse();        DownloadUtil downloadUtil = new DownloadUtil();        downloadUtil.download(byteArrayOutputStream, response, "a.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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.