Poi导入excel

桃扇骨 2022-04-08 19:42 461阅读 0赞

1.jsp页面

  1. <form action="$\{pageContext.request.contextPath\}/admin/uploadexcel" method="post" enctype="multipart/form-data" id="form2" οnsubmit="return check();">
  2. <table style="table-layout: fixed;" class="tablelist tablelistc">
  3. <tr>
  4. <td colspan="3" style="text-align: center;">
  5. <!-- <input id="upfile" type="file" name="upfile"> -->
  6. <input id="upfile" type="file" name="file">
  7. </td>
  8. </tr>
  9. <tr>
  10. <td colspan="3" style="text-align: center;">
  11. <a href="downhouseexcel?excelName=houseowner">下载Excel导入模版</a><br>
  12. </td>
  13. </tr>
  14. <tr>
  15. <td colspan="3">
  16. <input type="button" name="btn" id="btn" class="share-button-style" value="导入Excel" />
  17. </td>
  18. </tr>
  19. </table>
  20. </form>

2.js

  1. //ajax 方式上传文件操作
  2. $(document).ready(function()\{
  3. $('\#btn').click(function()\{
  4. showMask();
  5. $('\#btn').attr('disabled',"true");
  6. var $this = $(this).val('导入中...');
  7. if(checkData())\{
  8. $('\#form2').ajaxSubmit(\{
  9. url:'ajaxUploadHouseOwnerExcel',
  10. dataType: 'text',
  11. success: resutlMsg,
  12. error: errorMsg
  13. \});
  14. function resutlMsg(msg)\{
  15. alert(msg);
  16. hideMask();
  17. $('\#btn').removeAttr("disabled");
  18. $("\#upfile").val("");
  19. $this.val('导入Excel');
  20. close\_window('importhouseownerdata');
  21. $(".bodyid").mask("正在加载中...");
  22. $("\#formid").submit();
  23. \}
  24. function errorMsg()\{
  25. alert("服务正忙!");
  26. hideMask();
  27. $('\#btn').removeAttr("disabled");
  28. $this.val('导入Excel');
  29. \}
  30. \}
  31. \});
  32. \});
  33. //JS校验form表单信息
  34. function checkData()\{
  35. var fileDir = $("\#upfile").val();
  36. var suffix = fileDir.substr(fileDir.lastIndexOf("."));
  37. if("" == fileDir)\{
  38. alert("选择需要导入的Excel文件!");
  39. hideMask();
  40. $('\#btn').removeAttr("disabled");
  41. $('\#btn').val('导入Excel');
  42. return false;
  43. \}
  44. if(".xls" != suffix && ".xlsx" != suffix )\{
  45. alert("选择Excel格式的文件导入!");
  46. hideMask();
  47. $('\#btn').removeAttr("disabled");
  48. $('\#btn').val('导入Excel');
  49. return false;
  50. \}
  51. return true;
  52. \}

3.controller层

@SuppressWarnings(“unchecked”)
@RequestMapping(value = “/admin/ajaxUploadHouseOwnerExcel”, method = {RequestMethod.GET, RequestMethod.POST })
public void importHouseOwner(
HttpServletRequest request,HttpServletResponse response,HttpSession session)
throws Exception {
response.setCharacterEncoding(“utf-8”);// 防止ajax接受到的中文信息乱码
PrintWriter out = response.getWriter();

  1. MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
  2. InputStream in=null;
  3. MultipartFile file = multipartRequest.getFile("file");
  4. if(file.isEmpty())\{
  5. throw new Exception("文件不存在!");
  6. \}
  7. in = file.getInputStream();
  8. Workbook work = new ImportExcelUtil().getWorkbook(in,file.getOriginalFilename());
  9. List<TblHouseOwner> houseownerList = new ArrayList<TblHouseOwner>();
  10. TblHouseOwner houseOwner = null;
  11. int count = 0;// 业主导入数量
  12. // 得到一个工作表
  13. Sheet sheet = work.getSheetAt(0);
  14. // 获得表头
  15. //Row rowHead = sheet.getRow(0);
  16. // 获得数据的总行数
  17. int totalRowNum = sheet.getLastRowNum();
  18. // 获得所有数据
  19. for (int i = 1; i <= totalRowNum; i++) \{
  20. // 获得第i行对象
  21. Row row = sheet.getRow(i);
  22. if(row.getPhysicalNumberOfCells()!=9)//每一行得到列数
  23. continue;
  24. HSSFDataFormatter dataFormatter = new HSSFDataFormatter();//设置读取小数为整数
  25. // 获得获得第i行第0列的 String类型对象
  26. Cell cell = row.getCell((short) 0);
  27. if(cell.toString().trim().equals("")||cell==null)continue;
  28. houseOwner = new TblHouseOwner();
  29. houseOwner.setOwnerid(WebUtil.getRandUserId());
  30. houseOwner.setOwnername(cell.toString());
  31. cell = row.getCell((short) 1);
  32. if(!isNumeric(cell)||cell==null)continue;
  33. houseOwner.setOwnerphone(cell.toString());
  34. cell = row.getCell((short) 2);
  35. if(!isNumeric(cell)||cell==null)continue;
  36. houseOwner.setIdcard(cell.toString());
  37. cell = row.getCell((short) 3);
  38. if(!isNumeric(cell)||cell==null)continue;
  39. houseOwner.setVid(cell.toString());
  40. cell = row.getCell((short) 4);
  41. if(!isNumeric(cell)||cell==null)continue;
  42. houseOwner.setBuildcode(cell.toString());
  43. cell = row.getCell((short) 5);
  44. if(!isNumeric(cell))continue;
  45. houseOwner.setUnitcode(cell.toString());
  46. cell = row.getCell((short) 6);
  47. if(!isNumeric(cell))continue;
  48. houseOwner.setHousecode(cell.toString());
  49. cell = row.getCell((short) 7);
  50. if(!isNumeric(cell))continue;
  51. houseOwner.setHouseareas(cell.toString());
  52. cell = row.getCell((short) 8);
  53. if(!isNumeric(cell))continue;
  54. houseOwner.setUnitprice(cell.toString());
  55. houseOwner.setMonthpayfee(WebUtil.monthPayfee(houseOwner.getHouseareas(), houseOwner.getUnitprice()));
  56. houseOwner.setYearpayfee(WebUtil.totalPayfee(houseOwner.getHouseareas(), houseOwner.getUnitprice()));
  57. houseOwner.setHousebilldate(WebUtil.getCurrentMonthOneNum());// 获取当月一号
  58. houseownerList.add(houseOwner);
  59. \}
  60. if (houseownerList != null && houseownerList.size() > 0) \{
  61. if (houseownerList.size() > 3000) \{
  62. out.print("很抱歉,您本次导入的业主人数是" + houseownerList.size()+ "人,系统目前最大支持导入3000条数据!");
  63. out.flush();
  64. out.close();
  65. //inputStream.close();
  66. return;
  67. \}
  68. // 批量插入数据库
  69. baseDao.insertBatchDate(houseownerList);
  70. count=houseownerList.size();
  71. \}else \{
  72. out.flush();
  73. out.close();
  74. //inputStream.close();
  75. return;
  76. \}
  77. houseownerList = null;
  78. out.print("导入成功!本次共导入业主" + count + "人");
  79. out.flush();
  80. out.close();
  81. \}

4.工具类

package com.estate.tools;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ImportExcelUtil {
private final static String excel2003L =”.xls”; //2003- 版本的excel
private final static String excel2007U =”.xlsx”; //2007+ 版本的excel

  1. /\*\*
  2. \* 描述:获取IO流中的数据,组装成List<List<Object>>对象
  3. \* @param in,fileName
  4. \* @throws IOException
  5. \*//\*
  6. public List<List<Object>> getBankListByExcel(InputStream in,String fileName) throws Exception\{
  7. List<List<Object>> list = null;
  8. POIFSFileSystem fs = new POIFSFileSystem(in);
  9. HSSFWorkbook work = new HSSFWorkbook(fs);
  10. HSSFSheet sheet= null;
  11. HSSFRow row=null;
  12. Cell cell = null;
  13. //户主 电话 身份证 有无房屋 房屋缴费类型 房屋面积(m²) 房屋单价:m²/元 有无车位 车位费 车位缴费类型 单元(栋)
  14. list = new ArrayList<List<Object>>();
  15. //遍历Excel中所有的sheet
  16. for (int i = 0; i < work.getNumberOfSheets(); i++) \{
  17. sheet = work.getSheetAt(i);
  18. if(sheet==null)\{continue;\}
  19. //遍历当前sheet中的所有行 从第6行开始遍历
  20. for (int j = 6; j <=sheet.getLastRowNum(); j++)\{
  21. row = sheet.getRow(j);
  22. //遍历所有的列 row.getFirstCellNum()
  23. List<Object> li = new ArrayList<Object>();
  24. for (int y =0 ; y < row.getLastCellNum(); y++) \{
  25. if(y>=15) break;
  26. cell = row.getCell(y);
  27. if(cell!=null)
  28. \{
  29. cell.setCellType(Cell.CELL\_TYPE\_STRING);//设置列值类型
  30. if(StringUtils.isEmpty(cell.getStringCellValue().trim().replaceAll(" ", "")))
  31. \{
  32. cell.setCellValue("0");
  33. \}else
  34. \{
  35. cell.setCellValue(cell.getStringCellValue());
  36. \}
  37. li.add(this.getCellValue(cell));
  38. \}
  39. cell=null;
  40. \}
  41. if(li.size()>=15)
  42. \{
  43. list.add(li);
  44. \}
  45. \}
  46. \}
  47. //work.close();
  48. return list;
  49. \} \*/
  50. /\*\*
  51. \* 描述:根据文件后缀,自适应上传文件的版本
  52. \* @param inStr,fileName
  53. \* @return
  54. \* @throws Exception
  55. \*/
  56. public Workbook getWorkbook(InputStream inStr,String fileName) throws Exception\{
  57. Workbook wb = null;
  58. String fileType = fileName.substring(fileName.lastIndexOf("."));
  59. if(excel2003L.equals(fileType))\{
  60. wb = new HSSFWorkbook(inStr); //2003-
  61. \}else if(excel2007U.equals(fileType))\{
  62. wb = new XSSFWorkbook(inStr); //2007+
  63. \}else\{
  64. throw new Exception("解析的文件格式有误!");
  65. \}
  66. return wb;
  67. \}
  68. /\*\*
  69. \* 描述:对表格中数值进行格式化
  70. \* @param cell
  71. \* @return
  72. \*/
  73. public Object getCellValue(Cell cell)\{
  74. Object value = null;
  75. DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
  76. SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
  77. DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
  78. switch (cell.getCellType()) \{
  79. case Cell.CELL\_TYPE\_STRING:
  80. value = cell.getRichStringCellValue().getString();
  81. break;
  82. case Cell.CELL\_TYPE\_NUMERIC:
  83. if("General".equals(cell.getCellStyle().getDataFormatString()))\{
  84. value = df.format(cell.getNumericCellValue());
  85. \}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString()))\{
  86. value = sdf.format(cell.getDateCellValue());
  87. \}else\{
  88. value = df2.format(cell.getNumericCellValue());
  89. \}
  90. break;
  91. case Cell.CELL\_TYPE\_BOOLEAN:
  92. value = cell.getBooleanCellValue();
  93. break;
  94. case Cell.CELL\_TYPE\_BLANK:
  95. value = "";
  96. break;
  97. default:
  98. break;
  99. \}
  100. return value;
  101. \}
  102. public static void main(String\[\] args) \{
  103. \}

}

发表评论

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

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

相关阅读

    相关 poi批量导入excel

    1.先下载poi依赖的包,复制张贴代码一定没有错误 2.直接上代码,如果导入有错误,可能是别人给你发的excel模版有错误,可以自己创建一个excel测试