POI 导入导出Excel文件到数据库 亲测
来源:互联网 发布:淘宝退货的联系电话 编辑:程序博客网 时间:2024/06/16 19:18
1.导入相应的poi jar包,我用的是3.7;
2.导入Excel文件到数据的类(这里我把解析Excel文件的操作封装成一个类,在action中只要调用该类就可以了):
- /**
- * POI:解析Excel文件中的数据并把每行数据封装成一个实体
- * @param fis 文件输入流
- * @return List<EmployeeInfo> Excel中数据封装实体的集合
- */
- public static List<EmployeeInfo> importEmployeeByPoi(InputStream fis) {
- List<EmployeeInfo> infos = new ArrayList<EmployeeInfo>();
- EmployeeInfo employeeInfo = null;
- try {
- //创建Excel工作薄
- HSSFWorkbook hwb = new HSSFWorkbook(fis);
- //得到第一个工作表
- HSSFSheet sheet = hwb.getSheetAt(0);
- HSSFRow row = null;
- //日期格式化
- DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
- //遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数
- for(int i = 0; i < hwb.getNumberOfSheets(); i++) {
- sheet = hwb.getSheetAt(i);
- //遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数
- for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {
- row = sheet.getRow(j);
- employeeInfo = new EmployeeInfo();
- /*此方法规定Excel文件中的数据必须为文本格式,所以在解析数据的时候未进行判断
- //方法1:Excel解析出来的数字为double类型,要转化为Long类型必须做相应的处理(一开始用的方法,比较笨。)
- //先把解析出来的double类型转化为String类型,然后截取String类型'.'以前的字符串,最后把字符串转化为Long类型。
- String orgId = row.getCell(0).toString();
- String orgId1 = orgId.substring(0, orgId.indexOf('.'));
- //方法2:其实double类型可以通过(long)Double这样直接转化为Long类型。
- employeeInfo.setOrgId((long)(row.getCell(0).getNumericCellValue()));
- employeeInfo.setEmployeeNumber(row.getCell(1).toString());
- employeeInfo.setFullName(row.getCell(2).toString());
- employeeInfo.setSex(row.getCell(3).toString());
- if(row.getCell(4) != null) {
- try {
- employeeInfo.setDateOfBirth(ft.parse(row.getCell(4).toString()));
- } catch (ParseException e) {
- e.printStackTrace();
- }
- }
- employeeInfo.setTownOfBirth(row.getCell(5).toString());
- employeeInfo.setNationalIdentifier(row.getCell(6).toString());*/
- //此方法调用getCellValue(HSSFCell cell)对解析出来的数据进行判断,并做相应的处理
- if(ImportEmployee.getCellValue(row.getCell(0)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(0)))) {
- employeeInfo.setOrgId(Long.valueOf(ImportEmployee.getCellValue(row.getCell(0))));
- }
- employeeInfo.setEmployeeNumber(ImportEmployee.getCellValue(row.getCell(1)));
- employeeInfo.setFullName(ImportEmployee.getCellValue(row.getCell(2)));
- employeeInfo.setSex(ImportEmployee.getCellValue(row.getCell(3)));
- if(ImportEmployee.getCellValue(row.getCell(4)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(4)))) {
- try {
- employeeInfo.setDateOfBirth(ft.parse(ImportEmployee.getCellValue(row.getCell(4))));
- } catch (ParseException e) {
- e.printStackTrace();
- }
- employeeInfo.setTownOfBirth(ImportEmployee.getCellValue(row.getCell(5)));
- }
- employeeInfo.setNationalIdentifier(ImportEmployee.getCellValue(row.getCell(6)));
- infos.add(employeeInfo);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return infos;
- }
- //判断从Excel文件中解析出来数据的格式
- private static String getCellValue(HSSFCell cell){
- String value = null;
- //简单的查检列类型
- switch(cell.getCellType())
- {
- case HSSFCell.CELL_TYPE_STRING://字符串
- value = cell.getRichStringCellValue().getString();
- break;
- case HSSFCell.CELL_TYPE_NUMERIC://数字
- long dd = (long)cell.getNumericCellValue();
- value = dd+"";
- break;
- case HSSFCell.CELL_TYPE_BLANK:
- value = "";
- break;
- case HSSFCell.CELL_TYPE_FORMULA:
- value = String.valueOf(cell.getCellFormula());
- break;
- case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值
- value = String.valueOf(cell.getBooleanCellValue());
- break;
- case HSSFCell.CELL_TYPE_ERROR:
- value = String.valueOf(cell.getErrorCellValue());
- break;
- default:
- break;
- }
- return value;
- }
/** * POI:解析Excel文件中的数据并把每行数据封装成一个实体 * @param fis 文件输入流 * @return List<EmployeeInfo> Excel中数据封装实体的集合 */public static List<EmployeeInfo> importEmployeeByPoi(InputStream fis) {List<EmployeeInfo> infos = new ArrayList<EmployeeInfo>();EmployeeInfo employeeInfo = null;try {//创建Excel工作薄HSSFWorkbook hwb = new HSSFWorkbook(fis);//得到第一个工作表HSSFSheet sheet = hwb.getSheetAt(0);HSSFRow row = null;//日期格式化DateFormat ft = new SimpleDateFormat("yyyy-MM-dd");//遍历该表格中所有的工作表,i表示工作表的数量 getNumberOfSheets表示工作表的总数 for(int i = 0; i < hwb.getNumberOfSheets(); i++) {sheet = hwb.getSheetAt(i);//遍历该行所有的行,j表示行数 getPhysicalNumberOfRows行的总数for(int j = 1; j < sheet.getPhysicalNumberOfRows(); j++) {row = sheet.getRow(j);employeeInfo = new EmployeeInfo();/*此方法规定Excel文件中的数据必须为文本格式,所以在解析数据的时候未进行判断 //方法1:Excel解析出来的数字为double类型,要转化为Long类型必须做相应的处理(一开始用的方法,比较笨。)//先把解析出来的double类型转化为String类型,然后截取String类型'.'以前的字符串,最后把字符串转化为Long类型。String orgId = row.getCell(0).toString();String orgId1 = orgId.substring(0, orgId.indexOf('.'));//方法2:其实double类型可以通过(long)Double这样直接转化为Long类型。employeeInfo.setOrgId((long)(row.getCell(0).getNumericCellValue()));employeeInfo.setEmployeeNumber(row.getCell(1).toString());employeeInfo.setFullName(row.getCell(2).toString());employeeInfo.setSex(row.getCell(3).toString());if(row.getCell(4) != null) {try {employeeInfo.setDateOfBirth(ft.parse(row.getCell(4).toString()));} catch (ParseException e) {e.printStackTrace();}}employeeInfo.setTownOfBirth(row.getCell(5).toString());employeeInfo.setNationalIdentifier(row.getCell(6).toString());*///此方法调用getCellValue(HSSFCell cell)对解析出来的数据进行判断,并做相应的处理if(ImportEmployee.getCellValue(row.getCell(0)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(0)))) {employeeInfo.setOrgId(Long.valueOf(ImportEmployee.getCellValue(row.getCell(0))));}employeeInfo.setEmployeeNumber(ImportEmployee.getCellValue(row.getCell(1)));employeeInfo.setFullName(ImportEmployee.getCellValue(row.getCell(2)));employeeInfo.setSex(ImportEmployee.getCellValue(row.getCell(3)));if(ImportEmployee.getCellValue(row.getCell(4)) != null && !"".equals(ImportEmployee.getCellValue(row.getCell(4)))) {try {employeeInfo.setDateOfBirth(ft.parse(ImportEmployee.getCellValue(row.getCell(4))));} catch (ParseException e) {e.printStackTrace();}employeeInfo.setTownOfBirth(ImportEmployee.getCellValue(row.getCell(5)));}employeeInfo.setNationalIdentifier(ImportEmployee.getCellValue(row.getCell(6)));infos.add(employeeInfo);}}} catch (IOException e) {e.printStackTrace();}return infos;}//判断从Excel文件中解析出来数据的格式private static String getCellValue(HSSFCell cell){ String value = null; //简单的查检列类型 switch(cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING://字符串 value = cell.getRichStringCellValue().getString(); break; case HSSFCell.CELL_TYPE_NUMERIC://数字 long dd = (long)cell.getNumericCellValue(); value = dd+""; break; case HSSFCell.CELL_TYPE_BLANK: value = ""; break; case HSSFCell.CELL_TYPE_FORMULA: value = String.valueOf(cell.getCellFormula()); break; case HSSFCell.CELL_TYPE_BOOLEAN://boolean型值 value = String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_ERROR: value = String.valueOf(cell.getErrorCellValue()); break; default: break; } return value; }
action中的写法:
因为是做练习,只是熟悉它的用法,这里做的比较简单。
- //从页面接收参数:文件的路径
- String excelPath = request.getParameter("excelPath");
- //输入流
- InputStream fis = new FileInputStream(excelPath);
- //JXL:得到解析Excel的实体集合
- // List<EmployeeInfo> infos = ImportEmployee.importEmployee(fis);
- //POI:得到解析Excel的实体集合
- List<EmployeeInfo> infos = ImportEmployee.importEmployeeByPoi(fis);
- //遍历解析Excel的实体集合
- for(EmployeeInfo info:infos) {
- //判断员工编号是否存在(存在:做修改操作;不存在:做新增操作)
- EmployeeInfo info1 = this.selectEmpByEmpNum(info.getEmployeeNumber());
- if(info1 == null) {
- //把实体新加到数据库中
- this.service.addEmployeeInfo(info);
- }else{
- //把personId封装到实体
- info.setPersonId(info1.getPersonId());
- //更新实体
- this.updatEmployeeInfo(info);
- }
- }
- //关闭流
- fis.close();
//从页面接收参数:文件的路径String excelPath = request.getParameter("excelPath");//输入流InputStream fis = new FileInputStream(excelPath);//JXL:得到解析Excel的实体集合// List<EmployeeInfo> infos = ImportEmployee.importEmployee(fis);//POI:得到解析Excel的实体集合List<EmployeeInfo> infos = ImportEmployee.importEmployeeByPoi(fis);//遍历解析Excel的实体集合for(EmployeeInfo info:infos) {//判断员工编号是否存在(存在:做修改操作;不存在:做新增操作)EmployeeInfo info1 = this.selectEmpByEmpNum(info.getEmployeeNumber());if(info1 == null) {//把实体新加到数据库中this.service.addEmployeeInfo(info);}else{//把personId封装到实体info.setPersonId(info1.getPersonId());//更新实体this.updatEmployeeInfo(info);}}//关闭流fis.close();
为了整个导入的完整性,最后附上jsp页面的代码:
- <input type="file" id="excelPath" name="excelPath"/>
- <input type="button" value="导入Excel" onclick="importEmp()"/>
- -----------------------JS对导入的文件做简单的判断------------------------
- //Excel文件导入到数据库中
- function importEmp(){
- //检验导入的文件是否为Excel文件
- var excelPath = document.getElementById("excelPath").value;
- if(excelPath == null || excelPath == ''){
- alert("请选择要上传的Excel文件");
- return;
- }else{
- var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();
- if(fileExtend == '.xls'){
- }else{
- alert("文件格式需为'.xls'格式");
- return;
- }
- }
- //提交表单
- document.getElementById("empForm").action="<%=request.getContextPath()%>/EmpExcel.action.EmpExcelAction.do?method=importEmployeeInfos";
- document.getElementById("empForm").submit();
- }
<input type="file" id="excelPath" name="excelPath"/> <input type="button" value="导入Excel" onclick="importEmp()"/>-----------------------JS对导入的文件做简单的判断------------------------//Excel文件导入到数据库中function importEmp(){//检验导入的文件是否为Excel文件var excelPath = document.getElementById("excelPath").value;if(excelPath == null || excelPath == ''){alert("请选择要上传的Excel文件");return;}else{var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase(); if(fileExtend == '.xls'){}else{alert("文件格式需为'.xls'格式"); return;}}//提交表单document.getElementById("empForm").action="<%=request.getContextPath()%>/EmpExcel.action.EmpExcelAction.do?method=importEmployeeInfos"; document.getElementById("empForm").submit();}
到此为止就是导入Excel文件的所有代码。
3.导出为Excel文件:
- /**
- * POI : 导出数据,存放于Excel中
- * @param os 输出流 (action: OutputStream os = response.getOutputStream();)
- * @param employeeInfos 要导出的数据集合
- */
- public static void exportEmployeeByPoi(OutputStream os, List<EmployeeInfo> employeeInfos) {
- try {
- //创建Excel工作薄
- HSSFWorkbook book = new HSSFWorkbook();
- //在Excel工作薄中建一张工作表
- HSSFSheet sheet = book.createSheet("员工信息");
- //设置单元格格式(文本)
- //HSSFCellStyle cellStyle = book.createCellStyle();
- //第一行为标题行
- HSSFRow row = sheet.createRow(0);//创建第一行
- HSSFCell cell0 = row.createCell(0);
- HSSFCell cell1 = row.createCell(1);
- HSSFCell cell2 = row.createCell(2);
- HSSFCell cell3 = row.createCell(3);
- HSSFCell cell4 = row.createCell(4);
- //定义单元格为字符串类型
- cell0.setCellType(HSSFCell.CELL_TYPE_STRING);
- cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
- cell2.setCellType(HSSFCell.CELL_TYPE_STRING);
- cell3.setCellType(HSSFCell.CELL_TYPE_STRING);
- cell4.setCellType(HSSFCell.CELL_TYPE_STRING);
- //在单元格中输入数据
- cell0.setCellValue("员工编号");
- cell1.setCellValue("员工姓名");
- cell2.setCellValue("员工性别");
- cell3.setCellValue("出生日期");
- cell4.setCellValue("身份证号");
- //循环导出数据到excel中
- for(int i = 0; i < employeeInfos.size(); i++) {
- EmployeeInfo employeeInfo = employeeInfos.get(i);
- //创建第i行
- HSSFRow rowi = sheet.createRow(i + 1);
- //在第i行的相应列中加入相应的数据
- rowi.createCell(0).setCellValue(employeeInfo.getEmployeeNumber());
- rowi.createCell(1).setCellValue(employeeInfo.getFullName());
- //处理性别(M:男 F:女)
- String sex = null;
- if("M".equals(employeeInfo.getSex())) {
- sex = "男";
- }else {
- sex = "女";
- }
- rowi.createCell(2).setCellValue(sex);
- //对日期的处理
- if(employeeInfo.getDateOfBirth() != null && !"".equals(employeeInfo.getDateOfBirth())){
- java.text.DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
- rowi.createCell(3).setCellValue(format1.format(employeeInfo.getDateOfBirth()));
- }
- rowi.createCell(4).setCellValue(employeeInfo.getNationalIdentifier());
- }
- //写入数据 把相应的Excel 工作簿存盘
- book.write(os);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
/** * POI : 导出数据,存放于Excel中 * @param os 输出流 (action: OutputStream os = response.getOutputStream();) * @param employeeInfos 要导出的数据集合 */public static void exportEmployeeByPoi(OutputStream os, List<EmployeeInfo> employeeInfos) {try {//创建Excel工作薄HSSFWorkbook book = new HSSFWorkbook();//在Excel工作薄中建一张工作表HSSFSheet sheet = book.createSheet("员工信息");//设置单元格格式(文本)//HSSFCellStyle cellStyle = book.createCellStyle();//第一行为标题行HSSFRow row = sheet.createRow(0);//创建第一行HSSFCell cell0 = row.createCell(0);HSSFCell cell1 = row.createCell(1);HSSFCell cell2 = row.createCell(2);HSSFCell cell3 = row.createCell(3);HSSFCell cell4 = row.createCell(4);//定义单元格为字符串类型cell0.setCellType(HSSFCell.CELL_TYPE_STRING);cell1.setCellType(HSSFCell.CELL_TYPE_STRING);cell2.setCellType(HSSFCell.CELL_TYPE_STRING);cell3.setCellType(HSSFCell.CELL_TYPE_STRING);cell4.setCellType(HSSFCell.CELL_TYPE_STRING);//在单元格中输入数据cell0.setCellValue("员工编号");cell1.setCellValue("员工姓名");cell2.setCellValue("员工性别");cell3.setCellValue("出生日期");cell4.setCellValue("身份证号");//循环导出数据到excel中for(int i = 0; i < employeeInfos.size(); i++) {EmployeeInfo employeeInfo = employeeInfos.get(i);//创建第i行HSSFRow rowi = sheet.createRow(i + 1);//在第i行的相应列中加入相应的数据rowi.createCell(0).setCellValue(employeeInfo.getEmployeeNumber());rowi.createCell(1).setCellValue(employeeInfo.getFullName());//处理性别(M:男 F:女)String sex = null;if("M".equals(employeeInfo.getSex())) {sex = "男";}else {sex = "女";}rowi.createCell(2).setCellValue(sex);//对日期的处理if(employeeInfo.getDateOfBirth() != null && !"".equals(employeeInfo.getDateOfBirth())){java.text.DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");rowi.createCell(3).setCellValue(format1.format(employeeInfo.getDateOfBirth()));}rowi.createCell(4).setCellValue(employeeInfo.getNationalIdentifier());}//写入数据 把相应的Excel 工作簿存盘book.write(os);} catch (IOException e) {e.printStackTrace();}}
action代码和导入的相似这里就不再进行赘述。
- POI 导入导出Excel文件到数据库
- POI 导入导出Excel文件到数据库
- POI 导入导出Excel文件到数据库 亲测
- POI 导入导出Excel文件到数据库(转载)
- POI 导入导出Excel文件到数据库(转载)
- POI导入导出Excel到数据库
- POI Excel 导入导出数据库
- POI 读取excel导入导出数据到数据库
- 使用poi导入excel文件数据到数据库
- java中用poi导入excel文件到数据库总结
- POI文件excel文件导入导出
- 使用POI导入和导出 Excel文件
- 使用POI导入和导出Excel文件
- 使用POI导入和导出Excel文件
- 使用POI导入和导出Excel文件
- 利用POI导入和导出excel文件
- Poi对Excel文件的导入导出
- 简易使用POI导入导出excel文件
- nginx 配置
- NoSQL在腾讯的应用实践
- vim教程
- 例解GNU C之零长数组与变长数组
- Android系统Wifi移植
- POI 导入导出Excel文件到数据库 亲测
- 例解GNU C之指定初始化项目
- flex拖动技术汇总
- 例解GNU C之typeof
- php100视频之Ajax+PHP检查用户名或邮件(三)【50】
- AIX常用命令
- demo02_GIF
- Hadoop若干操作提示
- what is underdetermined linear system