springMVC前臺ajax上傳excel文件並且解析其中內容

一、前端頁面結構及邏輯

ajax文件上傳可以參考之前的文件
formData上傳文件

二、後臺的相關處理

java解析excel文件有兩種方式,一種是jxl一種是poi。
jxl和poi最明顯的區別是:前者只能處理後綴名爲.xls的文件(2003版的);後者可以處理後綴名爲.xls和.xlsx(2007版)

1、利用jxl解析excel的相關代碼

  • pom.xml中的配置
<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>
  • Controller中的配置
    //EXCEL相關
    @ResponseBody
    @RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
    public void uploadExcel(@RequestParam(value = "fileinfo", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //此方法可參考文章上述鏈接(FileTools.getFileInfo())
        String path=FileTools.getFileInfo(request, response, file);
        File file1=new File(path)
        ExcelTools.readExcelWrite2TXT(file1);s
    }
  • 工具類中的配置
package com.lawsiji.txtcheck.common;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.*;

public class ExcelTools {
    /*******************EXCEL文件相關方法**********************/
    // 去讀Excel的方法readExcel,該方法的入口參數爲一個File對象
    public static void readExcelWrite2TXT(File file) {
        // 創建文件輸出流
        FileWriter fw = null;
        PrintWriter out = null;
        try {
            // 指定生成txt的文件路徑
            String fileName = file.getName().replace(".xls", "");
            fw = new FileWriter(file.getParent() + "/" + fileName + ".txt");
            out = new PrintWriter(fw);
            // 創建輸入流,讀取Excel
            InputStream is = new FileInputStream(file.getAbsolutePath());
            // jxl提供的Workbook類
            Workbook wb = Workbook.getWorkbook(is);
            // Excel的頁籤數量
            int sheet_size = wb.getNumberOfSheets();
            for (int index = 0; index < sheet_size; index++) {
                // 每個頁籤創建一個Sheet對象
                Sheet sheet = wb.getSheet(index);
                // sheet.getRows()返回該頁的總行數
                for (int i = 0; i < sheet.getRows(); i++) {
                    // sheet.getColumns()返回該頁的總列數
                    for (int j = 0; j < sheet.getColumns(); j++) {
                        String cellinfo = sheet.getCell(j, i).getContents();
                        // 將從Excel中讀取的數據寫入到txt中
                        out.println(cellinfo);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 記得關閉流
                out.close();
                fw.close();
                // 由於此處用到了緩衝流,如果數據量過大,不進行flush操作,某些數據將依舊
                // 存在於內從中而不會寫入文件,此問題一定要注意
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2、利用poi解析excel的相關代碼

  • pom.xml中的配置
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>
  • Controller中的配置
    //EXCEL相關
    @ResponseBody
    @RequestMapping(value = "/uploadExcel", method = RequestMethod.POST)
    public void uploadExcel(@RequestParam(value = "fileinfo", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //此方法可參考文章上述鏈接(FileTools.getFileInfo())
        String path=FileTools.getFileInfo(request, response, file);
        String s=ExcelPoiTools.read(path);
        System.out.println(s);
    }
  • 工具類中的配置
    文件名ExcelPoiTools.class
package com.lawsiji.txtcheck.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.text.NumberFormat;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelPoiTools {

    public static String read(String filePath) {
        String content="";
        try {
            /* 驗證文件是否合法 */
            if (!WDWUtil.validateExcel(filePath)) {
                System.out.println("excel文件格式錯誤!");
            }else{
                /* 判斷文件的類型,是2003還是2007 */
                if (WDWUtil.isExcel2007(filePath)) {
                    content = readEXCEL2007(filePath);
                } else if (WDWUtil.isExcel2003(filePath)) {
                    content = readEXCEL(filePath);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return content;
    }

    // 讀取xls文件
    public static String readEXCEL(String file) throws IOException {
        StringBuilder content = new StringBuilder();
        HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));// 創建對Excel工作簿文件的引用
        for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
            if (null != workbook.getSheetAt(numSheets)) {
                HSSFSheet aSheet = workbook.getSheetAt(numSheets);// 獲得一個sheet
                for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {
                    if (null != aSheet.getRow(rowNumOfSheet)) {
                        HSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 獲得一個行
                        for (short cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) {
                            if (null != aRow.getCell(cellNumOfRow)) {
                                HSSFCell aCell = aRow.getCell(cellNumOfRow);// 獲得列值
                                if (convertCell(aCell).length() > 0) {
                                    content.append(convertCell(aCell));
                                }
                            }
                            content.append("\n");
                        }
                    }
                }
            }
        }
        return content.toString();
    }

    // 讀取xlsx文件
    public static String readEXCEL2007(String file) throws IOException {
        StringBuilder content = new StringBuilder();
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) {
            if (null != workbook.getSheetAt(numSheets)) {
                XSSFSheet aSheet = workbook.getSheetAt(numSheets);// 獲得一個sheet
                for (int rowNumOfSheet = 0; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) {
                    if (null != aSheet.getRow(rowNumOfSheet)) {
                        XSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 獲得一個行
                        for (short cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) {
                            if (null != aRow.getCell(cellNumOfRow)) {
                                XSSFCell aCell = aRow.getCell(cellNumOfRow);// 獲得列值
                                if (convertCell(aCell).length() > 0) {
                                    content.append(convertCell(aCell));
                                }
                            }
                            content.append("\n");
                        }
                    }
                }
            }
        }
        return content.toString();
    }

    private static String convertCell(Cell cell) {
        NumberFormat formater = NumberFormat.getInstance();
        formater.setGroupingUsed(false);
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_NUMERIC:
                cellValue = formater.format(cell.getNumericCellValue());
                break;
            case HSSFCell.CELL_TYPE_STRING:
                cellValue = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                cellValue = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                cellValue = Boolean.valueOf(cell.getBooleanCellValue()).toString();
                break;
            case HSSFCell.CELL_TYPE_ERROR:
                cellValue = String.valueOf(cell.getErrorCellValue());
                break;
            default:
                cellValue = "";
        }
        return cellValue.trim();
    }
}

文件名WDWUtil.class ——用來判斷傳入文件的格式

package com.lawsiji.txtcheck.common;

public class WDWUtil {
    /*
     * @描述:是否是2003的excel,返回true是2003
     * @param filePath
     * @return
     */
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    /*
     * @描述:是否是2007的excel,返回true是2007
     * @param filePath
     * @return
     */
    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /*
     * 驗證是否是EXCEL文件
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath){
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){
            return false;
        }
        return true;
    }
}

參考http://blog.csdn.net/lin9118/article/details/9310135


此文章是自己學習時的筆記,其中有些術語可能不太準確,只供參考,如有問題歡迎賜教!

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