Java操做Jxl實現數據交互。三部曲——《第二篇》

Java操做Jxl實現.xsl及.xsls兩種數據表格進行批量導入數據到SQL server數據庫。

本文實現背景Web項目:前臺用的框架是Easyui+Bootstrap結合使用須要引入相應的Js、Css文件頁面:Jsp、攔截請求:Servlet、邏輯處理:ClassBean、數據庫:SQLserverjavascript

:Bean中操做SQL語句進行處理是公司內部方法,可替換爲其它方法自行擴展!主要看代碼邏輯業務處理!css

首先咱們看見Easyui中的datagrid數據網格列表中沒有任何數據:html

其次建立一個xsl文件如下是須要導入的數據格式:java

讓咱們把注意力放到SQLserver數據庫:jquery

點擊導入按鈕後彈出一個窗口選擇咱們剛剛建立的Excel文件,最後點擊導入ajax

 

 

 導入成功此時此刻Easyui中的datagrid數據網格中已有了7條咱們以前建立的記錄!sql

 

 

 

 

 

咱們回到數據庫進行查看數據,果真和預期效果同樣與Excel表格數據一致證實導入成功!數據庫

Jsp代碼: apache

注:from中的enctype="multipart/form-data"屬性是必加的,要想進行上傳必須使用HTML中的文件控件,且必須使用enctype進行分裝,表示將表單按照二進制的方式提交。即全部的操做表單此時再也不是分別提交,不然將全部內容都按照二進制的方式提交。若是要上傳文件,表單則必須封裝。可是當一個表單使用了enctype="multipart/form-data"封裝後,其它的非表單控件的內容就沒法經過request內置對象獲取,此時在Servlet中必須調用SmartUpload類中提供的getRequest()方法獲取所有的請求參數json

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="com.pantech.base.common.tools.MyTools"%>
<%@ page import="com.pantech.base.common.tools.PublicTools"%>
<%@ page import="com.pantech.src.develop.Logs.*"%>
<%@ page import="com.pantech.base.common.tools.*"%>
<%@ page import="com.pantech.src.develop.store.user.*"%>
<%@ page import="com.pantech.src.develop.manage.workremind.WorkRemind"%>
<%@ page import="java.util.Vector"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="com.pantech.base.common.db.DBSource"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>導入</title>

    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/css/themes/icon.css">
    <link charset="utf-8" rel="stylesheet" href="<%=request.getContextPath()%>/css/bootstrap.css"/>
    <link charset="utf-8" rel="stylesheet" href="<%=request.getContextPath()%>/css/naber.css"/>
    <link charset="utf-8" rel="stylesheet" href="<%=request.getContextPath()%>/css/font-awesome/css/font-awesome.css">
    <link charset="utf-8" rel="stylesheet" href="<%=request.getContextPath()%>/css/SMS-index.css"/>
    <link charset="utf-8" rel="stylesheet" href="<%=request.getContextPath()%>/css/listPage.css"/>
    
    <script type="text/javascript" src="<%=request.getContextPath()%>/script/JQueryUI/jquery.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/script/JQueryUI/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/script/JQueryUI/locale/easyui-lang-zh_CN.js"></script>
    <script charset="utf-8" src="<%=request.getContextPath()%>/script/bootstrap.min.js"></script>
    <script charset="utf-8" src="<%=request.getContextPath()%>/script/layer/layer.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/script/common/clientScript.js"></script> 
    <script type="text/javascript" src="<%=request.getContextPath()%>/script/common/publicScript.js"></script>


</head>
<body>

<%-- 遮罩層 --%>
<div id="divPageMask4" class="maskStyle">
    <div id="maskFont2"></div>
</div>

    <div class="bg-box indexBox" style="width: 1000px;">
        <div class="box">
            <div class="manage-list">
                <div class="row">
                    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
                        <span>我的信息列表</span>
                    </div>
                    <input type="button" onclick="doToolbar(this.id);" id="importTJXX"class="btn form-control btn-success" value="體檢信息批量導入"style="width: 135px; margin-top: 3px;" />
                    <input type="button" onclick="doToolbar(this.id);" id="deleteTJXX"class="btn form-control btn-danger" value="所有刪除"style="width: 135px; margin-top: 3px;" />
                </div>
            </div>
        </div>

        <div id="tableDIV" class="tablelist"style="width: 100%; height: 600px;">
            <table id="list" width="100%"></table>
        </div>
    </div>


<!-- 彈窗 -->
<div id="importInfoDialog">
        <div class="col-lg-10 col-md-10 col-sm-12 col-xs-12 content" style="width:100%;padding-top: 30px;">
            <div class="content-border">
                <div id="querybox2">
                    <form id="form3" name="form3" method="POST" action="<%=request.getContextPath()%>/ImportFileBean_Servlet" enctype="multipart/form-data">
                        <div class="row">
                                <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height:80px;">
                                  <input id="excel1" name="excel1" width="100%" type="text" style="width:90%;height: 34px;" >
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
                                <input type="button" id="saveImport" class="btn form-control btn-success dialogButtom-btn" value="導入" onclick="doToolbar(this.id);"/> 
                            </div>
                        </div>
                        <input type="hidden" id="active2" name="active" />
                    </form>
                </div>
            </div>
        </div>
    </div>
</body>

<script type="text/javascript">


$(document).ready(function(){
        initDialog();//初始化對話框
        initFilebox();
        loadGrid();
});




/**工具欄按鈕調用方法,傳入按鈕的id
@id 當前按鈕點擊事件
**/
function doToolbar(iToolbar){

    //點擊按鈕打開上傳附件彈窗
    if (iToolbar == 'importTJXX'){
        $('#importInfoDialog').dialog('setTitle', '導入');
        $('#importInfoDialog').dialog("open");
    }

    //點擊按鈕打開上傳附件彈窗
    if (iToolbar == 'deleteTJXX'){
         layer.confirm('刪除後沒法恢復,您是否確認刪除?', {
                btn: ['肯定','取消'] 
            }, function(){
                deleteTJXX();
            }, function(){
                
            });
    }
    
    //上傳體檢excel文件
    if (iToolbar == 'saveImport'){
        var excel1 = $('#excel1').filebox('getValue')
        var excelsuffix=excel1.substring(excel1.lastIndexOf("."),excel1.length);

        if($('#excel1').filebox('getValue') == ''){
            layer.alert('請選擇上傳文件');
            return;
        }
        if(excelsuffix!=".xls" && excelsuffix!=".xlsx"){  
            layer.alert('只能導入Excel類型的文件!');
               return;
        } 
        
        $("#active2").val("importExamInfo");
        showShade();//打開遮罩層
        $('#form3').submit(); 
        
    }
    
}






//刪除ajax
function deleteTJXX(){
    $.ajax({
        type:"post",
        url:'<%=request.getContextPath()%>/ImportFileBean_Svl',
        data:"active=deleteTJXX",
        dataType:"json",
        success: function(datas){
            if(datas[0].MSG == '刪除成功'){
                layer.msg(datas[0].MSG);
                loadGrid();
            }else{
                layer.alert(datas[0].MSG);
            }
        }
    });
}


//遮罩層
function showShade(){ 
    $('#maskFont2').html('導入中,請稍候...'); 
    $('#divPageMask4').show(); 
}



//上傳按鈕初始化
function initFilebox(){
    $('#excel1').filebox({
        buttonText: '選擇文件',
        buttonAlign: 'right'
    });
}



    /**加載 dialog控件**/
function initDialog(){
        $('#importInfoDialog').dialog({  
            width: 360,//寬度設置   
            height: 200,//高度設置 
            modal:true,
            closed: true,   
            cache: false, 
            draggable:false,//是否可移動dialog框設置
            //打開事件
            onOpen:function(data){},
            //讀取事件
            onLoad:function(data){},
            //關閉事件
            onClose:function(data){
                $('#form3').form('clear');
            }
        });

    }
    
    
    

//加載datagrid主頁面信息
function loadGrid(){
    $('#list').datagrid({
        url: '<%=request.getContextPath()%>/ImportFileBean_Svl',
        queryParams: {"active":"queryList"},
        loadMsg : "信息加載中請稍後!",//載入時信息
        nowrap: false,//當數據長度超出列寬時將會自動截取
        showFooter:true,
        rownumbers: true,
        animate:true,
        striped : true,//隔行變色
        pageSize : 10,//每頁記錄數
        singleSelect : true,//單選模式
        pageNumber : 20,//當前頁碼
        pagination:true,
        fit:true,
        fitColumns: true,//設置邊距
        columns:[[
            {field:'編號',title:'序號',width:fillsize(0.2)},
            {field:'體檢者',title:'姓名',width:fillsize(0.2)},
            {field:'體檢日期',title:'體檢日期',width:fillsize(0.2)},
            {field:'體檢機構',title:'體檢機構',width:fillsize(0.2)},
            {field:'體檢結果',title:'體檢結果',width:fillsize(0.2)}
        ]],
        onClickRow:function(rowIndex, rowData){
            row=rowData;
        },
        onLoadSuccess: function(data){
            iKeyCode='';
        },
        onLoadError:function(none){
            
        }
    });
    

}




//表單提交方法
$('#form3').form({
    //定位到servlet位置的url
    url:'<%=request.getContextPath()%>/ImportFileBean_Servlet',
    //當點擊事件後觸發的事件
    onSubmit: function(data){ 
    }, 
    //當點擊事件併成功提交後觸發的事件
    success:function(data){
        var json = eval("("+data+")");
        if(json[0].MSG=="導入完成"){
            $('#divPageMask4').hide();
                $('#importInfoDialog').dialog("close");
                layer.msg(json[0].MSG);
                loadGrid();
        }else if(json[0].MSG=="未找到sheet1"){
            layer.alert("工做表名稱不符");
        }else{
            layer.alert(json[0].MSG);
        }
           
    }
});



</script>
</html>

 

Servlet代碼以下:

Servlet中攔截前臺的importExamInfo導入請求,在調用Bean層中的導入邏輯處理方法!

package or.og.jxldemo;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.pantech.base.common.exception.WrongSQLException;
import com.pantech.base.common.tools.JsonUtil;
import com.pantech.base.common.tools.MyTools;

import net.sf.json.JSONArray;
public class ImportFileBean_Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");//request編碼類型
        response.setContentType("text/html;charset=UTF-8");//reponse類型統一
        
        Vector vector=new Vector();
        JSONArray jsonArray = new JSONArray(); 
        Vector jsonV = null;//返回結果集
        JSONArray jal = null;//返回json對象
        
        ImportFileBean  bean = new ImportFileBean(request);
        ServletConfig sc = this.getServletConfig();
        SmartUpload mySmartUpload = new SmartUpload("UTF-8");
        mySmartUpload.initialize(sc, request, response);//獲取request及response對象
        try {
            mySmartUpload.upload();
        } catch (SmartUploadException exception1) {
            // TODO 自動生成 catch 塊
            exception1.printStackTrace();
        }
        getParameters(request, bean,mySmartUpload);//初始化參數
        String active = MyTools.StrFiltr(mySmartUpload.getRequest().getParameter("active"));//獲取前臺提交的操做類型
        
        
        //導入信息
        if(active.equalsIgnoreCase("importExamInfo")){
            try {
                    bean.importExamInfo(mySmartUpload);//調用bean層中邏輯方法
                    jsonArray = JsonUtil.addJsonParams(jsonArray, "MSG", bean.getMSG());//轉換JSON數據格式
                    response.getWriter().write(jsonArray.toString());//返回服務器端響應
                    
                } catch (SQLException e) {
                    // TODO 自動生成 catch 塊
                    e.printStackTrace();
                } catch (SmartUploadException e) {
                    // TODO 自動生成 catch 塊
                    e.printStackTrace();
                } catch (WrongSQLException e) {
                    // TODO 自動生成 catch 塊
                    e.printStackTrace();
                }
        }
        
        
    }
    
    
    //得到頁面參數
    public void getParameters(HttpServletRequest request,ImportFileBean bean,SmartUpload mySmartUpload){
            
    }
}

Servlet中攔截前臺的查詢datadrig數據網格請求,在調用Bean層中的查詢方法!

package or.og.jxldemo;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUploadException;
import com.pantech.base.common.exception.WrongSQLException;
import com.pantech.base.common.tools.JsonUtil;
import com.pantech.base.common.tools.MyTools;
import com.pantech.base.common.tools.TraceLog;

import net.sf.json.JSONArray;

public class ImportFileBean_Svl extends HttpServlet {
       

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置字符編碼爲UTF-8
                request.setCharacterEncoding("UTF-8");
                response.setContentType("text/html;charset=UTF-8");
                
                String active = MyTools.StrFiltr(request.getParameter("active"));// 拿取前臺的active值
                int pageNum = MyTools.parseInt(request.getParameter("page"));    //得到頁面page參數 分頁
                int pageSize = MyTools.parseInt(request.getParameter("rows"));    //得到頁面rows參數 分頁
                
                Vector jsonV = null;//返回結果集
                JSONArray jal = null;//返回json對象
                ImportFileBean bean = new ImportFileBean(request);
                this.getFormData(request, bean); //獲取SUBMIT提交時的參數(AJAX適用)
                System.out.println("active:--"+active);

                
                
                //查詢所有信息
                if("queryList".equalsIgnoreCase(active)){
                    try {
                        try {
                            jsonV=bean.queryList(pageNum,pageSize);
                        } catch (WrongSQLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        jal = (JSONArray)jsonV.get(2);
                        response.getWriter().write("{\"total\":" + MyTools.StrFiltr(jsonV.get(0)) + ",\"rows\":" + jal.toString() + "}");
                        
                        TraceLog.Trace("response:   "+jal.toString());
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                
                
                //刪除所有信息
                if("deleteTJXX".equalsIgnoreCase(active)) {
                    try {
                        bean.deleteTJXX();
                        //返回操做信息
                        jal=JsonUtil.addJsonParams(jal, "MSG", bean.getMSG());
                        response.getWriter().write(jal.toString());
                    } catch (WrongSQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    
                }
            
    }

    

    /**
    * 從界面沒獲取參數
    * @date 
    * @author:yeq
    * @param request
    * @param MajorSetBean
    */
    private void getFormData(HttpServletRequest request, ImportFileBean bean){
    }
    
}

Bean代碼:

注:Bean中的導入方法中分別對.xsl和.xsls兩種表格數據文件進行不一樣處理!

package or.og.jxldemo;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

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.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.jspsmart.upload.SmartFile;
import com.jspsmart.upload.SmartFiles;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.pantech.base.common.db.DBSource;
import com.pantech.base.common.exception.WrongSQLException;
import com.pantech.base.common.tools.MyTools;

public class ImportFileBean {
    
    private HttpServletRequest request; 
    private DBSource db;
    
    private String MSG;//提示消息
    
    /** 
    * <p>Title: </p> 
    * <p>Description: </p> 
    * @param request 
    */
    //獲取對象
    public ImportFileBean(HttpServletRequest request) {
        this.request = request;
        this.db = new DBSource(request);
    }

    
    //查詢所有信息
    public Vector queryList(int pageNum,int pageSize)throws WrongSQLException,SQLException{
        Vector vec = null;
        String sql="SELECT [編號],[體檢者],convert(nvarchar(19),[體檢日期],21)as 體檢日期,[體檢機構],[體檢結果] " + 
                "FROM [V_我的檔案_體檢記錄] ";
        vec = db.getConttexJONSArr(sql, pageNum, pageSize);
        return vec;
    }
    
    
    
    //刪除所有信息
    public void deleteTJXX()throws WrongSQLException,SQLException{
        String sql="delete from [V_我的檔案_體檢記錄] ";
        if(db.executeInsertOrUpdate(sql)) {
            this.setMSG("刪除成功");
        }else {
            this.setMSG("刪除失敗");
        }
    }
    
    
    /**
     * @Title: saveimpxls
     * @Description: 導入體檢信息
     * @author lupengfei
     * @date 2016-7-19
     */
    @SuppressWarnings("unchecked")
    public void importExamInfo(SmartUpload mySmartUpload) throws SQLException, ServletException, IOException, SmartUploadException, WrongSQLException{
        DBSource db = new DBSource(request);
        String sql="";
        String sqlmx="";
        Vector vec = null; // 結果集
        
        String tempsheet="";//sheet名
        String tempsoin="";//第1列
        String tempsoin2="";
        String templine="";//第3列
        int sheetnum=0;//sheet計數
        String BH="";//編號
        String TJZXM="";//體檢者姓名
        String TJRQ="";//體檢日期
        String TJJGMC="";//體檢機構名稱
        String TJJG="";//體檢結果
        
        String path = "c:/temp/upload";
        File f1 = new File(path);  
        //當文件夾不存在時建立
        if (!f1.exists()) {  
            f1.mkdirs();  
        }
        //Workbook workbook = null;
        HSSFWorkbook workbook = null;
        XSSFWorkbook workbook2 = null;
        Vector vectormx=new Vector();

        SmartFiles files = mySmartUpload.getFiles(); //獲取文件
        
        SmartFile file= null;

        //判斷
        
        if(files.getCount() > 0){
            file = files.getFile(0);
            if(file.getSize()<=0){
                MSG = "文件內容爲空,請確認!";
            }
            file.saveAs(path +"/"+file.getFileName());
        }
        path=path +"/"+file.getFileName();
        String filename=file.getFileName();
        System.out.println("file=:"+file.getFileName());

        File file1=new File(path);
        
        
        try {
            InputStream is = new FileInputStream(file1);
            if (filename.substring(filename.indexOf(".")+1,filename.length()).equals("xls")) {
               workbook = new HSSFWorkbook(is);
               System.out.println(workbook.getNumberOfSheets());
            
            for(int k=0;k<workbook.getNumberOfSheets();k++){ //控制循環幾個Sheet
                    
                    HSSFSheet sheet = workbook.getSheetAt(k); //獲取sheet(k)的數據對象
                    tempsheet=workbook.getSheetName(k);//獲取sheet名
                    int firstRowIndex = sheet.getFirstRowNum();
                    int lastRowIndex = sheet.getLastRowNum();
                    int rsRows=lastRowIndex;
                    
                    if(lastRowIndex==0){
                        
                    }else{    
                
                    if("sheet1".equalsIgnoreCase(tempsheet.trim().toLowerCase())){//對工做表名稱進行判斷
                        System.out.println("sheet:"+tempsheet+" rows="+rsRows);
                        sheetnum++;

                            int locbh=-1;//編號
                            int loctjzxm=-1;//體檢者姓名
                            int loctjrq=-1;//體檢日期
                            int loctjjgmc=-1;//體檢機構名稱
                            int loctjjg=-1;//體檢結果
                            
                            
                            Row currentRow = sheet.getRow(0);// 當前行
                            int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
                            int lastColumnIndex = currentRow.getLastCellNum();// 最後一列

                            
                            //對頭標題進行判斷記錄下標
                            for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
                                Cell currentCell = currentRow.getCell(columnIndex);// 當前單元格
                                tempsoin = this.getCellValue(currentCell, true);// 當前單元格的值
                                
                                if(tempsoin.equalsIgnoreCase("編號")){
                                    locbh=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢者")){
                                    loctjzxm=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢日期")){
                                    loctjrq=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢機構")){
                                    loctjjgmc=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢結果")){
                                    loctjjg=columnIndex;
                                }
                            }
                            
                            
                            
                            for (int i = 1; i <= rsRows; i++) {//從第2行遍歷excel文件
                                currentRow = sheet.getRow(i);// 當前行
                                if (currentRow == null) {
                                       
                                }else{
                                    firstColumnIndex = currentRow.getFirstCellNum(); // 首列
                                    lastColumnIndex = currentRow.getLastCellNum();// 最後一列
                                    for (int columnIndex =firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
                                        Cell currentCell = currentRow.getCell(columnIndex);// 當前單元格
                                        tempsoin = this.getCellValue(currentCell, true);// 當前單元格的值
                                        if(tempsoin.equalsIgnoreCase("")){
                                            continue;
                                        }else{
                                            if(locbh==-1){
                                                BH=""; //編號列
                                            }else{
                                                if(locbh==columnIndex){
                                                    BH=tempsoin.trim(); 
                                                }    
                                            }
                                            if(loctjzxm==-1){
                                                TJZXM=""; //體檢者
                                            }else{
                                                if(loctjzxm==columnIndex){
                                                    TJZXM=tempsoin.trim(); 
                                                }    
                                            }
                                            if(loctjrq==-1){
                                                TJRQ=""; //體檢日期列
                                            }else{
                                                if(loctjrq==columnIndex){
                                                    TJRQ=tempsoin.trim(); 
                                                    TJRQ=convertDate(TJRQ);//轉換時間類型
                                                }    
                                            }
                                            if(loctjjgmc==-1){
                                                TJJGMC=""; //體檢機構
                                            }else{
                                                if(loctjjgmc==columnIndex){
                                                    TJJGMC=tempsoin.trim();
                                                }    
                                            }
                                            if(loctjjg==-1){
                                                TJJG=""; //體檢結果列
                                            }else{
                                                if(loctjjg==columnIndex){
                                                    TJJG=tempsoin.trim(); 
                                                }    
                                            }
                                    }
                                }
                                    
                                    sqlmx=" insert into V_我的檔案_體檢記錄 ([編號],[體檢者],[體檢日期],[體檢機構],[體檢結果]) values (" +
                                            "'"+MyTools.fixSql(BH)+"'," +//編號
                                            "'"+MyTools.fixSql(TJZXM)+"'," +//體檢者姓名
                                            "'"+MyTools.fixSql(TJRQ)+"'," +//體檢日期
                                            "'"+MyTools.fixSql(TJJGMC)+"'," +//體檢機構名稱
                                            "'"+MyTools.fixSql(TJJG)+"') " ;//體檢結果
                                             
                                    vectormx.add(sqlmx);
                                }
                            }
                        }
                    }
            }
        } else if (filename.substring(filename.indexOf(".")+1,filename.length()).equals("xlsx")) {
            workbook2 = new XSSFWorkbook(is);
            System.out.println(workbook2.getNumberOfSheets());
            
            for(int k=0;k<workbook2.getNumberOfSheets();k++){
                
                    XSSFSheet sheet = workbook2.getSheetAt(k); //獲取sheet(k)的數據對象
                    tempsheet=workbook2.getSheetName(k);//獲取sheet名
                    int firstRowIndex = sheet.getFirstRowNum();
                    int lastRowIndex = sheet.getLastRowNum()+1;
                    int rsRows=lastRowIndex;
                    if(lastRowIndex==1){
                        
                    }else{                    
                        System.out.println("sheet:"+tempsheet+" rows="+rsRows);
                        
                        if("sheet1".equalsIgnoreCase(tempsheet.trim().toLowerCase())){
                            sheetnum++;
                            
                            int locbh=-1;//編號
                            int loctjzxm=-1;//體檢者姓名
                            int loctjrq=-1;//體檢日期
                            int loctjjgmc=-1;//體檢機構名稱
                            int loctjjg=-1;//體檢結果
                                
                            Row currentRow = sheet.getRow(0);// 當前行
                            int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
                            int lastColumnIndex = currentRow.getLastCellNum();// 最後一列
                            
                            for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
                                Cell currentCell = currentRow.getCell(columnIndex);// 當前單元格
                                tempsoin = this.getCellValue(currentCell, true);// 當前單元格的值

                                if(tempsoin.equalsIgnoreCase("編號")){
                                    locbh=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢者")){
                                    loctjzxm=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢日期")){
                                    loctjrq=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢機構")){
                                    loctjjgmc=columnIndex;
                                }else if(tempsoin.equalsIgnoreCase("體檢結果")){
                                    loctjjg=columnIndex;
                                }
                            }
                            
                                
                                for (int i = 1; i < rsRows; i++) {//從第2行遍歷excel文件
                                    currentRow = sheet.getRow(i);// 當前行

                                    if (currentRow == null) {
                                       
                                    }else{
                                        firstColumnIndex = currentRow.getFirstCellNum(); // 首列
                                        lastColumnIndex = currentRow.getLastCellNum();// 最後一列
                                        for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {
                                            Cell currentCell = currentRow.getCell(columnIndex);// 當前單元格
                                            tempsoin = this.getCellValue(currentCell, true);// 當前單元格的值
                                            
                                            if(tempsoin.equalsIgnoreCase("")){
                                                continue;
                                            }else{
                                                if(locbh==-1){
                                                    BH=""; //編號列
                                                }else{
                                                    if(locbh==columnIndex){
                                                        BH=tempsoin.trim(); 
                                                    }    
                                                }
                                                if(loctjzxm==-1){
                                                    TJZXM=""; //體檢者
                                                }else{
                                                    if(loctjzxm==columnIndex){
                                                        TJZXM=tempsoin.trim(); 
                                                    }    
                                                }
                                                if(loctjrq==-1){
                                                    TJRQ=""; //體檢日期列
                                                }else{
                                                    if(loctjrq==columnIndex){
                                                        TJRQ=tempsoin.trim(); 
                                                        TJRQ=convertDate(TJRQ);//轉換時間類型
                                                    }    
                                                }
                                                if(loctjjgmc==-1){
                                                    TJJGMC=""; //體檢機構
                                                }else{
                                                    if(loctjjgmc==columnIndex){
                                                        TJJGMC=tempsoin.trim(); 
                                                    }    
                                                }
                                                if(loctjjg==-1){
                                                    TJJG=""; //體檢結果列
                                                }else{
                                                    if(loctjjg==columnIndex){
                                                        TJJG=tempsoin.trim(); 
                                                    }    
                                                }
                                        }
                                    }
                                            
                                        sqlmx=" insert into V_我的檔案_體檢記錄 ([編號],[體檢者],[體檢日期],[體檢機構],[體檢結果]) values (" +
                                                "'"+MyTools.fixSql(BH)+"'," +//編號
                                                "'"+MyTools.fixSql(TJZXM)+"'," +//體檢者姓名
                                                "'"+MyTools.fixSql(TJRQ)+"'," +//體檢日期
                                                "'"+MyTools.fixSql(TJJGMC)+"'," +//體檢機構名稱
                                                "'"+MyTools.fixSql(TJJG)+"') " ;//體檢結果
                                                 
                                    }    vectormx.add(sqlmx);
                                }
                        }    
                    }
            }
        }
        if(db.executeInsertOrUpdateTransaction(vectormx)){
            this.MSG="導入完成";
        }else{
            this.MSG="導入失敗";
        }
        if(sheetnum==0){
            this.MSG="未找到sheet1";
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
    finally {
        //workbook.close();
    }
}
    
    
    
    
    
    
    
    
    /**
     * 取單元格的值
     * @param cell 單元格對象
     * @param treatAsStr 爲true時,當作文原本取值 (取到的是文本,不會把「1」取成「1.0」)
     * @return
     */
    private String getCellValue(Cell cell, boolean treatAsStr) {
        if (cell == null) {
            return "";
        }

        if (treatAsStr) {
            // 雖然excel中設置的都是文本,可是數字文本還被讀錯,如「1」取成「1.0」
            // 加上下面這句,臨時把它當作文原本讀取
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }

        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        }else {
            return String.valueOf(cell.getStringCellValue());
        }
  
    }
    
    
 // 轉換日期
     public static String convertDate(String s) throws ParseException{
         if (s == null || "".equals(s)) {
             return "";
         }
         // 將excel讀取日期時遇到數字 轉化爲日期
         // Excel 的一個有趣之處就是,當您試圖將數字轉換爲日期時,程序會假定該數字是一個序列號,
         // 表明自 1900 年 1 月 1 日起所發生的天數。自 1900 年 1 月 1 日 算起的第 39331 天就是 2007 年 9 月 6 日
         String rtn = "1900-01-01";
         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
         Date date1 = new Date();
         date1 = format.parse("1900-01-01");
         long i1 = date1.getTime();
         // 這裏要減去2,(Long.parseLong(s)-2) 否則日期會提早2天,具體緣由不清楚,
         // 估計和java計時是從1970-01-01開始有關
         // 而excel裏面的計算是從1900-01-01開始
         i1 = i1 / 1000 + ((Long.parseLong(s) - 2) * 24 * 3600);
         date1.setTime(i1 * 1000);
         rtn = format.format(date1);
         return rtn;
     }
    

    public String getMSG() {
        return MSG;
    }

    public void setMSG(String mSG) {
        MSG = mSG;
    }

}

至此Java操做Jxl批量導入數據成功,本人只是寫了一個簡單的小案例可自行擴展功能及所需表格格式

此文章來自一個努力作IT界中一股清流的小夥子。喜歡的朋友記得幫我頂一下!!

相關文章
相關標籤/搜索