scala小工具:读取EXCEL自动生成初始化语句

maven依赖:

<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>

脚本:

package Excel

import java.io.{File, FileInputStream, InputStream, PrintWriter}

import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.{Cell, CellType}

object TestExcel {
def main(args: Array[String]): Unit = {

//读取excel
val file = new File(args(0))
val stream = new FileInputStream(file)
//输出文件
var output=new PrintWriter("script.sql")
//工作簿
val workBook = new HSSFWorkbook(stream)
//获取sheets集合
val sheets = workBook.sheetIterator()
//sheet递归
while (sheets.hasNext) {
  //获取当前sheet
  val sheet = sheets.next()
  //获取rows集合
  val rows = sheet.rowIterator
  //行递归
  while (rows.hasNext) {
    //获取当前row
    val row = rows.next()
    //获取cell集合
    val cells = row.cellIterator()
    //sql语句
    var sql = "insert into " + sheet.getSheetName + " values("
    //内容
    var content: String = ""
    //cell遍历
    while (cells.hasNext) {
      var cell = cells.next()
      content += (cell.getCellType match {
        case CellType.NUMERIC => "," + cell.getNumericCellValue + ""
        case _ => ",'" + cell.getStringCellValue.toString.replace("'","\\'") + "'"
      }
        )
    }
    //生成sql
    sql+=content.replaceFirst(",","")+");"
    //写入文件
    output.write(sql)
    output.write("\n")
  }
}
output.close()

}
}

上一篇:归并排序算法


下一篇:插入排序