1. 程式人生 > >Apache POI 第七講之利用 POI 技術實現使用模板批量新增資料

Apache POI 第七講之利用 POI 技術實現使用模板批量新增資料

有時候我們在做專案時,有些專案需要生成Microsoft Excel檔案格式的報告。有時,甚至希望將Excel檔案作為輸入資料。這是我們需要用到Apache POI 。例如,本次利用 POI 技術實現使用模板批量新增資料。

下載上傳模板

1.編寫頁面

function downloadTemplate(){
    window.open('template/userExporTemplate.xls');
}

2.檢視結果

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

利用 POI 技術實現使用模板批量新增資料

1.編寫匯出工具類

public static String formatCell(HSSFCell hssfCell){
    if
(hssfCell==null){ return ""; }else{ if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){ return String.valueOf(hssfCell.getBooleanCellValue()); }else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){ return String.valueOf(hssfCell.getNumericCellValue()); }else
{ return String.valueOf(hssfCell.getStringCellValue()); } } }

2.編寫action類匯出方法

public String upload()throws Exception{
        POIFSFileSystem fs=new POIFSFileSystem(new FileInputStream(userUploadFile));
        HSSFWorkbook wb=new HSSFWorkbook(fs);
        HSSFSheet hssfSheet=wb.getSheetAt(0
); // 獲取第一個Sheet頁 if(hssfSheet!=null){ for(int rowNum=1;rowNum<=hssfSheet.getLastRowNum();rowNum++){ HSSFRow hssfRow=hssfSheet.getRow(rowNum); if(hssfRow==null){ continue; } User user=new User(); user.setName(ExcelUtil.formatCell(hssfRow.getCell(0))); user.setPhone(ExcelUtil.formatCell(hssfRow.getCell(1))); user.setEmail(ExcelUtil.formatCell(hssfRow.getCell(2))); user.setQq(ExcelUtil.formatCell(hssfRow.getCell(3))); Connection con=null; try{ con=dbUtil.getCon(); userDao.userAdd(con, user); }catch(Exception e){ e.printStackTrace(); }finally{ dbUtil.closeCon(con); } } } JSONObject result=new JSONObject(); result.put("success", "true"); ResponseUtil.write(ServletActionContext.getResponse(), result); return null; }

3.編寫頁面

<div id="dlg2" class="easyui-dialog" style="width:400px;height:180px;padding:10px 20px"
            closed="true" buttons="#dlg-buttons2">
        <form id="uploadForm" action="user!upload" method="post" enctype="multipart/form-data">
            <table>
                <tr>
                    <td>下載模版:</td>
                    <td><a href="javascript:void(0)" class="easyui-linkbutton"  onclick="downloadTemplate()">匯入模版</a></td>
                </tr>
                <tr>
                    <td>上傳檔案:</td>
                    <td><input type="file" name="userUploadFile"></td>
                </tr>
            </table>
        </form>
    </div>
function uploadFile(){
    alert("1");
    $("#uploadForm").form("submit",{
        success:function(result){
        var result=eval('('+result+')');
        if(result.errorMsg){
            $.messager.alert("系統提示",result.errorMsg);
        }else{
            $.messager.alert("系統提示","上傳成功");
            $("#dlg2").dialog("close");
            $("#dg").datagrid("reload");
        }
               }
    });
}

4.檢視結果

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述