当前位置:   article > 正文

excel文件导入或导出Java代码示例_java excel导出接口

java excel导出接口

1、excel文件导入

controller层接口内容

 service层代码

 

 serviceImpl内代码内容

  1. @Override
  2. @Transactional(rollbackFor = Exception.class)
  3. public void importCheckItemExcel(MultipartFile file, Long checkPkgId) throws Exception {
  4. if (file.isEmpty()){
  5. throw new IOException("请选择上传文件");
  6. }
  7. Workbook work = this.getWorkbook(file);
  8. if (null == work) {
  9. throw new HolliException(DeviceExceptionEnum.EXCEL_IS_NULL_EXCEPTION);
  10. }
  11. Iterator<Sheet> sheetIterator = work.sheetIterator();
  12. while (sheetIterator.hasNext()) {
  13. Sheet sheet = sheetIterator.next();
  14. if (sheet == null) {
  15. return;
  16. }
  17. //先获取首列标题
  18. Map<String, Integer> validColumns = new HashMap<>();
  19. List<String> headerCells = getFirstRow(sheet, 0);
  20. if (headerCells == null) {
  21. return;
  22. }
  23. for (int i = 0; i < headerCells.size(); i++) {
  24. Object header = headerCells.get(i);
  25. if (header == null) {
  26. continue;
  27. }
  28. if (ObjectUtil.contains(header, "修程")) {
  29. // validColumns.put("checkLevel", i);//数字
  30. validColumns.put("checkLevelName", i);//含义
  31. }else if (ObjectUtil.contains(header, "工作项目")) {
  32. validColumns.put("checkName", i);
  33. }else if (ObjectUtil.contains(header, "单位")) {
  34. // validColumns.put("checkUnit", i);//数字
  35. validColumns.put("checkUnitName", i);//含义
  36. }else if (ObjectUtil.contains(header, "周期")) {
  37. validColumns.put("checkCycle", i);
  38. }else if (ObjectUtil.contains(header, "工作内容及标准")) {
  39. validColumns.put("checkContent", i);
  40. }else if (ObjectUtil.contains(header, "ATP型号")) {
  41. validColumns.put("atpModel", i);
  42. }
  43. }
  44. //标题集合
  45. if (validColumns.size() == 0) {
  46. return;
  47. }
  48. Map<String, Object> map = new HashMap<String, Object>();
  49. //遍历当前sheet中的所有行
  50. //包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部
  51. for (int j = 1; j <= sheet.getLastRowNum(); j++) {
  52. //读取一行
  53. List<Object> rows = getRow(sheet, j);
  54. if (rows == null) {
  55. continue;
  56. }
  57. Set<String> keySet = validColumns.keySet();
  58. for (String key : keySet) {
  59. int col_index = validColumns.get(key);
  60. if (col_index >= rows.size()) {
  61. continue;
  62. }
  63. Object cell = rows.get(col_index);
  64. map.put(key, cell);
  65. }
  66. //取出对应属性及值内容 以便存储数据库
  67. //业务逻辑,数据存储
  68. DevCheckItemVo devCheckItemVo = new DevCheckItemVo();
  69. BeanUtil.copyProperties(map, devCheckItemVo);
  70. this.insertDevCheckItem(checkPkgId, devCheckItemVo, j + 1);
  71. }
  72. }
  73. }

 判断excel的格式,同时兼容2003和2007

  1. protected final static String excel2003L = ".xls"; //2003- 版本的excel
  2. protected final static String excel2007U = ".xlsx"; //2007+ 版本的excel
  3. /**
  4. * 描述:根据文件后缀,自适应上传文件的版本
  5. */
  6. public static Workbook getWorkbook(MultipartFile file) throws Exception {
  7. Workbook wb = null;
  8. InputStream is = file.getInputStream();
  9. String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
  10. if (excel2003L.equals(fileType)) {
  11. wb = new XSSFWorkbook(is); //2007+
  12. // 因HSSFWorkbook报(You need to call a different part of POI to process this data (eg XSSF instead of HSSF)),故直接使用XSSFWorkbook处理
  13. // wb = new HSSFWorkbook(is); //2003-
  14. } else if (excel2007U.equals(fileType)) {
  15. wb = new XSSFWorkbook(is); //2007+
  16. } else {
  17. throw new IOException("解析的文件格式有误!");
  18. }
  19. return wb;
  20. }

 获取行数据

  1. /**
  2. * 获取行数据
  3. * @param sheet
  4. * @param rowIndex
  5. * @return
  6. */
  7. public List<Object> getRow(Sheet sheet, int rowIndex) {
  8. List<Object> li = new ArrayList<Object>();
  9. if (sheet == null) {
  10. return null;
  11. }
  12. Row row = null;
  13. Cell cell = null;
  14. //读取一行
  15. row = sheet.getRow(rowIndex);
  16. //去掉空行和表头
  17. if (row == null) {
  18. return null;
  19. }
  20. /**为去掉空行,若第一列为空,则直接跳过该行*/
  21. if (ObjectUtil.isEmpty(row.getCell(0))) {
  22. return null;
  23. }
  24. //遍历所有的列
  25. for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
  26. cell = row.getCell(y);
  27. li.add(this.getCellFormatValue(cell));
  28. }
  29. return li;
  30. }

 //获取excel列表内的对应数据格式

  1. //获取excel列表内的对应数据格式
  2. protected Object getCellFormatValue(Cell cell) {
  3. Object val = "";
  4. if (null != cell) {
  5. if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA)
  6. {
  7. val = cell.getNumericCellValue();
  8. if (DateUtil.isCellDateFormatted(cell))
  9. {
  10. val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
  11. }
  12. else
  13. {
  14. if ((Double) val % 1 != 0)
  15. {
  16. val = new BigDecimal(val.toString());
  17. }
  18. else
  19. {
  20. val = new DecimalFormat("0").format(val);
  21. }
  22. }
  23. }
  24. else if (cell.getCellType() == CellType.STRING)
  25. {
  26. val = cell.getStringCellValue();
  27. }
  28. else if (cell.getCellType() == CellType.BOOLEAN)
  29. {
  30. val = cell.getBooleanCellValue();
  31. }
  32. else if (cell.getCellType() == CellType.ERROR)
  33. {
  34. val = cell.getErrorCellValue();
  35. }
  36. } else {
  37. val = "";
  38. }
  39. return val;
  40. }

 2、excel导出

controller层接口内容

  service层代码

  serviceImpl内代码内容

  1. @Override
  2. public void exportCheckItemExcel(String strIds, HttpServletResponse response) throws Exception {
  3. List<DevCheckItem> devCheckItemList = new ArrayList<>();
  4. long[] itemIdArray = StrUtil.splitToLong(strIds,",");
  5. //查询检修项id
  6. for (int i = 0; i< itemIdArray.length; i++){
  7. DevCheckItem devCheckItem = this.getById(itemIdArray[i]);
  8. if (ObjectUtil.isNotEmpty(devCheckItem)){
  9. devCheckItemList.add(devCheckItem);
  10. }
  11. }
  12. if (ObjectUtil.isNotEmpty(devCheckItemList) && devCheckItemList.size() > 0){
  13. //导出excel
  14. XSSFWorkbook workbook=new XSSFWorkbook();
  15. //获得名字为sheet的工作本对象,这个是看你的模板工作表的名字
  16. XSSFSheet sheet = workbook.createSheet("sheet1");
  17. // 序号
  18. int serialNo = 1;
  19. //行号
  20. int rowIndex = 1;
  21. //创建表头
  22. XSSFRow row_excel = sheet.createRow(0);
  23. //行业务数据填充
  24. XSSFCell cell = row_excel.createCell(0);
  25. cell.setCellValue("序号");
  26. cell = row_excel.createCell(1);
  27. cell.setCellValue("ATP型号");
  28. cell = row_excel.createCell(2);
  29. cell.setCellValue("修程");
  30. cell = row_excel.createCell(3);
  31. cell.setCellValue("工作项目");
  32. cell = row_excel.createCell(4);
  33. cell.setCellValue("单位");
  34. cell = row_excel.createCell(5);
  35. cell.setCellValue("周期(小时)");
  36. cell = row_excel.createCell(6);
  37. cell.setCellValue("工作内容及标准");
  38. //遍历填充数据
  39. for (DevCheckItem devCheckItem : devCheckItemList){
  40. //获取当前行
  41. row_excel = sheet.getRow(rowIndex);
  42. if (row_excel == null){
  43. //创建行
  44. row_excel = sheet.createRow(rowIndex);
  45. }
  46. //内容填充
  47. if (ObjectUtil.isNotEmpty(devCheckItem)){
  48. XSSFCell cellNew = row_excel.createCell(0);
  49. cellNew.setCellValue(serialNo);
  50. cell = row_excel.createCell(1);
  51. if (ObjectUtil.isNotEmpty(devCheckItem.getAtpModel())){
  52. cell.setCellValue(devCheckItem.getAtpModel());
  53. }
  54. cell = row_excel.createCell(2);
  55. if (ObjectUtil.isNotEmpty(devCheckItem.getCheckLevel())){
  56. String levelName = DevCheckLevelEnum.getLevelNameByType(devCheckItem.getCheckLevel());
  57. cell.setCellValue(levelName);
  58. }
  59. cell = row_excel.createCell(3);
  60. if (ObjectUtil.isNotEmpty(devCheckItem.getCheckName())){
  61. cell.setCellValue(devCheckItem.getCheckName());
  62. }
  63. cell = row_excel.createCell(4);
  64. if (ObjectUtil.isNotEmpty(devCheckItem.getCheckUnit())){
  65. String checkUnit = this.getCheckUnitNameByNum(devCheckItem.getCheckUnit());
  66. cell.setCellValue(checkUnit);
  67. }
  68. cell = row_excel.createCell(5);
  69. if (ObjectUtil.isNotEmpty(devCheckItem.getCheckCycle())){
  70. cell.setCellValue(devCheckItem.getCheckCycle());
  71. }
  72. cell = row_excel.createCell(6);
  73. if (ObjectUtil.isNotEmpty(devCheckItem.getCheckContent())){
  74. cell.setCellValue(devCheckItem.getCheckContent());
  75. }
  76. }
  77. serialNo++;
  78. rowIndex++;
  79. }
  80. response.setCharacterEncoding("UTF-8");
  81. response.setHeader("Content-Type", "application/vnd.ms-excel");
  82. ServletOutputStream out = response.getOutputStream();
  83. workbook.write(out);
  84. }
  85. }

以上已导出完成。

3、以下为可能会用到的导出实例文件,上传文件服务器的过程 

File格式转换MultipartFile格式的例子

//上传minio服务器
String fileName = "检修工作项目.xlsx";
File cacheFile = new File(fileName);
if (cacheFile.exists()) {
    cacheFile.delete();
}
  
cacheFile.createNewFile();//生成文件
OutputStream out = new FileOutputStream(cacheFile);
workbook.write(out);
---------------------------------------------------------------------------------------(上面为导出实例文件)
//下面为上传文件流格式转换的格式。
FileInputStream fileInputStream = new FileInputStream(cacheFile);
MultipartFile multipartFile = new MockMultipartFile("cacheFile", cacheFile.getName(), "text/plain", IOUtils.toByteArray(fileInputStream));

 

-------------------------------------以下无正文-----------------------------------------------------------

注:仅供学习,记录问题和参考,共勉!

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号