scala中把dataframe写到excel代码
时间: 2023-04-05 08:04:47 浏览: 123
可以使用以下代码将DataFrame写入Excel文件:
```
import org.apache.spark.sql.DataFrame
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Cell
import java.io.FileOutputStream
def writeDataFrameToExcel(dataFrame: DataFrame, filePath: String, sheetName: String) = {
val workbook: Workbook = WorkbookFactory.create(true)
val sheet: Sheet = workbook.createSheet(sheetName)
val headerRow: Row = sheet.createRow(0)
val columns = dataFrame.columns
for (i <- 0 until columns.length) {
val cell: Cell = headerRow.createCell(i)
cell.setCellValue(columns(i))
}
val rows = dataFrame.collect()
for (i <- 0 until rows.length) {
val row: Row = sheet.createRow(i + 1)
for (j <- 0 until columns.length) {
val cell: Cell = row.createCell(j)
cell.setCellValue(rows(i).get(j).toString)
}
}
val fileOut = new FileOutputStream(filePath)
workbook.write(fileOut)
fileOut.close()
}
```
其中,dataFrame是要写入Excel文件的DataFrame,filePath是Excel文件的路径,sheetName是Excel文件中的工作表名称。
阅读全文