1. 程式人生 > >依賴POI實現EXCEL匯入資料並生成javaBean和EXCEL根據資料庫表匯出

依賴POI實現EXCEL匯入資料並生成javaBean和EXCEL根據資料庫表匯出

首先是excel匯入匯出的工具類程式碼

public class ExportExcel {
    // 測試123
    private ExportExcel() {

    }

    /***
     * 工作簿
     */
    private static HSSFWorkbook workbook;

    /***
     * sheet
     */
    private static HSSFSheet sheet;

    /***
     * 表頭行開始位置
     */
    private static final int HEAD_START_POSITION = 0
; /*** * 文字行開始位置 */ private static final int CONTENT_START_POSITION = 1; /** * * @param dataList * 物件集合 * @param titleMap * 表頭資訊(物件屬性名稱->要顯示的標題值)[按順序新增] * @param sheetName * sheet名稱和表頭值 */ public static
void excelExport(List<?> dataList, Map<String, String> titleMap, String sheetName, String ExcelPath) { // 初始化workbook initHSSFWorkbook(sheetName); // 表頭行 createHeadRow(titleMap); // 文字行 createContentRow(dataList, titleMap); // 寫入處理結果 try
{ String filedisplay = sheetName; // 如果web專案,1、設定下載框的彈出(設定response相關引數);2、通過httpservletresponse.getOutputStream()獲取 OutputStream out = new FileOutputStream(ExcelPath + filedisplay); workbook.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } } /*** * * @param sheetName * sheetName */ private static void initHSSFWorkbook(String sheetName) { workbook = new HSSFWorkbook(); sheet = workbook.createSheet(sheetName); } /** * 建立表頭行 * * @param titleMap * 物件屬性名稱->表頭顯示名稱 */ private static void createHeadRow(Map<String, String> titleMap) { // 第1行建立 HSSFRow headRow = sheet.createRow(HEAD_START_POSITION); int i = 0; Set<Entry<String, String>> entrySet = titleMap.entrySet(); for (Entry<String, String> entry : entrySet) { HSSFCell headCell = headRow.createCell(i); headCell.setCellValue(entry.getValue()); i++; } } /** * * @param dataList * 物件資料集合 * @param titleMap * 表頭資訊 */ private static void createContentRow(List<?> dataList, Map<String, String> titleMap) { try { int i = 0; for (Object obj : dataList) { HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i); int j = 0; for (String entry : titleMap.keySet()) { String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1); Method m = obj.getClass().getMethod(method, null); String value; if (m.invoke(obj, null) == null) { value = ""; } else { value = m.invoke(obj, null).toString(); } HSSFCell textcell = textRow.createCell(j); textcell.setCellValue(value); j++; } i++; } } catch (Exception e) { e.printStackTrace(); } } public static List<Map<String, Object>> loadExcel(String filepath, int count) { // 建立Excel工作簿檔案的引用 HSSFWorkbook wookbook = null; try { wookbook = new HSSFWorkbook(new FileInputStream(filepath));// 根據路勁建立引用 } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 在excel文件中,第一個工作表的預設索引是0 HSSFSheet sheet = wookbook.getSheetAt(count); // 獲取到excel檔案中的所有行數 int rows = sheet.getPhysicalNumberOfRows(); List<Map<String, Object>> li = new ArrayList<Map<String, Object>>(); // boolean boo = false; for (int i = 1; i < rows; i++) { HSSFRow row = sheet.getRow(i); if (row != null) { // 獲取檔案中的所有列 int cells = row.getPhysicalNumberOfCells(); Map<String, Object> map = new HashMap<>(); // 遍歷列 for (int j = 0; j < cells; j++) { HSSFCell cell = row.getCell((short) j); if (cell != null) { HSSFRow title = sheet.getRow(0); HSSFCell titleCell = title.getCell(cell.getColumnIndex()); map.put(titleCell.getStringCellValue(), cell.getStringCellValue()); } } li.add(map); } } return li; } }

下面是呼叫服務程式碼

@Service
@Transactional
public class ExcelServiceImpl implements ExcelService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsKindMapper goodsKindMapper;

    @Value("${SheetName}")
    private String SheetName;

    @Value("${ExcelPath}")
    private String ExcelPath;

    @Value("${UploadPath}")
    private String UploadPath;

    @Override
    public void export() throws Exception {
        // TODO Auto-generated method stub
        GoodsExample example=new GoodsExample();
        List<Goods> list = goodsMapper.selectByExample(example);
        Map<String, String> titleMap=getTitleMap();
        ExportExcel.excelExport(list, titleMap, SheetName,ExcelPath);
    }


    private Map<String, String> getTitleMap() {
        // TODO Auto-generated method stub
        Map<String, String> titleMap=new TreeMap<String, String>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // TODO Auto-generated method stub
                return 1;
            }
        });
        titleMap.put("id","id" );
        titleMap.put("title","title" );
        titleMap.put("sellPoint","sellPoint" );
        titleMap.put("price","price" );
        titleMap.put("num","num" );
        titleMap.put("barcode","barcode" );
        titleMap.put("image","image" );
        titleMap.put("kid","kid" );
        titleMap.put("status","status" );
        titleMap.put("createDate","createDate" );
        titleMap.put("created","created" );
        titleMap.put("updated","updated" );
        return titleMap;
    }

    @Override
    @Transactional
    public void importExcel(String string, int i) throws Exception {
        // TODO Auto-generated method stub
        List<Map<String, Object>> loadExcel = ExportExcel.loadExcel(string, i);
        List<Goods> goods=new ArrayList<>();
        for (Map<String, Object> map : loadExcel) {
            Goods good=new Goods();
            good.setId(Long.parseLong(map.get("id").toString()));
            good.setTitle((String) map.get("title"));
            good.setSellPoint((String) map.get("sellPoint"));
            good.setPrice(Long.parseLong(map.get("price").toString()));
            good.setNum(Integer.parseInt(map.get("num").toString()));
            good.setBarcode((String) map.get("barcode"));
            good.setImage((String) map.get("image"));
            good.setKid(Long.parseLong(map.get("kid").toString()));
            good.setStatus(Byte.parseByte(map.get("status").toString()));
            good.setCreateDate(map.get("createDate").toString());
            good.setCreated(new Date(map.get("created").toString()));
            good.setUpdated(new Date(map.get("updated").toString()));
            goods.add(good);
        }
        goodsMapper.insertList(goods);
    }


    @Override
    public void buyImportExcel(String string, int i) throws Exception {
        // TODO Auto-generated method stub
        List<Map<String, Object>> loadExcel = ExportExcel.loadExcel(string, i);
        List<Goods> goods=new ArrayList<>();
        for (Map<String, Object> map : loadExcel) {
            Goods good=new Goods();
            good.setId(IDUtils.genItemId());
            good.setTitle((String) map.get("title"));
            good.setSellPoint((String) map.get("sellPoint"));
            good.setPrice(Long.parseLong(map.get("price").toString()));
            good.setNum(Integer.parseInt(map.get("num").toString()));
            good.setBarcode((String) map.get("barcode"));
            if(map.get("kname")!=null){
                String name = map.get("kname").toString().trim();
                GoodsKindExample example=new GoodsKindExample();
                Criteria createCriteria = example.createCriteria();
                createCriteria.andNameEqualTo(name);
                List<GoodsKind> list = goodsKindMapper.selectByExample(example);
                if(list!=null&&list.size()!=0){
                    for (GoodsKind goodsKind : list) {
                        if(!goodsKind.getIsParent()){
                            good.setKid(goodsKind.getId());
                        }
                    }
                }
            }
            good.setCreateDate(map.get("createDate").toString());
            good.setStatus(Byte.parseByte("1"));
            Date date = new Date();
            good.setCreated(date);
            good.setUpdated(date);
            goods.add(good);
        }
        goodsMapper.insertList(goods);
    }
}

getTitleMap方法中的map對應的是excel表格匯出中的第一列列名

下面是匯入和匯出的表格樣式
這裡寫圖片描述

資料庫表結構
這裡寫圖片描述