我正在从 Excel 文件读取二维数组。该数组在 ExcelRead
类中读取和创建。
我的其他类,SendAll
需要使用每一行作为一组不同的变量进行循环。它将为每一行发送一封电子邮件,其中包含唯一的“收件人”和“发件人”电子邮件。发送电子邮件的逻辑是有效的,但我发送的每封电子邮件都有单独的类中的代码。当我有很多电子邮件收件人时,这将是令人望而却步的。最好将它们存储在 Excel 行中,然后让我的代码循环并运行每一行的代码。
基本上,我需要循环遍历 SendAll
代码,为数组中的每一行运行它。
这是我分别运行每个Send
类的代码。 IE。仅提取此电子邮件需要的专门定义的数组值。
public class SendAll extends ExcelRead {
public static void main(String[] args) throws Exception {
ExcelRead newExcelRead = new ExcelRead();
//newExcelRead.dataReader();
String[][] data = newExcelRead.dataReader();
String host = "smtp.gmail.com";
String port = "587";
String mailTo = data[1][3];
String mailFrom = data[1][4];
String password = data[1][5];
(Below this is just my Send Email logic)
这是重要的部分,我不确定它会有帮助,但下面是我的数组类 ExcelRead
...
public class ExcelRead {
public String[][] dataReader() throws Exception {
File excel = new File ("C:/Users/(location)/Dashboards.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
int rowNum = sheet.getLastRowNum()+1;
int colNum = sheet.getRow(0).getLastCellNum();
String[][] data = new String[rowNum][colNum];
for (int i=0; i<rowNum; i++){
//get the row
XSSFRow row = sheet.getRow(i);
for (int j=0; j<colNum; j++){
//this gets the cell and sets it as blank if it's empty.
XSSFCell cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
String value = String.valueOf(cell);
//System.out.println("Value: " + value);
data[i][j] = value;
}
}
//System.out.println("End Value: " + data[2][0]);
return data;
}
}
最佳答案
看起来您的第一项工作是稍微转换这些数据,您需要将原始数据数组合理化为唯一的发送/发送地址。这里的“收件人”/“发件人”地址构成了数据的唯一“ key ”。因此,我建议您更改 dataReader 以返回 Map>。关键是发送/发送地址的串联,第二个元素是实际数据的映射。如果你的 dataReader 生成了这个,那么你解析数据就会容易得多。我还没有测试过这个,但是类似这样的事情,假设,就像在你的例子中,你知道什么数据在什么列中。
Map<String, Map<String, String>> data = new HashMap<String, Map<String, String>>();
for (int i=0; i<rowNum; i++){
//get the row
XSSFRow row = sheet.getRow(i);
Map<String, String> rowMap = new HashMap<String, String>();
rowMap.put("to", String.valueOf(row.getCell(3, Row.CREATE_NULL_AS_BLANK)));
rowMap.put("from", String.valueOf(row.getCell(4, Row.CREATE_NULL_AS_BLANK)));
rowMap.put("password", String.valueOf(row.getCell(5, Row.CREATE_NULL_AS_BLANK)));
data.put(rowMap.get("to") + rowMap.get("from"), rowMap);
}
return data;
}
现在您可以做很多聪明的事情来为您的 map 创建键值,但这只是一个开始。
关于java - 如何在二维数组中的变量行中循环我的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32274269/