就目前而言,我有241行代码用于创建46行,并使用HSSFRow填充excel中每行的第一列。每行都有名称,以便我稍后可以引用它以向该特定行添加更多列。
我正在尝试创建一个循环,为我创建这些行并为我节省200多行代码,这对于阅读来说简直无聊。无论如何使用循环动态命名和创建行?
这是我的一大块代码,工作正常,但重复一个疯狂的数量。块之间的唯一区别(除了易于循环和更改的索引)是我放置**的变量名:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Ions");
HSSFRow **name = worksheet.createRow((short) 0);
HSSFCell **cellA1 = **name.createCell((short) 0);
**cellA1.setCellValue("Name: ");
HSSFRow **lot = worksheet.createRow((short) 1);
HSSFCell **cellA2 = **lot.createCell((short) 0);
**cellA2.setCellValue("Lot #: ");
//..... This is done 46 more times!
我已经创建了一些数组,这些数组包含我想成为变量名的字符串,但如果可能的话,无法弄清楚如何实现它。到目前为止,这是我的想法,它不起作用,但显示了我想要达到的想法:
String[] nameString = {"name", "lot",...etc};
String[] cells = new String[50];//cellA1-A46
for(int i=0; i<46; i++){
cells[i] = "cellA"+(i+1);
System.out.print(cells[i] + ", ");
}
String[] text = {"Name: ", "Lot #: ",...etc};
for(int i = 0; i < 46; i++){
//creates row named from the index of nameString[].
HSSFRow nameString[i] = worksheet.createRow((short) i);
//creates cell named from index of cells[].
HSSFCell cells[i] = nameString[i].createCell((short) 0);
//sets that created cell equal to the index of text[]
cells[i].setCellValue(text[i]);
如果有任何想法请分享! 谢谢! -pdatric