【发布时间】:2014-12-07 16:49:37
【问题描述】:
我遇到了问题。
我希望获取一行中的所有文本(在不同的单元格中)并将其作为字符串添加到数组列表中(即每一行,ArrayList 中的新元素),稍后我将把该行拆分为单个元素然后我会将其中一些放入不同的变量中。
我已从“http://howtodoinjava.com/2013/06/19/readingwriting-excel-files-in-java-poi-tutorial/”获取此代码
我想将每个单元格添加到一个临时数组中,在每次迭代之后,我将它作为一个字符串组合在一起。但是,当我尝试为每个单元格编号(以查看一切如何工作)时,那是失败的,单元格到处都是。
任何支持都会很棒!
这是我的代码:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.util.*;
import org.apache.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import java.lang.Iterable;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class ReadExcelDemo {
ArrayList<String> stringRow = new ArrayList();
ArrayList<String> temp = new ArrayList();
ArrayList<String> list = new ArrayList<String>();
String listString = "";
String x;
String y;
public void go() {
try {
FileInputStream file = new FileInputStream(new File(
"ratesheet_prefix.xlsx"));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(1);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
String test;
// test.
while (rowIterator.hasNext()) {temp.clear();
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{temp.clear();
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
// System.out.print(cell.getNumericCellValue() + " ");
this.x = " " + cell.getNumericCellValue() + " ";
temp.add(x);
System.out.print(x);
break;
case Cell.CELL_TYPE_STRING:
this.y = " " + cell.getStringCellValue() + " ";
// System.out.print(cell.getStringCellValue() + " ");
System.out.print(y);
temp.add(y);
break;
}
/*
for (String s : temp) {
listString += s + "\t";
}
System.out.println(listString);
*/
}
System.out.println(" ");
stringRow.add(listString);
// String z = x + y;
// System.out.println(z);
/*
* for (String s : temp) { listString += s + "\t"; }
* System.out.println(listString); temp.clear();
* stringRow.add(listString);
*/}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
/*
* for (String x:stringRow){ System.out.println(x); }
*/
}
public static void main(String[] args) {
ReadExcelDemo main = new ReadExcelDemo();
main.go();
}
}
【问题讨论】:
-
到底是什么问题?从上面看不清楚。
标签: java arraylist apache-poi