SSM導出導入Excel表

項目中經常要用到Excel表格的導出導入。故此,寫了一個測試。現在奉上源碼。
項目的目錄結構:
這裏寫圖片描述

目錄結構截圖
這裏寫圖片描述

頁面展示截圖:
這裏寫圖片描述
導出截圖
這裏寫圖片描述

導入截圖成功插入數據庫
這裏寫圖片描述

現在給出全部源碼:
一:
PoiService.java

package com.bank.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.ss.usermodel.WorkbookFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.whf.dao.PoiDao;
import com.whf.entity.Computer;
import com.whf.util.FillComputerManager;
import com.whf.util.Layouter;
import com.whf.util.Writer;

@Service("poiService")
@Transactional
public class PoiService {

    @Resource(name = "poiDao")
    private PoiDao dao;

    public void exportXLS(HttpServletResponse response) {

        // 1.創建一個 workbook
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 2.創建一個 worksheet
        HSSFSheet worksheet = workbook.createSheet("Computer");

        // 3.定義起始行和列
        int startRowIndex = 0;
        int startColIndex = 0;

        // 4.創建title,data,headers
        Layouter.buildReport(worksheet, startRowIndex, startColIndex);

        // 5.填充數據
        FillComputerManager.fillReport(worksheet, startRowIndex, startColIndex, getDatasource());

        // 6.設置reponse參數
        String fileName = "ComputersReport.xls";
        response.setHeader("Content-Disposition", "inline; filename=" + fileName);
        // 確保發送的當前文本格式
        response.setContentType("application/vnd.ms-excel");

        // 7. 輸出流
        Writer.write(response, worksheet);

    }

    /**
     * 讀取報表
     */
    public List<Computer> readReport(InputStream inp) {

        List<Computer> computerList = new ArrayList<Computer>();

        try {
            String cellStr = null;

            Workbook wb = WorkbookFactory.create(inp);

            Sheet sheet = wb.getSheetAt(0);// 取得第一個sheets

            // 從第四行開始讀取數據
            for (int i = 3; i <= sheet.getLastRowNum(); i++) {

                Computer computer = new Computer();
                Computer addComputer = new Computer();

                Row row = sheet.getRow(i); // 獲取行(row)對象
                System.out.println(row);
                if (row == null) {
                    // row爲空的話,不處理
                    continue;
                }

                for (int j = 0; j < row.getLastCellNum(); j++) {

                    Cell cell = row.getCell(j); // 獲得單元格(cell)對象

                    // 轉換接收的單元格
                    cellStr = ConvertCellStr(cell, cellStr);

                    // 將單元格的數據添加至一個對象
                    addComputer = addingComputer(j, computer, cellStr);

                }
                // 將添加數據後的對象填充至list中
                computerList.add(addComputer);
            }

        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inp != null) {
                try {
                    inp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {

            }
        }
        return computerList;

    }

    /**
     * 從數據庫獲得所有的Computer信息.
     */
    private List<Computer> getDatasource() {
        return dao.getComputer();
    }

    /**
     * 讀取報表的數據後批量插入
     */
    public int[] insertComputer(List<Computer> list) {
        return dao.insertComputer(list);

    }

    /**
     * 獲得單元格的數據添加至computer
     * 
     * @param j 列數
     * @param computer 添加對象
     * @param cellStr 單元格數據
     * @return
     */
    private Computer addingComputer(int j, Computer computer, String cellStr) {
        switch (j) {
        case 0:
            // computer.setId(0);
            break;
        case 1:
            computer.setBrand(cellStr);
            break;
        case 2:
            computer.setCpu(cellStr);
            break;
        case 3:
            computer.setGpu(cellStr);
            break;
        case 4:
            computer.setMemory(cellStr);
            break;
        case 5:
            computer.setPrice(new Double(cellStr).doubleValue());
            break;
        }

        return computer;
    }

    /**
     * 把單元格內的類型轉換至String類型
     */
    private String ConvertCellStr(Cell cell, String cellStr) {

        switch (cell.getCellType()) {

        case Cell.CELL_TYPE_STRING:
            // 讀取String
            cellStr = cell.getStringCellValue().toString();
            break;

        case Cell.CELL_TYPE_BOOLEAN:
            // 得到Boolean對象的方法
            cellStr = String.valueOf(cell.getBooleanCellValue());
            break;

        case Cell.CELL_TYPE_NUMERIC:

            // 先看是否是日期格式
            if (DateUtil.isCellDateFormatted(cell)) {

                // 讀取日期格式
                cellStr = cell.getDateCellValue().toString();

            } else {

                // 讀取數字
                cellStr = String.valueOf(cell.getNumericCellValue());
            }
            break;

        case Cell.CELL_TYPE_FORMULA:
            // 讀取公式
            cellStr = cell.getCellFormula().toString();
            break;
        }
        return cellStr;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214

二:
PoiController.java

package com.whf.controller;

import java.io.IOException;
import java.util.List;

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.bank.service.PoiService;
import com.whf.entity.Computer;

@Controller
@RequestMapping("/report")
public class PoiController {

    @Resource(name = "poiService")
    private PoiService service;

    /**
     * 跳轉到主頁.
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String getIndex() {
        return "report";
    }

    /**
     * 導出excel報表
     */
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public void getXLS(HttpServletResponse response) {
        service.exportXLS(response);
    }

    /**
     * 讀取excel報表
     */
    @RequestMapping(value = "/read", method = RequestMethod.POST)
    public String getReadReport(@RequestParam
    MultipartFile file) throws IOException {
        List<Computer> list = service.readReport(file.getInputStream());
        service.insertComputer(list);
        return "addedReport";

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

三:
BaseDao.java

package com.whf.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.util.Assert;

/**
 * DAO基類,其它DAO可以直接繼承這個DAO,不但可以複用共用的方法,還可以獲得泛型的好處。
 */
public class BaseDao<T> {

    private Class<T> entityClass;

    @Autowired
    private HibernateTemplate hibernateTemplate;

    /**
     * 通過反射獲取子類確定的泛型類
     */
    public BaseDao() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    /**
     * 根據ID加載PO實例
     * 
     * @param id
     * @return 返回相應的持久化PO實例
     */
    public T load(Serializable id) {
        return (T) getHibernateTemplate().load(entityClass, id);
    }

    /**
     * 根據ID獲取PO實例
     * 
     * @param id
     * @return 返回相應的持久化PO實例
     */
    public T get(Serializable id) {
        return (T) getHibernateTemplate().get(entityClass, id);
    }

    /**
     * 獲取PO的所有對象
     * 
     * @return
     */
    public List<T> loadAll() {
        return getHibernateTemplate().loadAll(entityClass);
    }

    /**
     * 保存PO
     * 
     * @param entity
     */
    public void save(T entity) {
        getHibernateTemplate().save(entity);
        getHibernateTemplate().flush();
        // SessionFactory sf = hibernateTemplate.getSessionFactory();
        // sf.getCurrentSession().beginTransaction();
        // sf.getCurrentSession().save(entity);
    }

    /**
     * 刪除PO
     * 
     * @param entity
     */
    public void remove(T entity) {
        getHibernateTemplate().delete(entity);
    }

    /**
     * 更改PO
     * 
     * @param entity
     */
    public void update(T entity) {
        getHibernateTemplate().update(entity);
    }

    /**
     * 執行HQL查詢
     * 
     * @param sql
     * @return 查詢結果
     */
    public List find(String hql) {
        return this.getHibernateTemplate().find(hql);
    }

    /**
     * 執行帶參的HQL查詢
     * 
     * @param sql
     * @param params
     * @return 查詢結果
     */
    public List find(String hql, Object... params) {
        return this.getHibernateTemplate().find(hql, params);
    }

    /**
     * 對延遲加載的實體PO執行初始化
     * 
     * @param entity
     */
    public void initialize(Object entity) {
        this.getHibernateTemplate().initialize(entity);
    }

    /**
     * 分頁查詢函數,使用hql.
     * 
     * @param pageNo 頁號,從1開始.
     */
    public Page pagedQuery(String hql, int pageNo, int pageSize, Object... values) {
        Assert.hasText(hql);
        Assert.isTrue(pageNo >= 1, "pageNo should start from 1");
        // Count查詢
        String countQueryString = " select count (*) " + removeSelect(removeOrders(hql));
        List countlist = getHibernateTemplate().find(countQueryString, values);
        long totalCount = (Long) countlist.get(0);

        if (totalCount < 1)
            return new Page();
        // 實際查詢返回分頁對象
        int startIndex = Page.getStartOfPage(pageNo, pageSize);
        Query query = createQuery(hql, values);
        List list = query.setFirstResult(startIndex).setMaxResults(pageSize).list();

        return new Page(startIndex, totalCount, pageSize, list);
    }

    /**
     * 創建Query對象. 對於需要first,max,fetchsize,cache,cacheRegion等諸多設置的函數,可以在返回Query後自行設置. 留意可以連續設置,如下:
     * 
     * <pre>
     * dao.getQuery(hql).setMaxResult(100).setCacheable(true).list();
     * </pre>
     * 
     * 調用方式如下:
     * 
     * <pre>
     *        dao.createQuery(hql)
     *        dao.createQuery(hql,arg0);
     *        dao.createQuery(hql,arg0,arg1);
     *        dao.createQuery(hql,new Object[arg0,arg1,arg2])
     * </pre>
     * 
     * @param values 可變參數.
     */
    public Query createQuery(String hql, Object... values) {
        Assert.hasText(hql);
        Query query = getSession().createQuery(hql);
        for (int i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        return query;
    }

    /**
     * 去除hql的select 子句,未考慮union的情況,用於pagedQuery.
     * 
     * @see #pagedQuery(String,int,int,Object[])
     */
    private static String removeSelect(String hql) {
        Assert.hasText(hql);
        int beginPos = hql.toLowerCase().indexOf("from");
        Assert.isTrue(beginPos != -1, " hql : " + hql + " must has a keyword 'from'");
        return hql.substring(beginPos);
    }

    /**
     * 去除hql的orderby 子句,用於pagedQuery.
     * 
     * @see #pagedQuery(String,int,int,Object[])
     */
    private static String removeOrders(String hql) {
        Assert.hasText(hql);
        Pattern p = Pattern.compile("order\\s*by[\\w|\\W|\\s|\\S]*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(hql);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);
        return sb.toString();
    }

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    public Session getSession() {
        return SessionFactoryUtils.getSession(hibernateTemplate.getSessionFactory(), true);
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218


Page.java

package com.whf.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 分頁對象. 包含當前頁數據及分頁信息如總記錄數.
 * 
 */
public class Page implements Serializable {

    private static int DEFAULT_PAGE_SIZE = 20;

    private int pageSize = DEFAULT_PAGE_SIZE; // 每頁的記錄數

    private long start; // 當前頁第一條數據在List中的位置,從0開始

    private List data; // 當前頁中存放的記錄,類型一般爲List

    private long totalCount; // 總記錄數

    /**
     * 構造方法,只構造空頁.
     */
    public Page() {
        this(0, 0, DEFAULT_PAGE_SIZE, new ArrayList());
    }

    /**
     * 默認構造方法.
     * 
     * @param start 本頁數據在數據庫中的起始位置
     * @param totalSize 數據庫中總記錄條數
     * @param pageSize 本頁容量
     * @param data 本頁包含的數據
     */
    public Page(long start, long totalSize, int pageSize, List data) {
        this.pageSize = pageSize;
        this.start = start;
        this.totalCount = totalSize;
        this.data = data;
    }

    /**
     * 取總記錄數.
     */
    public long getTotalCount() {
        return this.totalCount;
    }

    /**
     * 取總頁數.
     */
    public long getTotalPageCount() {
        if (totalCount % pageSize == 0)
            return totalCount / pageSize;
        else
            return totalCount / pageSize + 1;
    }

    /**
     * 取每頁數據容量.
     */
    public int getPageSize() {
        return pageSize;
    }

    /**
     * 取當前頁中的記錄.
     */
    public List getResult() {
        return data;
    }

    /**
     * 取該頁當前頁碼,頁碼從1開始.
     */
    public long getCurrentPageNo() {
        return start / pageSize + 1;
    }

    /**
     * 該頁是否有下一頁.
     */
    public boolean isHasNextPage() {
        return this.getCurrentPageNo() < this.getTotalPageCount();
    }

    /**
     * 該頁是否有上一頁.
     */
    public boolean isHasPreviousPage() {
        return this.getCurrentPageNo() > 1;
    }

    /**
     * 獲取任一頁第一條數據在數據集的位置,每頁條數使用默認值.
     * 
     * @see #getStartOfPage(int,int)
     */
    protected static int getStartOfPage(int pageNo) {
        return getStartOfPage(pageNo, DEFAULT_PAGE_SIZE);
    }

    /**
     * 獲取任一頁第一條數據在數據集的位置.
     * 
     * @param pageNo 從1開始的頁號
     * @param pageSize 每頁記錄條數
     * @return 該頁第一條數據
     */
    public static int getStartOfPage(int pageNo, int pageSize) {
        return (pageNo - 1) * pageSize;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116

五:
PoiDao.java

package com.whf.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;

import com.whf.entity.Computer;

@Repository("poiDao")
public class PoiDao {

    private SimpleJdbcTemplate jdbcTemplate;

    @Resource(name = "dataSource")
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
    }

    public List<Computer> getComputer() {
        String sql = "SELECT * FROM computer";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Computer>(Computer.class));

    }

    public int[] insertComputer(List<Computer> list) {
        String sql = "INSERT INTO computer (BRAND,CPU,GPU,MEMORY,PRICE)VALUES(:brand,:cpu,:gpu,:memory,:price)";
        SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(list.toArray());
        return jdbcTemplate.batchUpdate(sql, batch);

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

六:
Computer.java

package com.whf.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Computer {

    @Id
    @GeneratedValue
    private int id;

    private String brand;

    private String cpu;

    private String gpu;

    private String memory;

    private Double price;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getGpu() {
        return gpu;
    }

    public void setGpu(String gpu) {
        this.gpu = gpu;
    }

    public String getMemory() {
        return memory;
    }

    public void setMemory(String memory) {
        this.memory = memory;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

七:
DateUtils.java

package com.whf.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Computer {

    @Id
    @GeneratedValue
    private int id;

    private String brand;

    private String cpu;

    private String gpu;

    private String memory;

    private Double price;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getCpu() {
        return cpu;
    }

    public void setCpu(String cpu) {
        this.cpu = cpu;
    }

    public String getGpu() {
        return gpu;
    }

    public void setGpu(String gpu) {
        this.gpu = gpu;
    }

    public String getMemory() {
        return memory;
    }

    public void setMemory(String memory) {
        this.memory = memory;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

八:
FillComputerManager.java

package com.whf.util;

import java.util.List;

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

import com.whf.entity.Computer;

public class FillComputerManager {

    public static void fillReport(HSSFSheet worksheet, int startRowIndex, int startColIndex, List<Computer> datasource) {

        // Row offset
        startRowIndex += 2;

        // Create cell style for the body
        HSSFCellStyle bodyCellStyle = worksheet.getWorkbook().createCellStyle();
        bodyCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        bodyCellStyle.setWrapText(false); // 是否自動換行.

        // Create body
        for (int i = startRowIndex; i + startRowIndex - 2 < datasource.size() + 2; i++) {
            // Create a new row
            HSSFRow row = worksheet.createRow((short) i + 1);

            // Retrieve the id value
            HSSFCell cell1 = row.createCell(startColIndex + 0);
            cell1.setCellValue(datasource.get(i - 2).getId());
            cell1.setCellStyle(bodyCellStyle);

            // Retrieve the brand value
            HSSFCell cell2 = row.createCell(startColIndex + 1);
            cell2.setCellValue(datasource.get(i - 2).getBrand());
            cell2.setCellStyle(bodyCellStyle);

            // Retrieve the model value
            HSSFCell cell3 = row.createCell(startColIndex + 2);
            cell3.setCellValue(datasource.get(i - 2).getCpu());
            cell3.setCellStyle(bodyCellStyle);

            // Retrieve the maximum power value
            HSSFCell cell4 = row.createCell(startColIndex + 3);
            cell4.setCellValue(datasource.get(i - 2).getGpu());
            cell4.setCellStyle(bodyCellStyle);

            // Retrieve the price value
            HSSFCell cell5 = row.createCell(startColIndex + 4);
            cell5.setCellValue(datasource.get(i - 2).getMemory());
            cell5.setCellStyle(bodyCellStyle);

            // Retrieve the efficiency value
            HSSFCell cell6 = row.createCell(startColIndex + 5);
            cell6.setCellValue(datasource.get(i - 2).getPrice());
            cell6.setCellStyle(bodyCellStyle);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

九:

package com.whf.util;

import java.util.List;

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

import com.whf.entity.Computer;

public class FillComputerManager {

    public static void fillReport(HSSFSheet worksheet, int startRowIndex, int startColIndex, List<Computer> datasource) {

        // Row offset
        startRowIndex += 2;

        // Create cell style for the body
        HSSFCellStyle bodyCellStyle = worksheet.getWorkbook().createCellStyle();
        bodyCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        bodyCellStyle.setWrapText(false); // 是否自動換行.

        // Create body
        for (int i = startRowIndex; i + startRowIndex - 2 < datasource.size() + 2; i++) {
            // Create a new row
            HSSFRow row = worksheet.createRow((short) i + 1);

            // Retrieve the id value
            HSSFCell cell1 = row.createCell(startColIndex + 0);
            cell1.setCellValue(datasource.get(i - 2).getId());
            cell1.setCellStyle(bodyCellStyle);

            // Retrieve the brand value
            HSSFCell cell2 = row.createCell(startColIndex + 1);
            cell2.setCellValue(datasource.get(i - 2).getBrand());
            cell2.setCellStyle(bodyCellStyle);

            // Retrieve the model value
            HSSFCell cell3 = row.createCell(startColIndex + 2);
            cell3.setCellValue(datasource.get(i - 2).getCpu());
            cell3.setCellStyle(bodyCellStyle);

            // Retrieve the maximum power value
            HSSFCell cell4 = row.createCell(startColIndex + 3);
            cell4.setCellValue(datasource.get(i - 2).getGpu());
            cell4.setCellStyle(bodyCellStyle);

            // Retrieve the price value
            HSSFCell cell5 = row.createCell(startColIndex + 4);
            cell5.setCellValue(datasource.get(i - 2).getMemory());
            cell5.setCellStyle(bodyCellStyle);

            // Retrieve the efficiency value
            HSSFCell cell6 = row.createCell(startColIndex + 5);
            cell6.setCellValue(datasource.get(i - 2).getPrice());
            cell6.setCellStyle(bodyCellStyle);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

十:
Layouter.java

package com.whf.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;

public class Layouter {

    /**
     * 創建報表
     */
    public static void buildReport(HSSFSheet worksheet, int startRowIndex, int startColIndex) {
        // 設置列的寬度
        worksheet.setColumnWidth(0, 5000);
        worksheet.setColumnWidth(1, 5000);
        worksheet.setColumnWidth(2, 5000);
        worksheet.setColumnWidth(3, 5000);
        worksheet.setColumnWidth(4, 5000);
        worksheet.setColumnWidth(5, 5000);

        buildTitle(worksheet, startRowIndex, startColIndex);

        buildHeaders(worksheet, startRowIndex, startColIndex);

    }

    /**
     * 創建報表標題和日期
     */
    private static void buildTitle(HSSFSheet worksheet, int startRowIndex, int startColIndex) {
        // 設置報表標題字體
        Font fontTitle = worksheet.getWorkbook().createFont();
        fontTitle.setBoldweight(Font.BOLDWEIGHT_BOLD);
        fontTitle.setFontHeight((short) 280);

        // 標題單元格樣式
        HSSFCellStyle cellStyleTitle = worksheet.getWorkbook().createCellStyle();
        cellStyleTitle.setAlignment(CellStyle.ALIGN_CENTER);
        cellStyleTitle.setWrapText(true);
        cellStyleTitle.setFont((HSSFFont) fontTitle);

        // 報表標題
        HSSFRow rowTitle = worksheet.createRow((short) startRowIndex);
        rowTitle.setHeight((short) 500);
        HSSFCell cellTitle = rowTitle.createCell(startColIndex);
        cellTitle.setCellValue("Computer Report!");
        cellTitle.setCellStyle(cellStyleTitle);

        // 合併區域內的報告標題
        worksheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));

        // date header
        HSSFRow dateTitle = worksheet.createRow((short) startRowIndex + 1);
        HSSFCell cellDate = dateTitle.createCell(startColIndex);
        cellDate.setCellValue("這個報表創建於: " + DateUtils.getNowTime());
    }

    /**
     * 創建表頭
     */
    private static void buildHeaders(HSSFSheet worksheet, int startRowIndex, int startColIndex) {
        // Header字體
        Font font = worksheet.getWorkbook().createFont();

        font.setBoldweight(Font.BOLDWEIGHT_BOLD);

        // 單元格樣式
        HSSFCellStyle headerCellStyle = worksheet.getWorkbook().createCellStyle();
        headerCellStyle.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
        headerCellStyle.setFillPattern(CellStyle.FINE_DOTS);
        headerCellStyle.setAlignment(CellStyle.ALIGN_CENTER);
        headerCellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
        headerCellStyle.setWrapText(true);
        headerCellStyle.setFont((HSSFFont) font);
        headerCellStyle.setBorderBottom(CellStyle.BORDER_THIN);

        // 創建字段標題
        HSSFRow rowHeader = worksheet.createRow((short) startRowIndex + 2);
        rowHeader.setHeight((short) 500);

        HSSFCell cell1 = rowHeader.createCell(startColIndex + 0);
        cell1.setCellValue("Id");
        cell1.setCellStyle(headerCellStyle);

        HSSFCell cell2 = rowHeader.createCell(startColIndex + 1);
        cell2.setCellValue("Brand");
        cell2.setCellStyle(headerCellStyle);

        HSSFCell cell3 = rowHeader.createCell(startColIndex + 2);
        cell3.setCellValue("CPU");
        cell3.setCellStyle(headerCellStyle);

        HSSFCell cell4 = rowHeader.createCell(startColIndex + 3);
        cell4.setCellValue("GPU");
        cell4.setCellStyle(headerCellStyle);

        HSSFCell cell5 = rowHeader.createCell(startColIndex + 4);
        cell5.setCellValue("Memory");
        cell5.setCellStyle(headerCellStyle);

        HSSFCell cell6 = rowHeader.createCell(startColIndex + 5);
        cell6.setCellValue("Price");
        cell6.setCellStyle(headerCellStyle);

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113

前端頁面:
一:
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<script>
  window.location.href=" <c:url value="/report"/>";
</script>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

二:
addedReport.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>Insert title here<</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 


  </head>

  <body>
    <h1>導入成功!</h1>  

<a href="/bank/report">返回</a>  
  </body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

三:
report.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>  
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>Report</title>


  </head>

  <body>
    <c:url var="exportUrl" value="/report/export" />  
    <c:url var="readUrl" value="/report/read" />  


    <h3><a href="${exportUrl }">Export Report</a></h3>  
    <br />  
    <form  id="readReportForm" action="${readUrl }" method="post" enctype="multipart/form-data"  >  
            <label for="file">File</label>  
            <input id="file" type="file" name="file" />  
            <p><button type="submit">Read</button></p>    
        </form>  
  </body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

《end》

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