scala导出UTF-8的CSV文件用Excel打开乱码

时间:2022-06-19 22:25:11

去掉BOM:\uFEFF

避免出现科学计数法:在 数据前或者后面加上“\t”


def exportFiles(title: String, subTitles: String, selectCondition: String, content: List[List[String]]) = {
    var fileName = "fail"
    try {
      val exportFile = new File(s"$LocalFilePath/$title($selectCondition)_${formatTimStamp()}.csv")
      if (!exportFile.getParentFile.exists())
        exportFile.getParentFile.mkdirs
      if (!exportFile.exists())
        exportFile.createNewFile
      log.info("exportFile Path:"+exportFile.getAbsoluteFile)
      log.info("exportFile Path:"+exportFile)
      val bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile), "UTF-8"))
      var count = 0
      bw.write("\uFEFF" + tackleSubtitles(subTitles))
      content.map {
        row => {
          val line = new StringBuffer()
          log.info("########data length===" + row.length)
          for (i <- 0 to row.length - 1) {
            if (i == row.length - 1) {
              /*if (row(i).equals("") || row(i) == "" || row(i) == "null" || row(i) == null)
                line.append("" + "\r\n")
              else*/
                line.append(Try(row(i).replace("--","")).getOrElse("") + "\t\r\n")
            } else {
              /*if (row(i).equals("") || row(i) == "" || row(i) == "null" || row(i) == null)
                line.append(row(i) + ",")
              else*/
              line.append(Try(row(i).replace("--","")).getOrElse("")  + "\t,")
            }
          }


          count += 1
          bw.write(line.toString)
          if (count % 100 == 0)
            bw.flush()
        }
      }
      bw.flush()
      bw.close()
      if (exportFile.exists && exportFile.length() > 0)
        fileName = exportFile.getName
    } catch {
      case e: Exception => {
        log.error(s"JdbcExport Error:${e}+++${e.getStackTrace}+++++${e.getStackTraceString}++++${e.printStackTrace()}")
      }
    }
    fileName
  }