您可以通过使用 Apache POI 库 (https://poi.apache.org/) 编写 Java 代码来处理加载 Excel 文件内容。该库是为处理包括 Excel 在内的 MS Office 应用程序数据而开发的。
我最近基于可帮助您将 Excel 文件加载到 MongoDB 数据库的技术创建了应用程序。
该应用程序在http://www.abespalov.com/ 下可用,并且仅针对 Windows 进行了测试,但也应适用于 Linux。应用程序将自动创建必要的集合并使用 Excel 文件内容填充集合。您可以并行导出多个文件。您可以跳过将文件转换为 CSV 格式的步骤。该应用程序处理 xls 和 xlsx 格式。
总体应用阶段为:
1) 加载excel文件内容。这是取决于文件扩展名的代码:
fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
if (fileExtension.equalsIgnoreCase("xlsx")) {
workbook = createWorkbook(openOPCPackage(inputSheetFile));
} else {
workbook = createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
}
sheet = workbook.getSheetAt(0);
2) 建立 MongoDB 连接。我使用 MongoClientURI 库;
MongoClientURI mongoClientURI = new MongoClientURI(
"mongodb://" + dbUser + ":" + dbPassword + "@" + dbServer
+ ":" + dbPort + "/" + dbDatabase);
excel2db.mongoClient = new MongoClient(mongoClientURI);
3) 遍历工作表并将行插入到集合中。这是一段Java代码:
Row row = (Row) rowIterator.next();
//get column names from a header
short minColIdx = row.getFirstCellNum();
short maxColIdx = row.getLastCellNum();
ArrayList<String> columnNameList = new ArrayList();
String columnName;
logger.info("The table {} is being populated", tableName);
//populate a list of column names
for (short colIdx = minColIdx; colIdx < maxColIdx; colIdx = (short) (colIdx + 1)) {
columnNameList.add(row.getCell(colIdx) == null? "": row.getCell(colIdx).toString());
}
while (rowIterator.hasNext()) {
Document document = new Document();
Row rowData = (Row) rowIterator.next();
numOfProcessedRows++;
for (short colIdx = minColIdx; colIdx < maxColIdx; colIdx = (short) (colIdx + 1)) {
document.put(columnNameList.get(colIdx), rowData.getCell(colIdx).toString());
}
//save the document into a collection, point to the database
MongoCollection mongoCollection = mongoDB.getCollection(tableName);
mongoCollection.insertOne(document);
}
}
在这里您可以找到为将 excel 导出到 Postgres (https://github.com/palych-piter/Excel2DB) 而创建的应用程序的所有 Java 代码。