java程序讀取excel表格並存入mysql數據庫詳細教程

0)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格式檔案的功能。

1)導入依賴

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

2)寫個ExcelUtil 工具類

package com.example.tool;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


import com.example.bean.ExcelBean;
import org.apache.http.client.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * @ClassName ExcelUtil
 * @Description TODO
 * @Author 胡澤
 * @Date 2019/8/31 9:31
 * @Version 1.0
 */
public class ExcelUtil {

    private final static String excel2003L = ".xls"; // 2003- 版本的excel
    private final static String excel2007U = ".xlsx"; // 2007+ 版本的excel

    /**
     * Excel導入
     */
    public static List<List<Object>> getUserListByExcel(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(getCellValue(cell));
                }
                list.add(li);
            }
        }
        return list;
    }

    /**
     * 描述:根據文件後綴,自適應上傳文件的版本
     */
    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;
    }

    /**
     * 描述:對錶格中數值進行格式化
     */
    public static Object getCellValue(Cell cell) {
        Object value = null;
        DecimalFormat df = new DecimalFormat("0"); // 格式化字符類型的數字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); // 日期格式化
        DecimalFormat df2 = new DecimalFormat("0"); // 格式化數字
        if (cell.getCellType() == CellType.STRING) {
            value = cell.getRichStringCellValue().getString();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                value = df.format(cell.getNumericCellValue());
            } else if ("m/d/yy".equals(cell.getCellStyle().getDataFormatString())) {
                value = sdf.format(cell.getDateCellValue());
            } else {
                value = df2.format(cell.getNumericCellValue());
            }
        } else if (cell.getCellType() == CellType.BOOLEAN) {
            value = cell.getBooleanCellValue();
        } else if (cell.getCellType() == CellType.BLANK) {
            value = "";
        }
        return value;
    }

    /**
     * 導入Excel表結束 導出Excel表開始
     *
     * @param sheetName
     *            工作簿名稱
     * @param clazz
     *            數據源model類型
     * @param objs
     *            excel標題列以及對應model字段名
     * @param map
     *            標題列行數以及cell字體樣式
     */
    public static XSSFWorkbook createExcelFile(Class clazz, List objs, Map<Integer, List<ExcelBean>> map,
                                               String sheetName) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException,
            ClassNotFoundException, IntrospectionException {
        // 創建新的Excel工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 在Excel工作簿中建一工作表,其名爲缺省值, 也可以指定Sheet名稱
        XSSFSheet sheet = workbook.createSheet(sheetName);
        // 以下爲excel的字體樣式以及excel的標題與內容的創建,下面會具體分析;
        createTableHeader(sheet, map); //創建標題(頭)
        createTableRows(sheet, map, objs, clazz); // 創建內容
        return workbook;
    }

    /**
     * @param sheet
     *            工作簿
     * @param map
     *            每行每個單元格對應的列頭信息
     */
    public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {
        for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
            XSSFRow row = sheet.createRow(entry.getKey());
            List<ExcelBean> excels = entry.getValue();
            for (int x = 0; x < excels.size(); x++) {
                XSSFCell cell = row.createCell(x);
                cell.setCellValue(excels.get(x).getHeadTextName());// 設置內容
            }
        }
    }

    public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz)
            throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException{
        int rowindex = map.size();
        int maxKey = 0;
        List<ExcelBean> ems = new ArrayList<>();
        for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
            if (entry.getKey() > maxKey) {
                maxKey = entry.getKey();
            }
        }
        ems = map.get(maxKey);
        for (Object obj : objs) {
            XSSFRow row = sheet.createRow(rowindex);
            for (int i = 0; i < ems.size(); i++) {
                ExcelBean em = (ExcelBean) ems.get(i);
                // 獲得get方法
                PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
                Method getMethod = pd.getReadMethod();
                Object rtn = getMethod.invoke(obj);
                String value = "";
                // 如果是日期類型進行轉換
                if (rtn != null) {
                    if (rtn instanceof Date) {
                        value = DateUtils.formatDate((Date) rtn, "yyyy-MM-dd");
                    } else {
                        value = rtn.toString();
                    }
                }
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(value);
                cell.setCellType(CellType.STRING);
            }
            rowindex++;
        }
    }
}

3)實體類

package com.example.bean;

import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import java.io.Serializable;

/**
 * @ClassName ExcelBean
 * @Description TODO
 * @Author 胡澤
 * @Date 2019/8/31 9:33
 * @Version 1.0
 */
public class ExcelBean implements Serializable {
    private String headTextName; // 列頭(標題)名
    private String propertyName; // 對應字段名
    private Integer cols; // 合併單元格數
    private XSSFCellStyle cellStyle;

    public ExcelBean() {
    }

    public ExcelBean(String headTextName, String propertyName) {
        this.headTextName = headTextName;
        this.propertyName = propertyName;
    }

    public ExcelBean(String headTextName, String propertyName, Integer cols) {
        super();
        this.headTextName = headTextName;
        this.propertyName = propertyName;
        this.cols = cols;
    }

    public String getHeadTextName() {
        return headTextName;
    }

    public void setHeadTextName(String headTextName) {
        this.headTextName = headTextName;
    }

    public String getPropertyName() {
        return propertyName;
    }

    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    public Integer getCols() {
        return cols;
    }

    public void setCols(Integer cols) {
        this.cols = cols;
    }

    public XSSFCellStyle getCellStyle() {
        return cellStyle;
    }

    public void setCellStyle(XSSFCellStyle cellStyle) {
        this.cellStyle = cellStyle;
    }

}

4)jsp頁面

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2019/8/30
  Time: 9:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri ="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--<form action="list" method="post" enctype="multipart/form-data"  >
    <input type="file" name="myfile" />
    <input type="submit" value="導入"/>
</form>--%>
<form action="getExcelData" method="post" enctype="multipart/form-data"  >
    <input type="file" name="myfile" />
    <input type="submit" value="導入"/>
</form>
<hr/>

<form action="export" method="post">
    <input type="submit" value="導出">
</form>
</body>
</html>

5)controller 類

@RequestMapping(value = "/getExcelData", method = RequestMethod.POST)
    public String getExcelData(MultipartFile myfile, Model model) {
        try {
            List<List<Object>> lists = ExcelUtil.getUserListByExcel(myfile.getInputStream(), myfile.getOriginalFilename());
            //List<List<Object>>--->List<User>
            List<UserInfo> users = new ArrayList<>();
            //
            for (int i = 0; i < lists.size(); i++) {
                UserInfo user = new UserInfo();
                List<Object> ob = lists.get(i);//List<Object>
                user.setId(Integer.parseInt(ob.get(0).toString()));//"1"
                user.setUsername(ob.get(1).toString());
                //ob.get(4).toString();//Object-->String("2019-08-30 12:12:12")--->Date
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println("1111111111111111111"+ob.get(4).toString());
                Date time = sdf.parse(ob.get(4).toString());
                user.setCreatedate(time);
                users.add(user);
            }
            //插入數據
            userInfoService.insert(users);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserInfoExample userExample = new UserInfoExample();
        List<UserInfo> allusers = userInfoService.selectByExample(userExample);
        model.addAttribute("all", allusers);
        return "display";
    }

6)效果圖
在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

哈哈哈哈哈哈哈哈!!!!!

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