poi批量實(shí)現(xiàn)導(dǎo)入功能,jxl實(shí)現(xiàn)導(dǎo)入預(yù)覽功能
- ////////////總結(jié):
- 導(dǎo)入流程:先下載導(dǎo)入模板,根據(jù)導(dǎo)入模板填寫(xiě)內(nèi)容,填寫(xiě)完保存到本地,
- 點(diǎn)擊批量數(shù)據(jù)導(dǎo)入彈出導(dǎo)入文件選擇界面,點(diǎn)擊預(yù)覽數(shù)據(jù)彈出表格,
- 點(diǎn)擊導(dǎo)入數(shù)據(jù),開(kāi)始導(dǎo)入。
- 其中技術(shù)點(diǎn)有:io實(shí)現(xiàn)下載,poi實(shí)現(xiàn)導(dǎo)入,jxl實(shí)現(xiàn)導(dǎo)入預(yù)覽。
- 需要的jar:
- poi-3.14-20160307.jar
- poi-extend4.0-20150421.jar
- jxl.jar
- commons-fileupload-1.3.1.jar
- commons-io-2.4.jar
- <a href="javascript:void(0)" class="easyui-linkbutton" id="docpath" iconCls="icon-excel" plain="true" onclick="DownLoad()">批量數(shù)據(jù)導(dǎo)入模版</a>
-
- 點(diǎn)擊批量數(shù)據(jù)導(dǎo)入模版的時(shí)候執(zhí)行
- function DownLoad(){
- $('#fpForm').submit();
- }
-
- //這個(gè)是對(duì)應(yīng)的下載導(dǎo)入模板
- <div id="fpForm1" style="float:left;margin-left:25px;">
- <form id="fpForm" action="${request.contextPath}/TdLawTask/download" method="post"><!--action對(duì)應(yīng)的是controle路徑-->
- <label style="width:60px"></label><input id="fp" name="filepath" value="WEB-INF/upload/files/import/單位導(dǎo)入數(shù)據(jù)模板.xls" type="hidden" /><!--value是模板路徑值-->
- </form>
- </div>
-
- 提交到后臺(tái)controle的路徑(action="${request.contextPath}/TdLawTask/download")
- /**
- * @Description下載選中行的附件
- */
- @ResponseBody
- @RequestMapping("download")
- public void download(@RequestParam String filepath,
- HttpServletRequest request, HttpServletResponse response) {
- filepath = filepath.replace("/", "\\");
- FileUtil.downloadfile(filepath, request, response);
- }
-
- 下載工具類(lèi)FileUtil
- /**
- * 下載文件(不需要修改,直接使用)
- *
- * @param file
- * @param request
- * @param isPic
- * @return
- */
- public static String downloadfile(String filepath,
- HttpServletRequest request, HttpServletResponse response) {
- String filename = "";
- //windows 中和liunx中路徑格式不一致
- if (File.separator.equals("\\")) {
- filepath = filepath.replace("/", "\\");
- filename = filepath.substring(filepath.lastIndexOf("\\") + 1);
- } else {
- filepath = filepath.replace("\\", "/");
- filename = filepath.substring(filepath.lastIndexOf("/") + 1);
- }
- //設(shè)置響應(yīng)編碼格式
- response.setCharacterEncoding("utf-8");
- //設(shè)置文件ContentType類(lèi)型,這樣設(shè)置,會(huì)自動(dòng)判斷下載文件類(lèi)型
- response.setContentType("multipart/form-data");
- // response.setHeader("Content-Disposition", "attachment;fileName="
- // + filename);
- String path = "";
- try {
- //設(shè)置文件頭:最后一個(gè)參數(shù)是設(shè)置下載文件名
- response.addHeader("Content-Disposition", "attachment;filename="
- + new String(filename.getBytes("gbk"), "iso-8859-1")); // 轉(zhuǎn)碼之后下載的文件不會(huì)出現(xiàn)中文亂碼
- //獲取Web項(xiàng)目的全路徑
- path = request.getSession().getServletContext().getRealPath("/")
- + filepath;
- File file = new File(path);
- if (!file.exists())
- return path;
- // System.out.println(path);
- response.addHeader("Content-Length", "" + file.length());
- InputStream inputStream = new FileInputStream(file);
- OutputStream os = response.getOutputStream();
- byte[] b = new byte[2048];
- int length;
- while ((length = inputStream.read(b)) > 0) {
- os.write(b, 0, length);
- }
- os.close();
- inputStream.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return path;
- }
-
-
- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-excel" plain="true" onclick="implexll();">批量數(shù)據(jù)導(dǎo)入</a>
-
- //點(diǎn)擊批量數(shù)據(jù)導(dǎo)入時(shí),打開(kāi)批量導(dǎo)入數(shù)據(jù)表單
- function implexll(){
- $('#dlgup').dialog('open').dialog('setTitle','導(dǎo)入excel');
- $('#impsearchfm').form('clear');
- }
-
- <!--批量導(dǎo)入數(shù)據(jù)表單-->
- <div id="dlgup" class="easyui-dialog" style="padding:10px 20px;" closed="true" buttons="#dlg-buttons-up">
- <form id="impsearchfm" novalidate method="post" enctype="multipart/form-data" style="float:left">
- <div class="fitem">
- <label style="width:90px">文件路徑:</label>
- <input name="file" id="file" class="easyui-filebox" style="width:240px" data-options="buttonText:'選擇文件',buttonIcon:'icon-search',prompt:'文件路徑...'" value="選擇文件">
- </div>
- </form>
- </div>
- <div id="dlg-buttons-up">
- <a href="javascript:void(0)" onclick="preview();" class="easyui-linkbutton" iconCls="icon-search">預(yù)覽數(shù)據(jù)</a>
- <a href="javascript:void(0)" onclick="implexl();" class="easyui-linkbutton" iconCls="icon-excel">導(dǎo)入數(shù)據(jù)</a>
- </div>
-
- <!--導(dǎo)入時(shí)預(yù)覽表單-->
- <div id="ppreview" class="easyui-dialog" closed="true" buttons="#dlg-buttons-up-ppreview" style="width:800px;height:500px;" >
- <table id="dgpreview" class="easyui-datagrid" style="width:auto;height:100%;overflow:hidden;"
- striped="true" fit="true" fitColumns="true" scrollbarSize=0
- pagination="false" rownumbers="true" singleSelect="true"
- data-options="fit:true,border:false,pagesize:2000,pageList:[20000]" >
- <thead>
- <tr>
- <th data-options="field:'userId',align:'left',halign:'center',width:'12%'">測(cè)試</th>
- <th data-options="field:'corpname',align:'left',halign:'center',width:'36%'" formatter=namecolor>測(cè)試1</th>
- </tr>
- </thead>
- </table>
- </div>
- <div id="dlg-buttons-up-ppreview">
- <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#ppreview').dialog('close')" style="width:90px">取消</a>
- </div>
-
- //點(diǎn)擊預(yù)覽數(shù)據(jù)
- function preview(){
- $('#ppreview').dialog('open').dialog('setTitle','信息預(yù)覽');
-
- var filename=$('#file').filebox('getValue');
- if(filename==null || filename=='')
- {
- showMsg('提示','請(qǐng)選擇文件!');
- return;
- }
- $('#impsearchfm').form('submit',{
- url: '${request.contextPath}/business/getfilename',//請(qǐng)求后臺(tái)
- onSubmit: function(){
- $.messager.progress({
- title : '提示',
- text : '數(shù)據(jù)處理中,請(qǐng)稍后....'
- });
- return true;
- },
- success: function(data){
-
- //上傳文件并得到文件名
- loadPriview(data);
- }
- });
-
- function loadPriview(filename){
- $.ajax({
- type : 'get',
- url : '${request.contextPath}/business/preview',
- dataType : 'json',
- data : {data :filename},
- cache :false,
- success : function(data) {
- $.messager.progress('close');
- $('#dgpreview').datagrid({
- data:data
- });
- }
- });
- }
- }
- //${request.contextPath}/business/getfilename',//后臺(tái)代碼
- /**
- *
- * @Method_Name: getfilename
- * @Description: 上傳文件并返回文件名
- */
- @ResponseBody
- @RequestMapping("getfilename")
- public String getFileName(DicInputPrd dicinputprd,@RequestParam("file") MultipartFile file, HttpServletRequest request,HttpSession session) {
- String filePath="";
- String fileName="";
-
- if(file!=null){
- if(file.getSize()>0)
- filePath=FileUtil.upload(file, request, true);//調(diào)用下面的上傳文件
- fileName=request.getSession().getServletContext()
- .getRealPath("/")+filePath;
- }
- return fileName;
- }
-
- 上傳下載工具類(lèi)FileUtil
- /**
- * 上傳文件
- *
- * @param file
- * @param request
- * @param isPic
- * @return
- */
- public static String upload(MultipartFile file, HttpServletRequest request,
- Boolean isPic) {
- SimpleDateFormat dateformat = new SimpleDateFormat("yyyy_MM_dd/HHMMSS");
- //文件夾名字
- String pathDir = "upload" + File.separator + "imgs" + File.separator
- + dateformat.format(new Date()) + (int) Math.random() * 1000
- + File.separator;
- if (File.separator.equals("\\")) {
- pathDir = pathDir.replace("/", "\\");
- }
-
- if (isPic == false) {
- pathDir = pathDir.replace("imgs", "files");
- }
-
- String filename = file.getOriginalFilename();//獲取文件名
- String extName = "";
- if (StrUtil.isNotBlank(filename)) {//判斷是否為空,不為空走if
- int t = filename.lastIndexOf(".");
- if (t > 0) {
- extName = filename.substring(t).toLowerCase();//獲取文件的后綴名字
- }
- }
- filename = sdf.format(new Date());//時(shí)間格式化
- // File file2 = new File(request.getSession().getServletContext()
- // .getRealPath(pathDir));
- pathDir += filename + extName;//上傳的路徑完整名
- String realPathDir = request.getSession().getServletContext()
- .getRealPath(pathDir);//項(xiàng)目的完整路徑名
- // if(!file2.exists())
- // file2.mkdir();
- try {
- FileUtils.copyInputStreamToFile(file.getInputStream(), new File(
- realPathDir));
- } catch (IOException e) {
- e.printStackTrace();
- }
- return pathDir;
- }
- ${request.contextPath}/business/preview',后臺(tái)代碼,獲取excel表格中數(shù)據(jù),并按照指定格式返回
-
- //導(dǎo)入時(shí)預(yù)覽
- @ResponseBody
- @RequestMapping("preview")
- public JqueryUiJson preview(String data, HttpServletRequest request,HttpSession session) {
- List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
- try {
- InputStream is = new FileInputStream(data);
- jxl.Workbook rwb = Workbook.getWorkbook(is);//得到工作薄
- Sheet[] rslist=rwb.getSheets();//工作?。╓orkbook)中工作表(Sheet)對(duì)象數(shù)組
- //循環(huán)讀取sheet工作表
- for(int i=0;i<rslist.length;i++){
- //獲取Sheet表中所包含的總行數(shù):getRows()
- for(int j=1;j<rslist[i].getRows();j++){
- Map<String, Object> map = new HashMap<String,Object>();
- int length = rslist[i].getColumns();//獲取Sheet表中所包含的總列數(shù):getColumns()
- String[] content=new String[length];//內(nèi)容數(shù)組content
- //如果一行沒(méi)有任何內(nèi)容,則跳過(guò)
- int flag = 0;
- for( int t=0;t<length;t++){//取到某行某列的內(nèi)容
- content[t]=rslist[i].getCell(t,j).getContents().trim();
- if(!"".equals(content[t])&&content[t] != null){
- flag=1;
- }
- }
- if(flag==0){
- continue;
- }
- map.clear();
-
- //這里可以對(duì)某一列進(jìn)行處理(這里可以修改start)
- String industry="";
- String [] stringArr = content[7].split(";");
- for(int t = 0;t<stringArr.length;t++){
- String sql6 = "SELECT VALUE as industry FROM sys_aaaa WHERE id = 'dic' AND item = '"+stringArr[t]+"'";
- Map map6 = sqlMapper.selectOne(sql6,new Object[]{"industry"});
- if(map6!=null){
- industry += map6.get("industry").toString()+",";
- }
- }
- industry=industry.substring(0,industry.length()-1);
- //這里可以對(duì)某一列進(jìn)行處理(這里可以修改end)
- map.put("ceshi1", content[0]);
- map.put("ceshi2", content[1]);
- map.put("ceshi3", content[2]);
- map.put("ceshi4", content[3]);
- map.put("ceshi5", content[4]);
- map.put("ceshi6", content[5]);
- map.put("ceshi7", industry);
- map.put("ceshi8", content[6]);
- list.add(map);
- }
- }
- rwb.close();//關(guān)閉工作薄
- //返回結(jié)果//返回(總條數(shù)(total),數(shù)據(jù)(rows))的格式。(這里根據(jù)自己需要的格式進(jìn)行返回)
- JqueryUiJson jqueryUiJson = new JqueryUiJson(ExampleUtil.getPageInfo(list).getTotal(), list);
- return jqueryUiJson;
- }catch(Exception e){
- e.printStackTrace();
- return null;
- }
- }
-
- 這個(gè)是分頁(yè)數(shù)據(jù)格式化,包名:(import com.github.pagehelper.PageInfo)
- public static <T> PageInfo<T> getPageInfo(List<T> tlist) {
- PageInfo<T> pageinfo = new PageInfo<T>(tlist);
- return pageinfo;
- }
-
-
- //點(diǎn)擊導(dǎo)入數(shù)據(jù)
- function implexl(){
- var filename=$('#file').filebox('getValue');//獲取文件名
- if(filename==null || filename=='')
- {
- showMsg('提示','請(qǐng)選擇文件!');
- return;
- }
- $('#impsearchfm').form('submit',{
- url: '${request.contextPath}/business/importExl',
- onSubmit: function(){
- $.messager.progress({//提示信息
- title : '提示',
- text : '數(shù)據(jù)處理中,請(qǐng)稍后....'
- });
- return true;
- },
- success: function(result){
- $.messager.progress('close');//成功關(guān)閉提示信息
- var rtnMsg="";
- if (result!="0"){
- showMsg('錯(cuò)誤提示','上傳數(shù)據(jù)不規(guī)范');
- } else {
- showMsg('提示','數(shù)據(jù)導(dǎo)入成功');
- //刷新列表
- //關(guān)閉提示框
- }
- }
- });
- }
-
- //導(dǎo)入時(shí)請(qǐng)求后臺(tái)
- '${request.contextPath}/business/importExl',請(qǐng)求對(duì)應(yīng)的后臺(tái)
-
- /**
- * @Method_Name: importExl
- * @Description: 批量導(dǎo)入
- */
- @ResponseBody
- @RequestMapping("importExl")
- public String importExl(@RequestParam("file") MultipartFile file, HttpServletRequest request,HttpSession session){
- try {
- String str = tdLawTaskService.importExl(file,session,type);
- return str;
- } catch (Exception e) {
- e.printStackTrace();
- return e.getMessage();
- }
- }
- service
- public String importExl(MultipartFile file,HttpSession session,String type);
-
- /**
- * @Method_Name: importExl
- * @Description: 導(dǎo)入
- */
- public String importExl(MultipartFile file,HttpSession session,String type){
- String str = "";
- if(file!=null){
- ImportExcel impexc = new ImportExcel();
- //創(chuàng)建時(shí)間
- String createdate = DateTimeUtil.getDateTime();
- try {
- List<String> list = impexc.readExcelContent(file.getInputStream());//讀取Excel數(shù)據(jù)內(nèi)容
- String sql_head ="INSERT into td_law_sss (ceshi1,ceshi2,ceshi3)VALUES ";
- for (int i = 0; i < list.size(); i++) {
- String[] sourceStrArray = list.get(i).split(",",-1);
- //判斷 空行 跳過(guò)
- if(StrUtil.konghang(sourceStrArray)){
- continue;
- }
- str =str+ "('"+sourceStrArray[0]+"'," +"'"+sourceStrArray[1]+"','"+sourceStrArray[2]+"'), ";
- }
- sqlMapper.insert(sql_head+str.substring(0, str.length()-2)+";");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return "0";
- }
-
- ImportExcel.java類(lèi)Start
- /**
- * 讀取Excel數(shù)據(jù)內(nèi)容
- * @param InputStream
- * @return Map 包含單元格數(shù)據(jù)內(nèi)容的Map對(duì)象
- */
- public List<String> readExcelContent(InputStream is) {
- // Map<Integer, String> content = new HashMap<Integer, String>();
- List<String> content = new ArrayList<String>();
- String str = "";
- try {
- fs = new POIFSFileSystem(is);
- wb = new HSSFWorkbook(fs);
- } catch (IOException e) {
- e.printStackTrace();
- }
- sheet = wb.getSheetAt(0);
- // 得到總行數(shù)
- int rowNum = sheet.getLastRowNum();
- row = sheet.getRow(0);
- //獲取不為空的列個(gè)數(shù)
- int colNum = row.getPhysicalNumberOfCells();
- // 正文內(nèi)容應(yīng)該從第二行開(kāi)始,第一行為表頭的標(biāo)題
- for (int i = 1; i <= rowNum; i++) {
- row = sheet.getRow(i);
- //防止中間某行沒(méi)有內(nèi)容
- int flag = 0;
- if(null!=row){
- flag = 1;
- }
- if(flag == 0){
- continue;
- }
- int j = 0;
- while (j < colNum) {
- // 每個(gè)單元格的數(shù)據(jù)內(nèi)容用"-"分割開(kāi),以后需要時(shí)用String類(lèi)的replace()方法還原數(shù)據(jù)
- // 也可以將每個(gè)單元格的數(shù)據(jù)設(shè)置到一個(gè)javabean的屬性中,此時(shí)需要新建一個(gè)javabean
- // str += getStringCellValue(row.getCell((short) j)).trim() +
- // "-";
- //得到Excel工作表指定行的單元格:row.getCell((short) j
- str += getCellFormatValue(row.getCell((short) j)).trim() + ","; //格式化數(shù)據(jù)
- j++;
- }
- content.add(str);
- str = "";
- }
- return content;
- }
-
- /**
- * 根據(jù)HSSFCell類(lèi)型設(shè)置數(shù)據(jù)
- * @param cell
- * @return
- */
- private String getCellFormatValue(HSSFCell cell) {
- String cellvalue = "";
- if (cell != null) {
- // 判斷當(dāng)前Cell(單元格)的Type
- switch (cell.getCellType()) {
- // 如果當(dāng)前Cell的Type為NUMERIC
- case HSSFCell.CELL_TYPE_NUMERIC:
- case HSSFCell.CELL_TYPE_FORMULA: {
- // 判斷當(dāng)前的cell是否為Date
- if (HSSFDateUtil.isCellDateFormatted(cell)) {
- // 如果是Date類(lèi)型則,轉(zhuǎn)化為Data格式
-
- //方法1:這樣子的data格式是帶時(shí)分秒的:2011-10-12 0:00:00
- //cellvalue = cell.getDateCellValue().toLocaleString();
-
- //方法2:這樣子的data格式是不帶帶時(shí)分秒的:2011-10-12
- Date date = cell.getDateCellValue();
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- cellvalue = sdf.format(date);
-
- }
- // 如果是純數(shù)字
- else {
- // 取得當(dāng)前Cell的數(shù)值
- //cellvalue = String.valueOf(cell.getNumericCellValue());
- DecimalFormat df = new DecimalFormat("0");
- cellvalue = df.format(cell.getNumericCellValue());
- }
- break;
- }
- // 如果當(dāng)前Cell的Type為STRIN
- case HSSFCell.CELL_TYPE_STRING:
- // 取得當(dāng)前的Cell字符串
- cellvalue = cell.getRichStringCellValue().getString();
- break;
- // 默認(rèn)的Cell值
- default:
- cellvalue = " ";
- }
- } else {
- cellvalue = "";
- }
- return cellvalue;
- }
- ImportExcel.java類(lèi)end
-
- //StrUtil類(lèi)中導(dǎo)入時(shí)判斷空行
- public static boolean konghang(String[] content){
- int flag = 0;
- for( int t=0;t<content.length;t++){
- if(!"".equals(content[t])&&content[t] != null){
- flag=1;
- break;
- }
- }
- if(flag==0){
- return true;
- }
- return false;
- }
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶(hù)發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。