Java操作Excel之POI:excel導出文件


開發步驟:

                    * 1、創建一個工作簿

                    * 2、創建一個工作表

                    * 3、創建一個行對象

                    * 4、創建一個單元格對象,指定它的列

                    * 5、給單元格設置內容

                    * 6、樣式進行修飾(跳過)

                    * 7、保存,寫文件

                    * 8、關閉對象

1.基礎打印

public void testHSSF_base() throws IOException{
        
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        Row nRow = sheet.createRow(7);            //第八行
        Cell nCell = nRow.createCell(4);        //第五列
        
        nCell.setCellValue("demo演示案例");
        
        OutputStream os = new FileOutputStream("c:\\testpoi.xls");    
        wb.write(os);
        
        os.flush();
        os.close();
    }

 2.HSSF無模板打印

                                      (注:表格來自傑信物流SSM java課程案例上的表格)

public void printNotemplate(String inputDate) throws IOException{
        
        /*
         * POI實現excel打印
         * 1、大標題,合並單元格
         * 2、標題,修飾
         * 3、內容,修飾
         * 
         */ Workbook wb = new HSSFWorkbook();        //創建一個工作簿
        Sheet sheet = wb.createSheet();            //創建一個工作表
        Row nRow = null;
        Cell nCell = null;
        int rowNo = 0;                            //行號,默認從0開始
        int colNo = 1;                            //列號為1 是因為a列為了打印美觀空出來
        
        //創建樣式和字體對象
        CellStyle curStyle = wb.createCellStyle();
        Font curFont = wb.createFont();
        
        //設置列寬 256,BUG,精度不夠,總是差一點
        sheet.setColumnWidth(0, 1*278);                //第1列
        sheet.setColumnWidth(1, 26*278);            //第2列
                
        
        //處理大標題    sheet.addMergedRegion(new CellRangeAddress(開始行,結束行,開始列,結束列));
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 1, 8));        //合並單元格
        nRow = sheet.createRow(rowNo++);
        nRow.setHeightInPoints(36);//行高
        
        nCell = nRow.createCell(1);
        nCell.setCellStyle(bigTitleStyle(wb));
        
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出貨表");        //yyyy-MM  2019-05改為2019年5月份 2019-10改為2019年10月份
        
        //處理標題
        String[] title = new String[]{"客戶","訂單號","貨號","數量","工廠","工廠交期","船期","貿易條款"};    //標題數組
        nRow = sheet.createRow(rowNo++);
        nRow.setHeightInPoints(26);
        
        for(int i=0;i<title.length;i++){
            nCell = nRow.createCell(i+1);
            nCell.setCellValue(title[i]);
            nCell.setCellStyle(this.titleStyle(wb));
        }
        
        //處理內容
        List<OutProductVO> dataList = outProductService.find(inputDate);
        for(int j=0;j<dataList.size();j++){
            colNo = 1;                //初始化 逐行從第2列開始寫數據
            OutProductVO op = dataList.get(j);
            
            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(this.textStyle(wb, curStyle, curFont));
        }
        
        OutputStream os = new FileOutputStream("c:\\outproduct.xls");
        wb.write(os);
        
        os.flush();
        os.close();
    }
//大標題樣式
    private CellStyle bigTitleStyle(Workbook wb){
        //為了防止創建多個樣式和字體,並且只覆蓋最后一次設置的樣式和字體值,需要創建新對象
        CellStyle curStyle = wb.createCellStyle();
        Font curFont = wb.createFont();
        
        curFont.setFontName("宋體");
        curFont.setFontHeightInPoints((short)16);
        curFont.setBoldweight(Font.BOLDWEIGHT_BOLD);                    //字體加粗
        
        curStyle.setFont(curFont);                                        //綁定字體
        
        curStyle.setAlignment(CellStyle.ALIGN_CENTER);                    //橫向居中
        curStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //縱向居中
        
        return curStyle;
    }
    
    //小標題樣式
    private CellStyle titleStyle(Workbook wb){
        CellStyle curStyle = wb.createCellStyle();
        Font curFont = wb.createFont();
        
        curFont.setFontName("黑體");
        curFont.setFontHeightInPoints((short)12);
        
        curStyle.setFont(curFont);                                        //綁定字體
        
        curStyle.setAlignment(CellStyle.ALIGN_CENTER);                    //橫向居中
        curStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //縱向居中
        
        
        curStyle.setBorderTop(CellStyle.BORDER_THIN);                    //設置四周邊線,細線
        curStyle.setBorderBottom(CellStyle.BORDER_THIN);
        curStyle.setBorderLeft(CellStyle.BORDER_THIN);
        curStyle.setBorderRight(CellStyle.BORDER_THIN);
        
        return curStyle;
    }
    
    //文字樣式
    private CellStyle textStyle(Workbook wb, CellStyle curStyle, Font curFont){
        
        curFont.setFontName("Times New Roman");
        curFont.setFontHeightInPoints((short)10);
        
        curStyle.setFont(curFont);                                        //綁定字體
        
        curStyle.setAlignment(CellStyle.ALIGN_LEFT);                    //橫向居左
        curStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //縱向居中
        
        
        curStyle.setBorderTop(CellStyle.BORDER_THIN);                    //設置四周邊線,細線
        curStyle.setBorderBottom(CellStyle.BORDER_THIN);
        curStyle.setBorderLeft(CellStyle.BORDER_THIN);
        curStyle.setBorderRight(CellStyle.BORDER_THIN);
        
        return curStyle;
    }

 3.HSSF含模板打印

public void printHSSF(String inputDate, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //linux下jdk1.8 方法獲取時,不會拼接自己寫的目錄 
        String path = request.getSession().getServletContext().getRealPath("/") + "/make/xlsprint/";
        InputStream is = new FileInputStream(new File(path + "tOUTPRODUCT.xls"));
        
        Workbook wb = new HSSFWorkbook(is);        //打開一個模板文件,工作簿
        Sheet sheet = wb.getSheetAt(0);            //獲取到第一個工作表
        
        Row nRow = null;
        Cell nCell = null;
        int rowNo = 0;                            //行號
        int colNo = 1;                            //列號
        
        //獲取模板上的單元格樣式
        nRow = sheet.getRow(2);
        
        //客戶的樣式
        nCell = nRow.getCell(1);
        CellStyle customStyle = nCell.getCellStyle();        
        
        //訂單號的樣式
        nCell = nRow.getCell(2);
        CellStyle contractNoStyle = nCell.getCellStyle();        
        
        //貨號的樣式
        nCell = nRow.getCell(3);
        CellStyle productNoStyle = nCell.getCellStyle();        
        
        //數量的樣式
        nCell = nRow.getCell(4);
        CellStyle numStyle = nCell.getCellStyle();        
        
        //生產廠家的樣式
        nCell = nRow.getCell(5);
        CellStyle factoryStyle = nCell.getCellStyle();        
        
        //日期的樣式
        nCell = nRow.getCell(6);
        CellStyle dateStyle = nCell.getCellStyle();        
        
        //貿易條款的樣式
        nCell = nRow.getCell(8);
        CellStyle tradeStyle = nCell.getCellStyle();        
                
        
        //處理大標題
        nRow = sheet.getRow(rowNo++);            //獲取一個行對象
        nCell = nRow.getCell(colNo);            //獲取一個單元格對象
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出貨表");        //yyyy-MM
        
        rowNo++;                                //跳過靜態表格頭
        
        //處理內容
        List<OutProductVO> dataList = outProductService.find(inputDate);
        for(int j=0;j<dataList.size();j++){
            colNo = 1;                //初始化
            OutProductVO op = dataList.get(j);
            
            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(customStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(contractNoStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(productNoStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(numStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(factoryStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(dateStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(dateStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(tradeStyle);
        }
        
//        OutputStream os = new FileOutputStream("c:\\outproduct.xls");
//        wb.write(os);
//        
//        os.flush();
//        os.close();
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        
        DownloadUtil downloadUtil = new DownloadUtil();                //直接彈出下載框,用戶可以打開,可以保存
        downloadUtil.download(os, response, "出貨表.xls");
        
        os.flush();
        os.close();
    }

4.XSSF打印

@RequestMapping("/cargo/outproduct/print.action")
    public void print(String inputDate, HttpServletRequest request, HttpServletResponse response) throws IOException{
        //linux下jdk1.8 方法獲取時,不會拼接自己寫的目錄 
        String path = request.getSession().getServletContext().getRealPath("/") + "/make/xlsprint/";
        InputStream is = new FileInputStream(new File(path + "tOUTPRODUCT.xlsx"));
        
        Workbook wb = new XSSFWorkbook(is);        //打開一個模板文件,工作簿 2007以上版本
        Sheet sheet = wb.getSheetAt(0);            //獲取到第一個工作表
        
        Row nRow = null;
        Cell nCell = null;
        int rowNo = 0;                            //行號
        int colNo = 1;                            //列號
        
        //獲取模板上的單元格樣式
        nRow = sheet.getRow(2);
        
        //客戶的樣式
        nCell = nRow.getCell(1);
        CellStyle customStyle = nCell.getCellStyle();        
        
        //訂單號的樣式
        nCell = nRow.getCell(2);
        CellStyle contractNoStyle = nCell.getCellStyle();        
        
        //貨號的樣式
        nCell = nRow.getCell(3);
        CellStyle productNoStyle = nCell.getCellStyle();        
        
        //數量的樣式
        nCell = nRow.getCell(4);
        CellStyle numStyle = nCell.getCellStyle();        
        
        //生產廠家的樣式
        nCell = nRow.getCell(5);
        CellStyle factoryStyle = nCell.getCellStyle();        
        
        //日期的樣式
        nCell = nRow.getCell(6);
        CellStyle dateStyle = nCell.getCellStyle();        
        
        //貿易條款的樣式
        nCell = nRow.getCell(8);
        CellStyle tradeStyle = nCell.getCellStyle();        
        
        
        //處理大標題
        nRow = sheet.getRow(rowNo++);            //獲取一個行對象
        nCell = nRow.getCell(colNo);            //獲取一個單元格對象
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出貨表");        //yyyy-MM
        
        rowNo++;                                //跳過靜態表格頭
        
        //處理內容
        List<OutProductVO> dataList = outProductService.find(inputDate);
        for(int j=0;j<dataList.size();j++){
            colNo = 1;                //初始化
            OutProductVO op = dataList.get(j);
            
            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(customStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(contractNoStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(productNoStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(numStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(factoryStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(dateStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(dateStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(tradeStyle);
        }
        
//        OutputStream os = new FileOutputStream("c:\\outproduct.xls");
//        wb.write(os);
//        
//        os.flush();
//        os.close();
        
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        
        DownloadUtil downloadUtil = new DownloadUtil();                //直接彈出下載框,用戶可以打開,可以保存
        downloadUtil.download(os, response, "出貨表.xlsx");
        
        os.flush();
        os.close();
    }

5.小結

HSSF 比較多,兼顧客戶的環境,針對excel2003

XSSF 應用比較少,當數據量比較大時,才采用,針對excel2007及以上

SXSSF 只用在海量數據的導出,且不支持模板導出


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM