前後端分離之POI實現Excel文件的上傳和下載

若有不對之處歡迎大家指出,這個也是在學習工作中的一些總結,侵刪!
需要源碼聯繫QQ:1352057131
得之在俄頃,積之在平日。

POI概述

Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格檔案讀和寫的功能。

結構:

HSSF:提供讀寫Microsoft Excel格式檔案的功能。
XSSF:提供讀寫Microsoft Excel OOXML格式檔案的功能。
HWPF:提供讀寫Microsoft Word格式檔案的功能。
HSLF:提供讀寫Microsoft PowerPoint格式檔案的功能。
HDGF:提供讀寫Microsoft Visio格式檔案的功能。

Excel文件的上傳

文件格式:
在這裏插入圖片描述

引入相關依賴:

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.8</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.8</version>
        </dependency>

實體類(此處省略了get set方法):

public class User {
    private Integer number;
    private String password;
    private String name;
    private Integer age;
    private String gender;
    private Long phone;
}

前端代碼:

<div>
        <form method="post" action="http://localhost:8080/upload/file" enctype="multipart/form-data">
               <input name = "fileName" type = "file"><br>
               <input type = "submit" value = "點擊上傳">
        </form>
</div>

文件上傳工具類:

public class LocalFileImportUtil {
    private final static String excel2003L =".xls";    //2003- 版本的excel
    private final static String excel2007U =".xlsx";   //2007+ 版本的excel
    /**
     * @Description:獲取IO流中的數據,組裝成List<List<Object>>對象
     * @param in,fileName
     * @return
     * @throws IOException
     */
    public static List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception{
        List<List<Object>> list = null;

        //創建Excel工作薄
        Workbook work = getWorkbook(in,fileName);
        if(null == work){
            throw new Exception("創建Excel工作薄爲空!");
        }
        Sheet sheet = null;  //頁數
        Row row = null;  //行數
        Cell cell = null;  //列數
        list = new ArrayList<List<Object>>();
        //遍歷Excel中所有的sheet
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if(sheet==null){continue;}
            //遍歷當前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if(row==null||row.getFirstCellNum()==j){continue;}
                //遍歷所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    cell = row.getCell(y);
                    li.add(getValue(cell));
                }
                list.add(li);
            }
        }
        return list;
    }
    /**
     * @Description:根據文件後綴,自適應上傳文件的版本
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public static  Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if(excel2003L.equals(fileType)){
            wb = new HSSFWorkbook(inStr);  //2003-
        }else if(excel2007U.equals(fileType)){
            wb = new XSSFWorkbook(inStr);  //2007+
        }else{
            throw new Exception("解析的文件格式有誤!");
        }
        return wb;
    }

    /**
     * @Description:對錶格中數值進行格式化
     * @param cell
     * @return
     */
    //解決excel類型問題,獲得數值
    public static String getValue(Cell cell) {
        String value = "";
        if(null==cell){
            return value;
        }
        switch (cell.getCellType()) {
            //數值型
            case Cell.CELL_TYPE_NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //如果是date類型則 ,獲取該cell的date值
                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    value = format.format(date);;
                }else {// 純數字
                    BigDecimal big=new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解決1234.0  去掉後面的.0
                    if(null!=value&&!"".equals(value.trim())){
                        String[] item = value.split("[.]");
                        if(1<item.length&&"0".equals(item[1])){
                            value=item[0];
                        }
                    }
                }
                break;
            //字符串類型
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue().toString();
                break;
            // 公式類型
            case Cell.CELL_TYPE_FORMULA:
                //讀公式計算值
                value = String.valueOf(cell.getNumericCellValue());
                if (value.equals("NaN")) {// 如果獲取的數據值爲非法值,則轉換爲獲取字符串
                    value = cell.getStringCellValue().toString();
                }
                break;
            // 布爾類型
            case Cell.CELL_TYPE_BOOLEAN:
                value = " "+ cell.getBooleanCellValue();
                break;
            default:
                value = cell.getStringCellValue().toString();
        }
        if("null".endsWith(value.trim())){
            value="";
        }
        return value;
    }
}

Controller:

@Controller
@RequestMapping("/upload")
@CrossOrigin(origins = "http://localhost:8080")
public class FrontEndFileUploadController {

    @RequestMapping(value = "/file", method = RequestMethod.POST)
    public void fileUpload(@RequestParam("fileName") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        System.out.println("文件名稱+"+fileName);
        try {
            InputStream inputStream = file.getInputStream();
            List<List<Object>> list = LocalFileImportUtil.getListByExcel(inputStream, fileName);
            list.forEach((u)-> System.out.println(list.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Excel文件下載

此處僅演示後端生成Excel文件
文件上傳工具類:

public class ExportFileUtil {
    /**
     * @param sheetName sheet名稱
     * @param title     標題
     * @param values    內容
     * @param wb        HSSFWorkbook對象
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
        // 第一步,創建一個HSSFWorkbook,對應一個Excel文件
        if (wb == null)
            wb = new HSSFWorkbook();
        // 第二步,在workbook中添加一個sheet,對應Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet(sheetName);
        // 第三步,在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制
        HSSFRow row = sheet.createRow(0);
        // 第四步,創建單元格,並設置值表頭 設置表頭居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 創建一個居中格式
        //聲明列對象
        HSSFCell cell = null;
        //創建標題
        for (int i = 0; i < title.length; i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }
        //創建內容
        for (int i = 0; i < values.length; i++) {
            row = sheet.createRow(i + 1);
            for (int j = 0; j < values[i].length; j++) {
                //將內容按順序賦給對應的列對象
                row.createCell(j).setCellValue(values[i][j]);
            }
        }
        return wb;
    }
}

Controller:

@Controller
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:8080")//解決跨域請求方式二
public class ExportController {
    @ResponseBody
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//設置日期格式
        String year = df.format(new Date());
        //爲了方便大家理解,自己創建Uesr
        List<User> list = new ArrayList<>();
        for (int i = 0; i <10 ; i++) {
            User user = new User(i*2,"aaa"+i,"xiaoming"+i,i*5,"nan",(long) 1234567890);
            list.add(user);
        }
        //設置Excel表頭
        String[] title = {"賬號", "密碼", "姓名", "年齡", "性別", "電話"};
        //設置Excel文件名
        String filename = "LeaderList_"+year+".xls";
        //設置工作表名稱
        String sheetName = "sheet1";
        //開始對從數據庫中獲取到的數據進行處理
        String[][] content = new String[list.size()][6];
        try {
            for (int i = 0; i < list.size(); i++) {
                content[i][0] = String.valueOf(list.get(i).getNumber());
                content[i][1] = list.get(i).getPassword();
                content[i][2] = list.get(i).getName();
                content[i][3] = String.valueOf(list.get(i).getAge());
                content[i][4] = list.get(i).getGender();
                content[i][5] = String.valueOf(list.get(i).getPhone());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HSSFWorkbook wb = ExportFileUtil.getHSSFWorkbook(sheetName, title, content, null);
        try {
            // 響應到客戶端
            this.setResponseHeader(response, filename);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 向客戶端發送響應流方法
     *
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

測試:

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