我已经使用 Excel 文件(.xlsx)创建了 Azure blob。我想使用 Java(Apache-poi) 和 Azure SDK 阅读相同内容,而无需在本地下载。我可以将 blob/文件下载到临时位置并读取它,但我应该能够直接从 blob 读取文件,而无需根据我的要求下载 blob。有这样的办法吗?
使用 Java 和 Azure SDK 从 Azure Blob 读取 excel 文件 (.xlsx),无需在本地下载。
您可以使用以下代码使用 Azure Java SDK 从 Azure Blob 存储读取 .xlsx 文件,而无需在本地下载。
代码:
import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobClientBuilder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
public class App {
public static void main(String[] args) {
String connectionString = "xxxx";
String containerName = "test";
String blobName = "sample5000.xlsx";
BlobClient blobClient = new BlobClientBuilder()
.connectionString(connectionString)
.containerName(containerName)
.blobName(blobName)
.buildClient();
try (InputStream inputStream = blobClient.openInputStream()) {
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
// Iterate through the rows
for (Row row : sheet) {
boolean isRowEmpty = true; // Flag to check if the row is empty
// Iterate through each cell in the row
for (Cell cell : row) {
if (cell.getCellType() != CellType.BLANK) {
isRowEmpty = false; // If we find a non-blank cell, the row is not empty
}
// Handle different cell types
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
// Handle dates if the cell contains a date
if (DateUtil.isCellDateFormatted(cell)) {
System.out.print(cell.getDateCellValue() + "\t");
} else {
System.out.print(cell.getNumericCellValue() + "\t");
}
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
System.out.print("Unknown Type\t");
}
}
// Only print a new line if the row is not empty
if (!isRowEmpty) {
System.out.println();
}
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面的代码使用了
BlobClient
,从指定的 blob 中以流的形式打开一个 Excel 文件 (.xlsx
),并读取第一个工作表。它迭代每一行和单元格,根据单元格内容的类型(字符串、数字、日期或布尔值)打印单元格内容。处理完所有行和单元格后,工作簿将关闭以完成。
在我的环境中,该文件包含 5000 行,上面的内容已执行并成功从 Azure Blob 存储中检索,无需在本地下载。
输出:
4992.0 Dorcas Darity Female United States 37.0 21/05/2015 8765.0
4993.0 Angel Sanor Male France 24.0 15/10/2017 3259.0
4994.0 Willodean Harn Female United States 39.0 16/08/2016 3567.0
4995.0 Weston Martina Male United States 26.0 21/05/2015 6540.0
4993.0 Angel Sanor Male France 24.0 15/10/2017 3259.0
4994.0 Willodean Harn Female United States 39.0 16/08/2016 3567.0
4995.0 Weston Martina Male United States 26.0 21/05/2015 6540.0
4995.0 Weston Martina Male United States 26.0 21/05/2015 6540.0
4996.0 Roma Lafollette Female United States 34.0 15/10/2017 2654.0
4997.0 Felisa Cail Female United States 28.0 16/08/2016 6525.0
4998.0 Demetria Abbey Female United States 32.0 21/05/2015 3265.0
4999.0 Jeromy Danz Male United States 39.0 15/10/2017 3265.0
5000.0 Rasheeda Alkire Female United States 29.0 16/08/2016 6125.0