1. 程式人生 > >springboot+poi匯出和匯入

springboot+poi匯出和匯入

1.匯入座標

<!-- excel2003使用的包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>
        <!-- excel2007+使用的包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.11</version>
        </dependency>

2 poi 匯出的controller

package com.czxy.web.reportform;

import com.czxy.common.DownloadUtil;
import com.czxy.domain.teke_delivery.WayBill;
import com.czxy.service.take_delivery.WayBillService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/poi")
public class PoiController {

    @Autowired
    private WayBillService wayBillService;

    @GetMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception{

        // 匯出  運單資訊
        List<WayBill> wayBillList = wayBillService.findAll();

        //1 建立工作簿 HSSFWorkbook   2003    XSSFWorkbook   2007
        Workbook wb = new XSSFWorkbook();
        //2 建立工作表
        Sheet sheet = wb.createSheet();

        // 設定列寬
        sheet.setColumnWidth(0,10*256);
        sheet.setColumnWidth(1,10*256);
        sheet.setColumnWidth(2,10*256);
        sheet.setColumnWidth(3,20*256);
        sheet.setColumnWidth(4,20*256);
        sheet.setColumnWidth(5,20*256);
        sheet.setColumnWidth(6,20*256);
        sheet.setColumnWidth(7,20*256);
        sheet.setColumnWidth(8,20*256);




        /***
         * 定義公共變數
         */
        int rowNo = 0,cellNo = 0;
        Row nRow = null;
        Cell nCell = null;

        /**************大標題*************/
        //3 建立行
        nRow = sheet.createRow(rowNo);
        // 設定行高
        nRow.setHeightInPoints(36);

        //4 建立單元格
        nCell = nRow.createCell(cellNo);
        //5 設定內容
        nCell.setCellValue("bos系統運單資訊"+new Date().toLocaleString());
        //6 設定內容格式
        // 合併單元格
        //引數1:起始行 引數2:終止行 引數3:起始列 引數4:終止列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, (short) 0, (short) 9));

        // 橫向居中  +   水平居中   +  紅色宋體22號
        nCell.setCellStyle(bigTitleCellStyle(wb));


        /*************小標題輸出**************/
        // 行號rowNo需要變化嗎  列需要變化嗎?
        rowNo++;

        String[] titles = {"id","運單號","訂單號","寄件人姓名","寄件人電話","寄件人地址","收件人姓名","收件人電話","收件人地址"};

        //3 建立行
        nRow = sheet.createRow(rowNo);
        for (String title:titles){

            //4 建立單元格
            nCell = nRow.createCell(cellNo++);// 先建立cell單元格,然後在自增
            //5 設定內容
            nCell.setCellValue(title);
            //6 設定內容格式
            nCell.setCellStyle(titleCellStyle(wb));
        }


        /**************內容*************/
        // 行號和列號需要變化?
        rowNo++;


        for(WayBill wayBill:wayBillList){
            cellNo=0;
            //3 建立行
            nRow = sheet.createRow(rowNo++);

            //4 建立單元格
            nCell = nRow.createCell(cellNo++);
            //5 設定內容
            nCell.setCellValue(wayBill.getId()+"");
            //6 設定內容格式
            nCell.setCellStyle(contentCellStyle(wb));
            // wayBillNum
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getWayBillNum());
            nCell.setCellStyle(contentCellStyle(wb));
            //訂單號
            nCell = nRow.createCell(cellNo++);

            nCell.setCellStyle(contentCellStyle(wb));
            //發件人姓名
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getSendName());
            nCell.setCellStyle(contentCellStyle(wb));
            //發件人電話
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getSendMobile());
            nCell.setCellStyle(contentCellStyle(wb));
            //發件人地址
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getSendAddress());
            nCell.setCellStyle(contentCellStyle(wb));
            //收件人姓名
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getRecName());
            nCell.setCellStyle(contentCellStyle(wb));

            //收件人電話
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getRecMobile());
            nCell.setCellStyle(contentCellStyle(wb));
            //收件人地址
            nCell = nRow.createCell(cellNo++);
            nCell.setCellValue(wayBill.getRecAddress());
            nCell.setCellStyle(contentCellStyle(wb));
        }




        /*************7 下載**********************/
        DownloadUtil downloadUtil = new DownloadUtil();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 將wb寫入流
        wb.write(byteArrayOutputStream);

        /**
         byteArrayOutputStream 將檔案內容寫入ByteArrayOutputStream
         response HttpServletResponse	寫入response
         returnName 返回的檔名

         */
        downloadUtil.download(byteArrayOutputStream,response,"bos運單表.xlsx");


    }

    public CellStyle bigTitleCellStyle(Workbook wb){
//        橫向居中  +   水平居中   +  紅色宋體22號
        CellStyle cellStyle = wb.createCellStyle();
        // 橫向居中
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        // 垂直居中
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

        Font font = wb.createFont();
        font.setFontHeight((short) 440);
        font.setColor(Font.COLOR_RED);
        font.setFontName("宋體");

        cellStyle.setFont(font);

        return cellStyle;
    }

    public CellStyle titleCellStyle(Workbook wb){
        // 宋體16號  傾斜   邊框線   水平垂直居中
        Font font = wb.createFont();
        font.setFontName("宋體");
        font.setItalic(true);
        font.setBold(true);

        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setFont(font);

        // 邊框線
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 細線
        cellStyle.setBorderRight(CellStyle.BORDER_DASHED);//圓點....
        cellStyle.setBorderBottom(CellStyle.BORDER_DOTTED);// 矩形的虛線_ _ _ _ _
        cellStyle.setBorderLeft(CellStyle.BORDER_DOUBLE);// 雙線
        // 橫向居中
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        // 垂直居中
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

        return cellStyle;

    }
    public CellStyle contentCellStyle(Workbook wb){
        // 邊框線   水平垂直居中
        CellStyle cellStyle = wb.createCellStyle();
        // 邊框線
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 細線
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);//
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);//
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);//

        return cellStyle;

    }

}

3.下載檔案的utils

package com.czxy.common;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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"));	//儲存的檔名,必須和頁面編碼一致,否則亂碼
			
			//attachment作為附件下載;inline客戶端機器有安裝匹配程式,則直接開啟;注意改變配置,清除快取,否則可能不能看到效果
			response.addHeader("Content-Disposition",   "attachment;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",   "attachment;filename=" + returnName);  
		response.setContentLength(byteArrayOutputStream.size());
		
		ServletOutputStream outputstream = response.getOutputStream();	//取得輸出流
		byteArrayOutputStream.writeTo(outputstream);					//寫到輸出流
		byteArrayOutputStream.close();									//關閉
		outputstream.flush();											//刷資料
	}
}

4 匯入Excel檔案

public static void main(String[] args) throws  Exception{
    // 流讀取檔案
    FileInputStream is = new FileInputStream(new File("d:\\area.xls"));
    // 根據流建立檔案
    Workbook wb = new HSSFWorkbook(is);
    // 獲取sheet
    Sheet sheet = wb.getSheetAt(0);
    // 遍歷row
    for(Row row:sheet){
        // 第一行是標題,不需要讀取
        if(row.getRowNum()==0){
            continue;
        }
        // 當遇到空行,跳過
        if(row.getCell(0)==null || StringUtils.isBlank(row.getCell(1).getStringCellValue())){
            continue;
        }
        // 列印內容
        System.out.print(row.getCell(0).getStringCellValue()+":");
        System.out.print(row.getCell(1).getStringCellValue()+":");
        System.out.print(row.getCell(2).getStringCellValue()+":");
        System.out.print(row.getCell(3).getStringCellValue()+":");
        System.out.println(row.getCell(4).getStringCellValue());
    }
}