我的Java代码遇到了一些问题。我使用NetBeans 8.0.1。
我正在尝试读取包含多张工作表的Excel文件,然后将读数打印到输出窗口。代码中的某些东西不允许打印。我添加了一个for循环以循环覆盖 - 这会起作用吗?
此外,我一直在寻找如何将读数打印成.txt文件,但我无法找到它的相关信息。有人能帮助我吗?
这是我的代码:
package read_write_excel_v2;
import java.io.IOException;
import java.util.Iterator;
import javax.swing.JOptionPane;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class JIA_ReadingRewritingWorbooks_v5 {
public static String GetFileExtension(String path2){
String pathName = path2;
String path = "";
String ext = "";
int mid = pathName.lastIndexOf(".");
path = pathName.substring(0, mid);
ext = pathName.substring(mid + 1, pathName.length());
return ext;
}
/**
* Excel 2007 (and newer) file reader function. Uses Apache POI. Returns excel content
* @throws org.apache.poi.openxml4j.exceptions.InvalidFormatException
* @throws java.io.IOException
*/
public static void main(String[] args) throws IOException, InvalidFormatException {
String ExcelPath;
//ExcelPath = JOptionPane.showInputDialog(null, "Enter Excel path: ");
ExcelPath = "ExcelJAVAWrite_demo.xlsx";
try{
// OPCPackage eats less memory than a InputStream, which requires
// more memory
OPCPackage pkg;
pkg = OPCPackage.open(ExcelPath);
XSSFWorkbook wb = new XSSFWorkbook(pkg); // Declare XSSF WB
String fileExtn = GetFileExtension(ExcelPath);
//Sheet sheet = null;
for(int i = 0; i < wb.getNumberOfSheets(); i++){
Sheet sheet = wb.getSheetAt(i);
// Iteration of rows - rows are ready from the sheet
Iterator<Row> rows = sheet.rowIterator();
while(rows.hasNext()){
Row row = (Row) rows.next();
Iterator<Cell> cells = row.cellIterator();
while(cells.hasNext()){
Cell cell = (Cell) cells.next();
// Ready with the iteration of cells
// Now we get the cell type and display the values
switch(cell.getCellType()){
case Cell.CELL_TYPE_BLANK:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
case Cell.CELL_TYPE_ERROR:
System.out.print(cell.getErrorCellValue() + "\t");
break;
case Cell.CELL_TYPE_FORMULA:
System.out.print(cell.getCellFormula());
break;
default:
System.out.println();
case Cell.CELL_TYPE_NUMERIC:
if(DateUtil.isCellDateFormatted(cell)){
System.out.print(cell.getDateCellValue() + "\t");
} else {
System.out.print(cell.getNumericCellValue() + "\t");
}
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getRichStringCellValue().getString() + "\t");
break;
}
}
System.out.println("");
}
}
//wb.write(pkg);
pkg.close();
System.out.println("Excel file written successfully on screen");
}
catch ( IOException ex ) {
ex.printStackTrace();
}
}
}