0
点赞
收藏
分享

微信扫一扫

Kotlin 导出excel表

1、引入所需依赖

implementation 'org.apache.poi:poi:3.17'

2、常用方法介绍

创建.xlsx格式文件对象

workbook = new XSSFWorkbook(inputStream);

创建.xls格式文件对象

workbook = new HSSFWorkbook(inputStream);

获取工作表的对象

Sheet sheetAt = workbook.getSheetAt(0);

获取工作表的行

Row row = sheetAt.getRow(0);

获取实际单元格数

int physicalNumberOfCells = row.getPhysicalNumberOfCells();

获取工作表的单元格

Row.getCell(i);

获得单元格格式

Cell.getCellType();

获取单元格类型

Cell.getBooleanCellValue();//获取布尔类型的单元格
Cell.getNumericCellValue();//获取数字类型的单元格
Cell.getDateCellValue();//获取日期类型的单元格
Cell.getNumericCellValue();//获取数值类型的单元格
Cell.getStringCellValue();//获取字符串类型的单元格

获取实际行数

SheetAt.getPhysicalNumberOfRows();

创建工作表的名字

XSSFSheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("Sheet1"));

创建行

Row row = sheet.createRow(int i);

创建列

Cell cell = row.createCell(int i);

将需要添加到Excel的文本添加到对应的Cell

Cell.setCellValue((String) map.get(j));

将数据写入文件并保存在指定文件夹

OutputStream outputStream = context.getContentResolver().openOutputStream(Uri uri);
XSSFWorkbook.write(outputStream);

3、使用案例

/**
     * 导出Excel
     *
     * @param fileDir         导出文件夹
     * @param fileName        导出文件名
     * @param context         activity上下文
     * @param exportAllResult 导出全部数据或者仅测试过数据
     * @return
     */
fun reportExportExcel(
  fileDir: String,
  fileName: String,
  context: Context,
  exportAllResult: Boolean
): Boolean {
  return try {
    val numberOfSheets = mWorkbook.numberOfSheets
    wb = XSSFWorkbook()
    var sheetNum = 0
    for (sheetIndex in 0 until numberOfSheets) {
      var sheetDataList: ArrayList<ReportSheetData> = ArrayList()
      val sheetName = mWorkbook.getSheetName(sheetIndex)
      if ("不需要的shell" != sheetName) {
        val sheetList = readSpecificSheet(sheetIndex)
        for (i in 0 until (sheetList?.size ?: 0)) {
          var reportSheetData = ReportSheetData()
          reportSheetData.functionDesc = sheetList?.get(i)?.functionDesc.toString()
          reportSheetData.adaptIdStr = sheetList?.get(i)?.adaptIdStr.toString()
          reportSheetData.adaptZoneStr = sheetList?.get(i)?.adaptZoneStr.toString()
          reportSheetData.adaptValueStr = sheetList?.get(i)?.adaptValueStr.toString()
          reportSheetData.setIsSuccess =
          ReportUtils.getHashMap(reportSheetData.functionDesc + ReportUtils._set)
          reportSheetData.getIsSuccess =
          ReportUtils.getHashMap(reportSheetData.functionDesc + ReportUtils._get)
          reportSheetData.callbackIsSuccess =
          ReportUtils.getHashMap(reportSheetData.functionDesc + ReportUtils._callback)
          reportSheetData.owner =
          ReportUtils.getHashMap(reportSheetData.functionDesc + ReportUtils._owner)
          reportSheetData.reasonRemarks =
          ReportUtils.getHashMap(reportSheetData.functionDesc + ReportUtils._reason_remarks)
          
          reportSheetData.testResult =
          when {
            reportSheetData.setIsSuccess == ReportUtils.NoFull || reportSheetData.getIsSuccess == ReportUtils.NoFull || reportSheetData.callbackIsSuccess == ReportUtils.NoFull -> {
              ReportUtils.NoFull
            }

            reportSheetData.setIsSuccess == ReportUtils.NOK || reportSheetData.getIsSuccess == ReportUtils.NOK || reportSheetData.callbackIsSuccess == ReportUtils.NOK -> {
              ReportUtils.NOK
            }

            reportSheetData.setIsSuccess == ReportUtils.NA && reportSheetData.getIsSuccess == ReportUtils.NA && reportSheetData.callbackIsSuccess == ReportUtils.NA -> {
              ReportUtils.NA
            }

            else -> {
              ReportUtils.OK
            }
          }
          if (!exportAllResult && reportSheetData.setIsSuccess == ReportUtils.NoFull && reportSheetData.getIsSuccess == ReportUtils.NoFull && reportSheetData.callbackIsSuccess == ReportUtils.NoFull) continue
          sheetDataList.add(reportSheetData)
        }
        if (exportAllResult || sheetDataList.size > 0) {
          val sheet = wb.createSheet()
          val sheetName = mWorkbook.getSheetName(sheetIndex)
          wb.setSheetName(sheetNum, sheetName)
          sheetNum++
          reportPopulateSheetData(sheet, sheetDataList)
        }
      }
    }
    if (wb.numberOfSheets == 0) {
      wb.createSheet()
    }
    val s = Environment.getExternalStorageDirectory().toString() + "/" + fileDir
    val dir = File(s)
    if (!dir.exists()) {
      dir.mkdirs()
    }
    var excel = File(dir, "$fileName.xlsx")
    if (!excel.exists()) {
      excel.createNewFile()
    }
    LogAct.d(TAG, " 导出路径" + excel.path)
    val fos = FileOutputStream(excel)
    wb.write(fos)
    wb.close()
    fos.flush()
    fos.close()
    true
  } catch (e: Exception) {
    LogAct.e("ExpressExcel", "reportExportExcel=${e}")
    false
  }
}
// 填充数据
private fun reportPopulateSheetData(
  sheet: Sheet,
  sheetDataList: ArrayList<ReportSheetData>
    ) {
  var row = sheet.createRow(0)
  val colNum = reportSheetTitle.size
  for (i in 0 until colNum) {
    val cellStyleTitle = reportSetCellStyle(ReportUtils.TITLE_TYPE)
    sheet.setColumnWidth(i, 20 * 256)
    val cell1 = row.createCell(i)
    cell1.setCellValue(reportSheetTitle[i])
    cell1.cellStyle = cellStyleTitle
  }
  for (rowNum in sheetDataList.indices) {
    row = sheet.createRow(rowNum + 1)
    row.heightInPoints = 28f

    val bean: ReportSheetData = sheetDataList[rowNum]
    for (j in reportSheetTitle.indices) {
      val cell = row.createCell(j)
      var reportCellStyle = reportSetCellStyle(ReportUtils.DEFAULT_TYPE)
      when (j) {
        0 -> {
          cell.setCellValue(bean.functionDesc)
        }

        1 -> {
          cell.setCellValue(bean.adaptIdStr)
        }

        2 -> {
          cell.setCellValue(bean.adaptZoneStr)
        }

        3 -> {
          cell.setCellValue(bean.adaptValueStr)
        }

        4 -> {
          cell.setCellValue(bean.testResult)
          when (bean.testResult) {
            ReportUtils.OK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.OK_TYPE)
            }

            ReportUtils.NOK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NOK_TYPE)
            }

            ReportUtils.NA -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NA_TYPE)
            }

            ReportUtils.NoFull -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NoFull_TYPE)
            }
          }
        }

        5 -> {
          cell.setCellValue(bean.owner)
          when (bean.owner) {
            ReportUtils.VHAL -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.VHAL_TYPE)
            }

            ReportUtils.Middleware -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.MIDDLEWARE_TYPE)
            }

            ReportUtils.SE -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.SE_TYPE)
            }
          }
        }

        6 -> {
          cell.setCellValue(bean.setIsSuccess)
          when (bean.setIsSuccess) {
            ReportUtils.OK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.OK_TYPE)
            }

            ReportUtils.NOK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NOK_TYPE)
            }

            ReportUtils.NA -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NA_TYPE)
            }

            ReportUtils.NoFull -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NoFull_TYPE)
            }
          }
        }

        7 -> {
          cell.setCellValue(bean.getIsSuccess)
          when (bean.getIsSuccess) {
            ReportUtils.OK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.OK_TYPE)
            }

            ReportUtils.NOK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NOK_TYPE)
            }

            ReportUtils.NA -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NA_TYPE)
            }

            ReportUtils.NoFull -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NoFull_TYPE)
            }
          }
        }

        8 -> {
          cell.setCellValue(bean.callbackIsSuccess)
          when (bean.callbackIsSuccess) {
            ReportUtils.OK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.OK_TYPE)
            }

            ReportUtils.NOK -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NOK_TYPE)
            }

            ReportUtils.NA -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NA_TYPE)
            }

            ReportUtils.NoFull -> {
              reportCellStyle = reportSetCellStyle(ReportUtils.NoFull_TYPE)
            }
          }
        }

        9 -> {
          cell.setCellValue(bean.reasonRemarks)
        }
      }
      cell.cellStyle = reportCellStyle
    }
  }
}

private fun reportSetCellStyle(type: Int): CellStyle {
  val reportCellStyle: CellStyle = wb.createCellStyle()
  val cellStyleAt = mWorkbook.getCellStyleAt(0)
  val reportFont = wb.createFont()
  reportCellStyle.cloneStyleFrom(cellStyleAt)
  reportCellStyle.borderLeft = HSSFBorderFormatting.BORDER_THICK
  reportCellStyle.borderRight = HSSFBorderFormatting.BORDER_THICK
  reportCellStyle.borderTop = HSSFBorderFormatting.BORDER_THICK
  reportCellStyle.borderBottom = HSSFBorderFormatting.BORDER_THICK
  reportCellStyle.wrapText = true
  when (type) {
    ReportUtils.DEFAULT_TYPE -> {

    }

    ReportUtils.TITLE_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.SKY_BLUE.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
    }

    ReportUtils.OK_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.GREEN.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.WHITE.index
    }

    ReportUtils.NOK_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.RED.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.WHITE.index
    }

    ReportUtils.NA_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.YELLOW.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.BLACK.index
    }

    ReportUtils.NoFull_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.DARK_YELLOW.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.WHITE.index
    }

    ReportUtils.VHAL_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.BLUE_GREY.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.WHITE.index
    }

    ReportUtils.MIDDLEWARE_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.CORNFLOWER_BLUE.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.WHITE.index
    }

    ReportUtils.SE_TYPE -> {
      reportCellStyle.fillForegroundColor = IndexedColors.BRIGHT_GREEN.index
      reportCellStyle.fillPattern = HSSFCellStyle.SOLID_FOREGROUND
      reportFont.color = IndexedColors.WHITE.index
    }
  }
  reportCellStyle.setFont(reportFont)
  return reportCellStyle
}

class ReportSheetData {
  var functionDesc: String = ""
  var adaptIdStr: String = ""
  var adaptZoneStr: String = ""
  var adaptValueStr: String = ""
  var testResult: String = ""
  var owner: String = ""
  var setIsSuccess: String = ""
  var getIsSuccess: String = ""
  var callbackIsSuccess: String = ""
  var reasonRemarks: String = ""
}

举报

相关推荐

0 条评论