我需要读取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());
}
}
}
你能告诉我怎么进一步?
答案 0 :(得分:1)
您可以使用String中的contains api,而不是检查是否相等:
cell.getStringCellValue().contains(columnWanted)
这意味着
"What is /@v1@/% of /@v2@/?".contains("v4") //No it doesnt
"What is /@v1@/% of /@v2@/?".contains("v2") //Yes it does
答案 1 :(得分:1)
听起来您可以使用Excel模板处理解决方案。我知道的两个是jXLS和JETT(免责声明:我写了JETT,我保留了它。)
库类似,因为它们都依赖Apache Commons JEXL在模板电子表格中提供表达式支持。
在您的模板中,您当前有一些占位符,例如/@v1@/
,您需要将其替换为实际的变量值。在任一框架中,您都可以使用${
和}
来表示应该用值替换的表达式。这将是模板电子表格中的单元格值。
What is ${v1}% of ${v2}?
在Java代码中,创建一个Map<String, Object>
,将变量名称映射到值,例如
Map<String, Object> beans = new HashMap<String, Object>();
beans.put("v1", 50);
beans.put("v2", 16);
库使用此Map
为要计算的表达式提供值。
然后,您调用API入口点以创建另一个表达式替换为值的电子表格。在JETT中,这将是:
ExcelTransformer transformer = new ExcelTransformer();
transformer.transform(inputTemplateFilename, outputFilename, beans);
在jXLS中,它将非常相似:
XLSTransformer transformer = new XLSTransformer();
transformer.transformXLS(inputTemplateFilename, beans, outputFilename);
对于上面的示例单元格,任何一种情况下的输出都是:
What is 50% of 16?