scala利用poi导出Excel

今天做了scala把数据库的数据按照需求导出Excel中,遇到一些问题和坑,记录下来遇到的大家分享。首先一个贴上一个粗糙的demo,大家可以借鉴一下。

利用Apache poi包进行处理,用的是4.0.1,依赖包:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
//创建file
val file = new File("/Users/xk/Desktop/a.xlsx")
//val ps = new POIFSFileSystem(new BufferedInputStream(new FileInputStream("/Users/xk/Desktop/a.xlsx")))
//判断file是否存在,不存在创建
if(!file.exists()){
try{
file.createNewFile()
// WorkbookFactory.create(new FileInputStream("/Users/xk/Desktop/a.xlsx"))
}catch {
case ex:IOException=>{
println("error")
}

}
}

//excel处理Excel的类
val hssf = new XSSFWorkbook()
//创建一个工作簿
val sheet = hssf.createSheet("student")
//创建第一行,一般都是的头部
val firstRow = sheet.createRow(0)
//设置行头
val heads = Array[String]("名字","年龄","班级")
//设置头部
for(i<- 0 until heads.length){
val cell = firstRow.createCell(i)
cell.setCellValue(new XSSFRichTextString(heads(i)))
}


val rowlist = parkDF.collect().toList

for(i <- 0 until rowlist.length){
val erow = sheet.createRow(i+1)
val xlsDot = rowlist(i)


val sortCell = erow.createCell(0)
sortCell.setCellValue(xlsDot.getString(0))

val sortCell1 = erow.createCell(1)
sortCell1.setCellValue(xlsDot.getString(1))

val sortCell2 = erow.createCell(2)
sortCell2.setCellValue(xlsDot.getString(2))

}

val out = new FileOutputStream("/Users/xk/Desktop/a.xlsx")
hssf.write(out)
out.close()
//in.close()
hssf.close()

遇到的坑:

org.apache.poi.poifs.filesystem.NotOLE2FileException

之前用的HSSFWorkbook类处理Excel,发现这个类只处理2007版之前的Excel,可以看成后缀是xls的Excel文件,后缀为xlsx需要用XSSFWorkbook,这个类不在poi包,需要引用poi-ooxml和poi-ooxml-schemas包

org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)

看到网上例子,创建XSSFWorkbook的时候,有用fileInputStream参数创建的。我就用了val hssf = new XSSFWorkbook(new FileInputStream(“/Users/g2/Desktop/a.xlsx”))的方式报错,结果一直报这个错误,去掉流的参数就可以了

####