导入Excel

我会带着你远行 2022-08-11 00:56 354阅读 0赞

前面利用poi实现了导出excel,现在再来实现导入功能。

基本思路是前台页面上传Excel文件,将文件路径作为参数传到后台,后台获取完整路径,并通过InputStream来得到文件,再解析出文件内容,作为实体对象存到数据库,最后删除上传的excel文件。

这是页面代码:

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ page import="gx.util.base.SecurityUtil"%>
  4. <%
  5. String contextPath = request.getContextPath();
  6. SecurityUtil securityUtil = new SecurityUtil(session);
  7. %>
  8. <!DOCTYPE html>
  9. <html>
  10. <head>
  11. <title>会议组织</title>
  12. <jsp:include page="../../inc.jsp"></jsp:include>
  13. <script type="text/javascript">
  14. var uploader;//上传对象
  15. // 导出excel
  16. var export1 = function(){
  17. window.open(gx.contextPath + '/base/cmorganization!export.gx');
  18. };
  19. $(function() {
  20. //文件上传
  21. uploader = new plupload.Uploader({//上传插件定义
  22. browse_button : 'pickfiles',//选择文件的按钮
  23. container : 'container',//文件上传容器
  24. runtimes : 'html5,flash',//设置运行环境,会按设置的顺序,可以选择的值有html5,gears,flash,silverlight,browserplus,html4
  25. flash_swf_url : gx.contextPath + '/jslib/plupload-1.5.8/js/plupload.flash.swf',// Flash环境路径设置
  26. url : gx.contextPath + '/plUploadFile?fileFolder=/userPhoto',//上传文件路径
  27. max_file_size : '10mb',//100b, 10kb, 10mb, 1gb
  28. chunk_size : '10mb',//分块大小,小于这个大小的不分块
  29. unique_names : true,//生成唯一文件名
  30. // 指定要浏览的文件类型
  31. filters : [ {
  32. title : 'excel文件',
  33. extensions : 'xls,xlsx'
  34. } ]
  35. });
  36. uploader.bind('Init', function(up, params) {//初始化时
  37. //$('#filelist').html("<div>当前运行环境: " + params.runtime + "</div>");
  38. $('#filelist').html("");
  39. });
  40. uploader.bind('FilesAdded', function(up, files) {//选择文件后
  41. debugger;
  42. $.each(files, function(i, file) {
  43. $('#filelist').append('<div id="' + file.id + '">' + file.name + '(' + plupload.formatSize(file.size) + ')<strong></strong>' + '<span οnclick="uploader.removeFile(uploader.getFile($(this).parent().attr(\'id\')));$(this).parent().remove();" style="cursor:pointer;" class="ext-icon-cross" title="删除"> </span></div>');
  44. });
  45. up.refresh();
  46. });
  47. uploader.bind('BeforeUpload', function(uploader, file) {//上传之前
  48. if (uploader.files.length > 1) {
  49. parent.$.messager.alert('提示', '只允许最多选择1个文件!', 'error');
  50. uploader.stop();
  51. return;
  52. }
  53. $('.ext-icon-cross').hide();
  54. });
  55. uploader.bind('UploadProgress', function(up, file) {//上传进度改变
  56. var msg;
  57. if (file.percent == 100) {
  58. msg = '99';//因为某些大文件上传到服务器需要合并的过程,所以强制客户看到99%,等后台合并完成...
  59. } else {
  60. msg = file.percent;
  61. }
  62. $('#' + file.id + '>strong').html(msg + '%');
  63. parent.gx.progressBar({//显示文件上传滚动条
  64. title : '文件上传中...',
  65. value : msg
  66. });
  67. });
  68. uploader.bind('Error', function(up, err) {//出现错误
  69. $('#filelist').append("<div>错误代码: " + err.code + ", 描述信息: " + err.message + (err.file ? ", 文件名称: " + err.file.name : "") + "</div>");
  70. up.refresh();
  71. });
  72. uploader.bind('FileUploaded', function(up, file, info) {//上传完毕
  73. var response = $.parseJSON(info.response);
  74. if (response.status) {
  75. $('#' + file.id + '>strong').html("100%");
  76. $.post(gx.contextPath + '/base/cmorganization!upload.gx?cmorganizationUploadFile='+response.fileUrl,function(result) {
  77. if (result.success) {
  78. $.messager.alert("系统提示","上传成功");
  79. $("#dlg2").dialog("close");
  80. $("#dg").datagrid("reload");
  81. location.reload();
  82. }
  83. }, 'json');
  84. }
  85. });
  86. uploader.init();
  87. });
  88. // 导出excel
  89. var exportFunction = function(){
  90. var checklength = $('#grid').datagrid('getSelections');
  91. if (checklength.length > 0) {
  92. var saveid="";
  93. for (var a=0; a<checklength.length; a++) {
  94. var cmid = checklength[a].cmId;
  95. saveid += "'"+cmid+"',";
  96. }
  97. if (saveid.length > 0) {
  98. saveid = saveid.substring(0, saveid.length-1);
  99. window.location.href=gx.contextPath+ '/base/cmorganization!export.gx?cmId='+saveid;
  100. } else {
  101. parent.$.messager.alert('提示',"请勾选可操作信息进行导出!");
  102. }
  103. } else {
  104. parent.$.messager.alert('提示',"请勾选可操作信息进行导出!");
  105. }
  106. };
  107. // 打开导入数据面板
  108. var openUploadFileDialog = function(){
  109. $("#dlg2").dialog('open').dialog('setTitle','批量导入数据');
  110. };
  111. // 下载导入模板
  112. var downloadTemplate = function(){
  113. window.open(gx.contextPath +'/securityJsp/video/template/cmorganizationExporTemplate.xlsx');
  114. };
  115. var uploadFile = function() {
  116. //点添加
  117. var dialog = parent.gx.modalDialog({
  118. title : '导入',
  119. url : gx.contextPath + '/securityJsp/video/MeetingManagementFileForm.jsp',
  120. buttons : [ {
  121. text : '保存',
  122. iconCls: 'icon-save',
  123. handler : function() {
  124. dialog.find('iframe').get(0).contentWindow.submitForm(dialog, grid, parent.$);
  125. }
  126. },{
  127. text : '关闭',
  128. iconCls: 'icon-cancel',
  129. handler: function () { dialog.dialog("close"); }
  130. } ]
  131. });
  132. };
  133. var uploadFile = function() {
  134. if ($('form').form('validate')) {
  135. if (uploader.files.length > 0) {
  136. uploader.start();
  137. uploader.bind('StateChanged', function(uploaders) { // 在所有的文件上传完毕时,提交表单
  138. if (uploaders.files.length === (uploaders.total.uploaded + uploaders.total.failed)) {
  139. //这里操作文件insert
  140. parent.gx.progressBar('close');//关闭上传进度条
  141. }
  142. });
  143. }
  144. }
  145. };
  146. </script>
  147. </head>
  148. <body class="easyui-layout" data-options="fit:true,border:false">
  149. <!-- 导入数据面板 -->
  150. <div id="dlg2" class="easyui-dialog" style="width:400px;height:180px;padding:10px 20px"
  151. closed="true" buttons="#dlg-buttons2">
  152. <form method="post" class="form">
  153. <table>
  154. <tr>
  155. <th>下载模版:</th>
  156. <td><a href="javascript:void(0)" class="easyui-linkbutton" οnclick="downloadTemplate()">导入模版</a></td>
  157. <tr>
  158. <tr>
  159. <th>附件信息:</th>
  160. <td colspan="3">
  161. <div id="container" style="float: left;width: 100%;">
  162. <a id="pickfiles" href="javascript:void(0);" style="float: left;"
  163. class="easyui-linkbutton" data-options="iconCls:'ext-icon-zoom'">选择文件</a>
  164. </div>
  165. <div style="float: left;" id="filelist">您的浏览器没有安装Flash插件,或不支持HTML5!</div>
  166. </td>
  167. <tr>
  168. </tr>
  169. </table>
  170. </form>
  171. </div>
  172. <div id="dlg-buttons2">
  173. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-ok" οnclick="uploadFile()">上传</a>
  174. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" οnclick="javascript:$('#dlg2').dialog('close')">关闭</a>
  175. </div>
  176. </body>
  177. </html>

action中的代码:

  1. /**
  2. * 导入Excel
  3. */
  4. public String upload() throws Exception {
  5. String webParentPath = new File(getRequest().getSession().getServletContext().getRealPath("/")).getParent();// 当前WEB环境的上层目录
  6. String filePath =webParentPath+cmorganizationUploadFile;
  7. Workbook wb = ExcelUtil.readExcel(filePath); // 获取工作簿
  8. insertExcel(wb); // 插入数据库
  9. ExcelUtil.deleteFile(filePath); // 删除文件
  10. JSONObject result=new JSONObject();
  11. result.put("success", "true");
  12. ResponseUtil.write(ServletActionContext.getResponse(), result);
  13. return null;
  14. }
  15. /**
  16. * 读取excel文件内容,并存到数据库
  17. */
  18. public void insertExcel(Workbook wb) {
  19. Sheet sheet = wb.getSheetAt(0);
  20. if (sheet != null) {
  21. for(int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
  22. Row row = sheet.getRow(rowNum);
  23. if(row == null) {
  24. continue;
  25. }
  26. TCrCmOrganization cmOrganization = new TCrCmOrganization();
  27. cmOrganization.setCmName(ExcelUtil.formatCell(row.getCell(0)));
  28. cmOrganization.setCmTimeks(DateUtil.stringToDate(ExcelUtil.formatCell(row.getCell(1))));
  29. cmOrganization.setCmTimejs(DateUtil.stringToDate(ExcelUtil.formatCell(row.getCell(2))));
  30. cmOrganization.setCmOrganizer(ExcelUtil.formatCell(row.getCell(3)));
  31. cmOrganization.setCmCapacity(ExcelUtil.formatCell(row.getCell(4)));
  32. cmOrganization.setCmContent(ExcelUtil.formatCell(row.getCell(5)));
  33. cmOrganization.setCmHost(ExcelUtil.formatCell(row.getCell(6)));
  34. cmOrganization.setCmRecordpeople(ExcelUtil.formatCell(row.getCell(7)));
  35. cmOrganization.setCmSummaryLevel(ExcelUtil.formatCell(row.getCell(8)));
  36. service.save(cmOrganization);
  37. }
  38. }
  39. }

action中调用的方法:

  1. /**
  2. * 读取excel文件
  3. */
  4. public static Workbook readExcel(String path) {
  5. Workbook wb = null;
  6. try {
  7. InputStream inp = new FileInputStream(path);
  8. wb = WorkbookFactory.create(inp);
  9. } catch (FileNotFoundException e) {
  10. e.printStackTrace();
  11. } catch (InvalidFormatException e) {
  12. e.printStackTrace();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. return wb;
  17. }
  18. /**
  19. * 删除单个文件
  20. * @param sPath 被删除文件的文件名
  21. * @return 单个文件删除成功返回true,否则返回false
  22. */
  23. public static boolean deleteFile(String sPath) {
  24. boolean flag = false;
  25. File file = new File(sPath);
  26. // 路径为文件且不为空则进行删除
  27. if (file.isFile() && file.exists()) {
  28. file.delete();
  29. flag = true;
  30. }
  31. return flag;
  32. }
  33. /**
  34. * 将excel里面的数据类型全部转为String类型
  35. */
  36. public static String formatCell(HSSFCell hssfCell){
  37. if(hssfCell==null){
  38. return "";
  39. }else{
  40. if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
  41. return String.valueOf(hssfCell.getBooleanCellValue());
  42. }else if(hssfCell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
  43. return String.valueOf(hssfCell.getNumericCellValue());
  44. }else{
  45. return String.valueOf(hssfCell.getStringCellValue());
  46. }
  47. }
  48. }
  49. /**
  50. * 将excel里面的数据类型全部转为String类型
  51. */
  52. public static String formatCell(Cell cell){
  53. if(cell==null){
  54. return "";
  55. }else{
  56. if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN){
  57. return String.valueOf(cell.getBooleanCellValue());
  58. }else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC){
  59. return String.valueOf(cell.getNumericCellValue());
  60. }else{
  61. return String.valueOf(cell.getStringCellValue());
  62. }
  63. }
  64. }

不喜勿喷,欢迎共同探讨。

发表评论

表情:
评论列表 (有 0 条评论,354人围观)

还没有评论,来说两句吧...

相关阅读

    相关 导入Excel

    前面利用poi实现了导出excel,现在再来实现导入功能。 基本思路是前台页面上传Excel文件,将文件路径作为参数传到后台,后台获取完整路径,并通过InputStream来

    相关 jxls导入excel

    我们在开发中经常用jxls实现导出功能,殊不知jxls也有导入功能,下面来介绍下如何使用jxls导入excel。 首先在maven的pom中添加相关依赖,如下: