项目中遇到将sqlserver2005数据导出到excel并将excel导入到oracle中,导出的字段顺序可以变但是第二列不能为空。
解析的时候也得按照这个需求来解析,我把代码贴出来分享下。
页面:
imp.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>数据导入</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="<%=path %>/js/jquery.js"></script> <script type="text/javascript" src="js/ajaxfileupload.js"></script> <script type="text/javascript" src="<%=path %>/js/jquery.easyui.min.js"></script> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function ajaxFileUpload() { var areaida = $('#areaid').val(); $("#loading") .ajaxStart(function(){ $(this).show(); })//开始上传文件时显示一个图片 .ajaxComplete(function(){ $(this).hide(); });//文件上传完成将图片隐藏起来 $.ajaxFileUpload ( { url:'FileImpDBServlet',//用于文件上传的服务器端请求地址 secureuri:false,//一般设置为false fileElementId:'uploadimage',//文件上传空间的id属性 <input type="file" id="file" name="file" /> dataType: 'json',//返回值类型 一般设置为json success: function (data, status) //服务器成功响应处理函数 { alert(data[0].message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量 $('#previewImage').attr("src",data[1].imagepath); $('#lawpeopleimage').val(data[1].imagepath); $('#myspan').html(data.message); if(typeof(data.error) != 'undefined') { if(data.error != '') { alert(data.error); }else { alert(data.message); } } }, error: function (data, status, e)//服务器响应失败处理函数 { //alert("服务中断或连接超时导致通信失败!"); //alert(e); } } ) return false; } </script> </head> <body> <!-- <div align="center" ><img src="images/wutupian.jpg" alt="预览图片" name="previewImage" align="middle" id="previewImage" style="WIDTH: 100px; HEIGHT: 150px"/> </div> --> <div align="center"> <img src="images/loading.gif" id="loading" style="display: none;"> <span style="color: red;" id="myspan"></span><br/> <input type="file" id="uploadimage" name="uploadimage" size="8" /> <!--<s:hidden name="lawpeople.image" id="lawpeopleimage"></s:hidden> --> <input type="text" name="lawpeople.image" id="lawpeopleimage" readonly="readonly" style="display: none"/> <input type="button" value="导入" onClick="return ajaxFileUpload();"> </div> </body> </html>
FileImpDBServlet .java
package com.future.zfs.util; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.future.zfs.model.Manager; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.future.zfs.biz.impl.AreaBizImpl; import com.future.zfs.biz.intf.IAreaBizInf; import com.future.zfs.model.Area; /** * * @author xushigang *此方法是接收页面传来的excel */ @SuppressWarnings("serial") public class FileImpDBServlet extends HttpServlet { final long MAX_SIZE = 50*1024*1024;// 设置上传文件最大为 50M // 允许上传的文件格式的列表 final String[] allowtype = new String[] {"xlsb","xls"}; private IAreaBizInf areaimpl = new AreaBizImpl(); private List<Area> listarea = new ArrayList<Area>(); public FileImpDBServlet() { super(); } public void destroy() { super.destroy(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); // 设置字符编码为UTF-8, 这样支持汉字显示 response.setCharacterEncoding("UTF-8"); // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload DiskFileItemFactory dfif = new DiskFileItemFactory(); dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘 dfif.setRepository(new File(request.getRealPath("/") + "uploadtemp"));// 设置存放临时文件的目录,web根目录下的uploadtemp目录 // 用以上工厂实例化上传组件 ServletFileUpload sfu = new ServletFileUpload(dfif); // 设置最大上传尺寸 sfu.setSizeMax(MAX_SIZE); PrintWriter out = response.getWriter(); // 从request得到 所有 上传域的列表 List fileList = null; try { fileList = sfu.parseRequest(request); } catch (FileUploadException e) {// 处理文件尺寸过大异常 if (e instanceof SizeLimitExceededException) { // out.println("[{message:'文件尺寸超过规定大小:"+MAX_SIZE+"字节'}]"); out.println("[{message:'文件尺寸超过规定大小请导入50M以内的文件!'}]"); return; } e.printStackTrace(); } // 没有文件上传 if (fileList == null || fileList.size() == 0) { out.println("[{message:'请选择文件进行导入'}]"); return; } // 得到所有上传的文件 Iterator fileItr = fileList.iterator(); // 循环处理所有文件 while (fileItr.hasNext()) { FileItem fileItem = null; String path = null; long size = 0; // 得到当前文件 fileItem = (FileItem) fileItr.next(); // 忽略简单form字段而不是上传域的文件域(<input type="text" />等) if (fileItem == null || fileItem.isFormField()) { continue; } // 得到文件的完整路径 path = fileItem.getName(); // 得到文件的大小 size = fileItem.getSize(); if ("".equals(path) || size == 0) { out.println("[{message:'请选择文件进行导入'}]"); return; } // 得到去除路径的文件名 String t_name = path.substring(path.lastIndexOf("\\") + 1); // 得到文件的扩展名(无扩展名时将得到全名) String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1); // 拒绝接受规定文件格式之外的文件类型 int allowFlag = 0; int allowedExtCount = allowtype.length; for (; allowFlag < allowedExtCount; allowFlag++) { if (allowtype[allowFlag].equals(t_ext)) break; } if (allowFlag == allowedExtCount) { String message = ""; for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++){ message+="*." + allowtype[allowFlag] + " "; } out.println("[{message:'请导入以下类型的文件"+message+"'}]"); return; } long now = System.currentTimeMillis(); // 根据系统时间生成上传后保存的文件名 String prefix = String.valueOf(now); // StringBuffer sb = new StringBuffer(); String basepath = request.getRealPath("/") + "upload/"; // 保存的最终文件完整路径,保存在web根目录下的upload目录下 //----------------------- //Integer areaid = Integer.parseInt(request.getParameter("areaid")); // listarea = areaimpl.selectSupareaById(areaid); // for (Area area : listarea) { // sb.append(area.getId()+"/"); // } // System.out.println(sb.toString()); Manager admin = (Manager)request.getSession().getAttribute("currManager"); String u_name = basepath+ admin.getUsername() + "." + t_ext; //原来的文件名 File u_name2 = new File(u_name); // u_name2.getParentFile().mkdirs(); //------------------------------- //path=request.getRealPath("/") + "upload/"+path; String filename="upload/"+ prefix + "." + t_ext; try { // 保存文件 fileItem.write(u_name2); //此行代码是根据传来路径通过poi方式读取excel并放入数组中,一行行插入数据库中。 //第一个参数为文件路径,第二个为工作簿名称,第三个为要插入的表名称 if(ExcelToOracleForImp.excelToOracleForImp(u_name,"lawpeople","lawpeople")) { if(ExcelToOracleForImp.excelToOracleForImp(u_name,"change","change")) { response.setStatus(200); out.println("[{message:\"操作成功.\"},{imagepath:\""+filename+"\"}]"); } else { out.println("[{message:\"操作失败.\"},{imagepath:\""+filename+"\"}]"); } } else { out.println("[{message:\"操作失败.\"},{imagepath:\""+filename+"\"}]"); } } catch (Exception e) { e.printStackTrace(); } } } }
excelToOracleForImp.java
package com.future.zfs.util; import java.io.File; import java.io.FileInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelToOracleForImp { /** * * @param filename * @return * @author xushigang * 此方法是读取上传过来的excel并解析 */ public static boolean excelToOracleForImp(String filename,String sheetname,String tablename) { File f = new File(filename); try { FileInputStream is = new FileInputStream(f); HSSFWorkbook wbs = new HSSFWorkbook(is); // HSSFSheet childSheet = wbs.getSheetAt(sheetname); HSSFSheet childSheet = wbs.getSheet(sheetname); //System.out.println(childSheet.getPhysicalNumberOfRows()); // System.out.println("有行数" + childSheet.getLastRowNum()); String[] ArrayExcelRow = new String[childSheet.getRow(0).getLastCellNum()]; String[] headtitle = new String[childSheet.getRow(0).getLastCellNum()]; for (int i = 0; i < childSheet.getPhysicalNumberOfRows(); i++) { System.out.println(childSheet.getPhysicalNumberOfRows()); HSSFRow row = childSheet.getRow(i); // System.out.println("有列数" + row.getLastCellNum()); if (null != row) { for (int j = 0; j < row.getLastCellNum(); j++) { HSSFCell cell = row.getCell(j); if (null != cell) { if(i==0) { headtitle[j] = cell.getStringCellValue(); // System.out // .println(headtitle[j]); } else { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_NUMERIC: // 数字 if (HSSFDateUtil.isCellDateFormatted(cell)) { Date d = cell.getDateCellValue(); DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ArrayExcelRow[j] = "to_date('"+formater.format(d)+"','yyyy-mm-dd hh24:mi:ss')"; } else{ ArrayExcelRow[j] = String.valueOf((int)cell.getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_STRING: // 字符串 ArrayExcelRow[j] = "'"+cell.getStringCellValue()+"'"; break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean ArrayExcelRow[j] = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: // 公式 ArrayExcelRow[j] = String.valueOf(cell.getCellFormula()); break; case HSSFCell.CELL_TYPE_BLANK: // 空值 ArrayExcelRow[j] = ""; break; case HSSFCell.CELL_TYPE_ERROR: // 故障 ArrayExcelRow[j] = ""; break; default: System.out.print("未知类型 "); break; } } } else { System.out.print(""); } } if(i!=0&&ArrayExcelRow[1]!=""&&ArrayExcelRow[1]!=null) { System.out.println("---这是存储代码--"); new InsertIntoOracle().save(headtitle, ArrayExcelRow,tablename); } } //System.out.println(); } return true; } catch (Exception e) { return false; // e.printStackTrace(); } } }
InsertIntoOracle.java
package com.future.zfs.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.apache.log4j.Logger; import com.future.zfs.dao.impl.AreaDaoImpl; import com.future.zfs.db.BaseDao; import com.future.zfs.db.TransactionUtil; import com.future.zfs.exception.TransactionException; /** * * @author xushigang *此方法是读取excel并计息之后存入数据库的方法 */ public class InsertIntoOracle extends BaseDao{ private Connection conn; private PreparedStatement pstmt; private Statement stmt; public ResultSet res; public static final Logger logger = Logger.getLogger(AreaDaoImpl.class); public boolean save(String[] headtitle,String[] ExcelBody,String table) { try { StringBuffer sql = new StringBuffer(); StringBuffer forargs = new StringBuffer(); sql.append("insert into "+table+"("); for (int i = 1; i < headtitle.length; i++) { // System.out.println(i); if(i==headtitle.length-1) { sql.append(headtitle[i]); // System.out.println(headtitle[i]); } else {//此处是过滤掉id这一列,数据库中不需要插入id了有数据库自己实现即可。 sql.append(headtitle[i]+","); // System.out.println(headtitle[i]); } } // sql.append(") values(?,?,?,?,?,?,?,?,?,?"); // sql.append(",?,?,?,?,?,?,?,?,?,?"); // sql.append(",?,?,?,?,?,?,?,?,?,?"); // sql.append(",?,?,?,?,?,?,?,?,?,?"); // sql.append(",?,?,?,?,?,?,?,?,?)"); // String[] args = new String[49]; // for (int i = 1; i < ExcelBody.length; i++) { // args[i-1] = ExcelBody[i]; // } // System.out.println(sql.toString()+"==================="); for (int i = 1; i < ExcelBody.length; i++) { if(i==ExcelBody.length-1) { forargs.append(ExcelBody[i]); } else { forargs.append(ExcelBody[i]+","); // System.out.println(ExcelBody[i]+","); } } sql.append(") values("); sql.append(forargs.toString()); sql.append(")"); System.out.println(sql.toString()+"==================="); int n = this.executeUpdate(sql.toString(), null); return n == 1 ? true : false; } catch (Exception e) { logger.info("本模块为数据导入模块,向数据库插入数据出错!异常的原因是:"+ e.getMessage(), e.fillInStackTrace()); throw new TransactionException( "本模块为数据导入模块,向数据库插入数据出错!异常的原因是:"+ e.getMessage(), e.fillInStackTrace()); } finally { this.closeRes(); this.closePstmt(); try { this.conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public int executeUpdate(String sql, String[] args) { int result = 0; try { conn = TransactionUtil.getConnection(); if(conn.getAutoCommit()){ conn.setAutoCommit(false); } pstmt = conn.prepareStatement(sql); if(args!=null && args.length>0){ for(int i=0;i<args.length;i++){ pstmt.setString(i+1, args[i]); } } result = pstmt.executeUpdate(); conn.commit(); } catch (SQLException e) { logger.info("本模块为数据导入模块,向数据库插入数据出错!"); throw new TransactionException(e.getMessage(),e); }finally{ this.closePstmt(); } return result; } }
界面如下:
注意:只要你弄一份与数据库字段对应的excel就可以了,excel里要定义工作簿的名字,因为你要解析excel里面的工作簿。
注意:下面的代码说明了参数都是什么!
//此行代码是根据传来路径通过poi方式读取excel并放入数组中,一行行插入数据库中。 //第一个参数为文件路径,第二个为工作簿名称,第三个为要插入的表名称 if(ExcelToOracleForImp.excelToOracleForImp(u_name,"lawpeople","lawpeople")) { if(ExcelToOracleForImp.excelToOracleForImp(u_name,"change","change")) { response.setStatus(200); out.println("[{message:\"操作成功.\"},{imagepath:\""+filename+"\"}]"); } else { out.println("[{message:\"操作失败.\"},{imagepath:\""+filename+"\"}]"); } } else { out.println("[{message:\"操作失败.\"},{imagepath:\""+filename+"\"}]"); }
好了,写了一堆,希望对大家有帮助,有问题可以留言啊!!!