POI操作excel表格代碼

package cn.itcast.jk.controller.cargo.outproduct;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFFont;
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.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.itcast.jk.controller.BaseController;
import cn.itcast.jk.service.OutProductService;
import cn.itcast.jk.vo.OutProductVO;
import cn.itcast.util.DownloadUtil;

@Controller
public class OutProductController extends BaseController {
    @Resource
    OutProductService outProductService;
    
    //轉向輸入年月的頁面
    @RequestMapping("/cargo/outproduct/toedit.action")
    public String toedit(){
        return "/cargo/outproduct/jOutProduct.jsp";
    }
    
    //模板打印
    @RequestMapping("/cargo/outproduct/printTemplate.action")
    public void printTemplate(String inputDate, HttpServletRequest request, HttpServletResponse response) throws IOException{
        List<OutProductVO> dataList = outProductService.find(inputDate);
        
        //打開模板文件
        String path = request.getSession().getServletContext().getRealPath("/");        //jdk1.8 bug 在linux下不帶後面你寫的路徑
        String tempFile = path + "/make/xlsprint/tOUTPRODUCT.xlsx";
        Workbook wb = new XSSFWorkbook(new FileInputStream(new File(tempFile)));
        
        //寫入業務內容
        Sheet sheet = wb.getSheetAt(0);        //獲得工作表sheet
        Row nRow = null;
        Cell nCell = null;
        int rowNo = 2;
        int colNo = 1;
        
        //獲取樣式
        nRow = sheet.getRow(2);                                    //獲得行對象
        nCell = nRow.getCell(1);                                //獲取單元格對象
        CellStyle customNameStyle = nCell.getCellStyle();        //獲取到樣式
        
        nCell = nRow.getCell(2);
        CellStyle contractNoStyle = nCell.getCellStyle();
        
        nCell = nRow.getCell(3);
        CellStyle productNoStyle = nCell.getCellStyle();
        
        nCell = nRow.getCell(4);
        CellStyle cnumberStyle = nCell.getCellStyle();
        
        nCell = nRow.getCell(5);
        CellStyle factoryStyle = nCell.getCellStyle();
        
        nCell = nRow.getCell(6);
        CellStyle extStyle = nCell.getCellStyle();
        
        nCell = nRow.getCell(7);
        CellStyle dateStyle = nCell.getCellStyle();
        
        nCell = nRow.getCell(9);
        CellStyle tradeStyle = nCell.getCellStyle();
        
        //大標題
        nRow = sheet.getRow(0);
        nCell = nRow.getCell(1);
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出貨表");            //yyyy-MM

        //處理數據
        for(int x=0;x<800;x++){
            
        for(int j=0;j<dataList.size();j++){
            System.out.println(rowNo);
            
            colNo = 1;                                //列號初始化
            OutProductVO op = dataList.get(j);        //獲取出貨表對象
            
            nRow = sheet.createRow(rowNo++);
            nRow.setHeightInPoints(24);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCustomName());
            nCell.setCellStyle(customNameStyle);    //設置樣式
            
            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(cnumberStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(factoryStyle);
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getExts());
            nCell.setCellStyle(extStyle);
            
            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);
        }
        }
        
        //下載
        DownloadUtil du = new DownloadUtil();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        du.download(os, response, "出貨表.xlsx");
    }
    
    @RequestMapping("/cargo/outproduct/print.action")
    public void print(String inputDate, HttpServletResponse response) throws IOException{        //inputDate 格式:yyyy-MM
        
        List<OutProductVO> dataList = outProductService.find(inputDate);
        
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        Row nRow = null;
        Cell nCell = null;
        
        int rowNo = 0;                //行號
        int colNo = 1;                //列號
        
        //聲明樣式對象和字體對象
        CellStyle nStyle = wb.createCellStyle();
        Font nFont = wb.createFont();
        
        sheet.setColumnWidth(0, 2*272);        //列寬
        sheet.setColumnWidth(1, 26*272);    //列寬 BUG,API底層設置不夠精確 256;272近似
        sheet.setColumnWidth(2, 12*272);
        sheet.setColumnWidth(3, 29*272);
        sheet.setColumnWidth(4, 10*272);
        sheet.setColumnWidth(5, 12*272);
        sheet.setColumnWidth(6, 8*272);
        sheet.setColumnWidth(7, 10*272);
        sheet.setColumnWidth(8, 10*272);
        sheet.setColumnWidth(9, 8*272);
        
        
        //大標題,合併單元格
        sheet.addMergedRegion(new CellRangeAddress(0,0,1,9));        //開始行,結束行,開始列,結束列
        //合併單元格的內容是寫在合併前第一個單元格中
        nRow = sheet.createRow(rowNo++);
        nRow.setHeightInPoints(36);                    //行高
        
        nCell = nRow.createCell(1);
        nCell.setCellValue(inputDate.replaceFirst("-0", "-").replaceFirst("-", "年") + "月份出貨表");            //yyyy-MM
        nCell.setCellStyle(this.bigTitle(wb, nStyle, nFont));
                                        
        String[] title = new String[]{"客戶","訂單號","貨號","數量","工廠","附件","工廠交期","船期","貿易條款"};
        
        nRow = sheet.createRow(rowNo++);
        nRow.setHeightInPoints(26.25f);
        
        //初始化
        nStyle = wb.createCellStyle();
        nFont = wb.createFont();
        
        for(int i=0;i<title.length;i++){
            nCell = nRow.createCell(i+1);
            nCell.setCellValue(title[i]);
            nCell.setCellStyle(this.title(wb, nStyle, nFont));
        }

        //初始化
        nStyle = wb.createCellStyle();
        nFont = wb.createFont();
        
        //處理數據
        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(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getContractNo());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getProductNo());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getCnumber());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getFactoryName());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getExts());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getDeliveryPeriod());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getShipTime());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
            
            nCell = nRow.createCell(colNo++);
            nCell.setCellValue(op.getTradeTerms());
            nCell.setCellStyle(this.text(wb, nStyle, nFont));
        }

        
        //OutputStream os = new FileOutputStream(new File("c:\\outproduct.xls"));
        //wb.write(os);
        //os.flush();
        //os.close();
        
        //下載
        DownloadUtil du = new DownloadUtil();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        du.download(os, response, "出貨表.xls");
    }
    
    //大標題樣式
    public CellStyle bigTitle(Workbook wb, CellStyle nStyle, Font nFont){
        nFont.setFontName("宋體");
        nFont.setFontHeightInPoints((short)16);
        nFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);                //字體加粗
        
        nStyle.setAlignment(CellStyle.ALIGN_CENTER);                //橫向居中
        nStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //縱向居中
        
        nStyle.setFont(nFont);
        
        return nStyle;
    }
    
    //標題樣式
    public CellStyle title(Workbook wb, CellStyle nStyle, Font nFont){
        nFont.setFontName("黑體");
        nFont.setFontHeightInPoints((short)12);
        
        nStyle.setAlignment(CellStyle.ALIGN_CENTER);                //橫向居中
        nStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //縱向居中
        
        //表格線
        nStyle.setBorderTop(CellStyle.BORDER_THIN);                    //上細線
        nStyle.setBorderBottom(CellStyle.BORDER_THIN);                //下細線
        nStyle.setBorderLeft(CellStyle.BORDER_THIN);                //左細線
        nStyle.setBorderRight(CellStyle.BORDER_THIN);                //右細線
        
        nStyle.setFont(nFont);
        
        return nStyle;
    }
    
    //文字樣式
    public CellStyle text(Workbook wb, CellStyle nStyle, Font nFont){
        nFont.setFontName("Times New Roman");
        nFont.setFontHeightInPoints((short)10);
        
        nStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);        //縱向居中
        
        //表格線
        nStyle.setBorderTop(CellStyle.BORDER_THIN);                    //上細線
        nStyle.setBorderBottom(CellStyle.BORDER_THIN);                //下細線
        nStyle.setBorderLeft(CellStyle.BORDER_THIN);                //左細線
        nStyle.setBorderRight(CellStyle.BORDER_THIN);                //右細線
        
        nStyle.setFont(nFont);
        
        return nStyle;
    }
}
下載代碼:

package util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class DownloadUtil {
    
    /**
     * @param filePath 要下載的文件路徑
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否刪除文件
     */
    protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(new File(filePath), returnName, response, delFlag);
    }


    /**
     * @param file 要下載的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否刪除文件
     */
    protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
        this.prototypeDownload(file, returnName, response, delFlag);
    }
    
    /**
     * @param file 要下載的文件
     * @param returnName 返回的文件名
     * @param response HttpServletResponse
     * @param delFlag 是否刪除文件
     */
    public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
        // 下載文件
        FileInputStream inputStream = null;
        ServletOutputStream outputStream = null;
        try {
            if(!file.exists()) return;
            response.reset();
            //設置響應類型    PDF文件爲"application/pdf",WORD文件爲:"application/msword", EXCEL文件爲:"application/vnd.ms-excel"。  
            response.setContentType("application/octet-stream;charset=utf-8");

            //設置響應的文件名稱,並轉換成中文編碼
            //returnName = URLEncoder.encode(returnName,"UTF-8");
            returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));    //保存的文件名,必須和頁面編碼一致,否則亂碼
            
            //p_w_upload作爲附件下載;inline客戶端機器有安裝匹配程序,則直接打開;注意改變配置,清除緩存,否則可能不能看到效果
            response.addHeader("Content-Disposition",   "p_w_upload;filename="+returnName);  
            
            //將文件讀入響應流
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            int length = 1024;
            int readLength=0;
            byte buf[] = new byte[1024];
            readLength = inputStream.read(buf, 0, length);
            while (readLength != -1) {
                outputStream.write(buf, 0, readLength);
                readLength = inputStream.read(buf, 0, length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //刪除原文件
            
            if(delFlag) {                
                file.delete();
            }
        }
    }

    /**
     * by tony 2013-10-17
     * @param byteArrayOutputStream 將文件內容寫入ByteArrayOutputStream
     * @param response HttpServletResponse    寫入response
     * @param returnName 返回的文件名
     */
    public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
        response.setContentType("application/octet-stream;charset=utf-8");
        returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));            //保存的文件名,必須和頁面編碼一致,否則亂碼
        response.addHeader("Content-Disposition",   "p_w_upload;filename=" + returnName);  
        response.setContentLength(byteArrayOutputStream.size());
        
        ServletOutputStream outputstream = response.getOutputStream();    //取得輸出流
        byteArrayOutputStream.writeTo(outputstream);                    //寫到輸出流
        byteArrayOutputStream.close();                                    //關閉
        outputstream.flush();                                            //刷數據
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章