JAVA写个读取Excel
时间: 2024-01-03 21:02:27 浏览: 48
java实现Excel的读取
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static void main(String[] args) {
try {
// 读取Excel文件
InputStream inputStream = new FileInputStream(new File("example.xlsx"));
Workbook workbook = WorkbookFactory.create(inputStream);
// 获取第一个sheet
Sheet sheet = workbook.getSheetAt(0);
// 遍历行
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// 遍历单元格
Iterator<Cell> cellIterator = row.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// 打印单元格内容
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
System.out.print("\t");
}
}
System.out.println();
}
// 关闭文件流
workbook.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
阅读全文