如何从Excel工作表中读取列a1并执行字符串匹配以在Java程序中定义变量
我需要读取Excel工作表中的一个固定列,然后从该列中找出变量并将其加载到Java程序中
例如,我需要阅读包含以下数据的a1列:“什么是/@v1@/%of/@v2@/?”
/@v1@/和/@v2@/是变量。我的Java程序需要检测这些变量并在其中插入随机值。我已经做了以下工作:
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ACGS {
public static void main(String[] args) throws Exception {
//test file is located in your project path
FileInputStream fileIn = new FileInputStream("C://users/admin/Desktop/Content.xls");
//read file
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
HSSFWorkbook filename = new HSSFWorkbook(fs);
//open sheet 0 which is first sheet of your worksheet
HSSFSheet sheet = filename.getSheetAt(0);
//we will search for column index containing string "Your Column Name" in the row 0 (which is first row of a worksheet
String columnWanted = "v4";
Integer columnNo = null;
//output all not null values to the list
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = sheet.getRow(0);
for(Cell cell:firstRow){
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
if (columnNo != null){
for (Row row : sheet) {
Cell c = row.getCell(columnNo);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + fileIn.toString());
}
}
}
你能告诉我怎么进一步吗
# 1 楼答案
听起来您可以使用Excel模板处理解决方案。我知道的两个是jXLS和JETT(免责声明:我写了JETT,并维护它)
这些库是相似的,因为它们都依赖于Apache Commons JEXL在模板电子表格中提供表达式支持
在模板中,您当前有需要用实际变量值替换的
/@v1@/
等占位符。在这两种框架中,您都可以使用${
和}
来表示应该用值替换的表达式。这将是模板电子表格中的单元格值在Java代码中,创建一个
Map<String, Object>
将变量名映射到值,例如库使用此
Map
为要计算的表达式提供值然后,调用API入口点创建另一个电子表格,该电子表格中的表达式替换为值。在JETT中,这类似于:
在jXLS中,情况非常相似:
任何一种情况下的输出都是,例如上面的示例单元格:
# 2 楼答案
不必检查相等性,您可以使用字符串中的contains api,如下所示:
也就是说