[英]how can I read xls and xlsx file in spark with java?
我想像火花一樣逐行讀取xls和xlsx(MS Excel)文件,就像我們對文本文件所做的那樣,或者如何?
我想使用spark來提高讀取1 GB大型xls文件的性能,這就是為什么我需要spark來讀取文件的部分,就像處理文本文件一樣。
我如何從Spark中的excel文件中讀取數據,無論它是逐行還是不逐行?
我只想使用spark來讀取xls文件中的條目。
請提出建議。
謝謝!!!
您無法通過spark
做到這一點。 這不是為了它。 使用其他庫(例如Apache POI)來讀取excel,然后將數據作為文本輸入。
盡管這個問題有點老了,但我仍在回答。 可能對其他人有用。 答案是肯定的,您可以使用Apache Spark 2.x來完成。 假設您要將3列的xls轉換為Dataset。
class Bean {
private String col1;
private String col2;
private Timestamp col3;
}
StructType structType= new StructType(new StructField[] {
new StructField("col1", DataTypes.StringType, true, Metadata.empty()),
new StructField("col2", DataTypes.StringType, true, Metadata.empty()),
new StructField("col3", DataTypes.TimestampType, true, Metadata.empty())
});
Dataset<Bean> ds = sparkSession.read().
schema(structType).
format("com.crealytics.spark.excel").
option("useHeader", true). // If the xls file has headers
option("timestampFormat", "yyyy-MM-dd HH:mm:ss"). // If you want to convert timestamp to a specific format
option("treatEmptyValuesAsNulls", "false").
option("inferSchema", "false").
option("addColorColumns", "false").
load("/home/user/test/sample.xls"). //path to xls or xlsx
as(Encoders.bean(Bean.class)); // Bean in which you want to convert the data, you can remove this line if Dataset<Row> is just fine for you
您可以嘗試使用HadoopOffice庫使用Spark讀取/寫入Excel文件( https://github.com/ZuInnoTe/hadoopoffice/wiki )。 它支持加密的Excel,鏈接的工作簿,按元數據過濾...
這是我的工作方式。
在Maven中添加依賴項
<dependencies>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-core_2.11</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>org.apache.spark</groupId>
<artifactId>spark-sql_2.11</artifactId>
<version>2.4.2</version>
</dependency>
<dependency>
<groupId>com.crealytics</groupId>
<artifactId>spark-excel_2.11</artifactId>
<version>0.11.1</version>
</dependency>
</dependencies>
我的主班
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
public class ReadExcelSheets {
public static void main(String[] args) {
//skip logging extras
Logger.getLogger("org").setLevel(Level.ERROR);
//build session
SparkSession spark = SparkSession
.builder()
.appName("Java Spark SQL Example")
.config("spark.master", "local")
.getOrCreate();
//read excel - change file name
Dataset<Row> df = spark.read()
.format("com.crealytics.spark.excel")
.option("useHeader", "true")
//.option("dataAddress", "'Sheet1'!A1:M1470") // optional when you want to read sheets where A1 first top cell and M1470 us very bottom left of sheet.
.load("datasets/test1.xlsx");
//show your data
df.show();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.