简介
众多 Java 攻城狮对 excel 读写等使用并不精通。本文通过最易理解,拿来即用原则编写。
读取Excel
maven 依赖
<!-- excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
excel 文档格式
这里读取的是 .xlsx
格式文件
java 源码
package com.javapub;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
public class ExcelTest {
private static XSSFSheet sheet;
public static void main(String[] args) {
ExcelTest excelTest = new ExcelTest();
String filePath = "D:\\java\\idea_workspace\\testAll\\src\\main\\resources\\excel\\testexcel.xlsx";//路径名
String sheetName = "Sheet1";//表名
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filePath);
XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);
//获取sheet
sheet = sheets.getSheet(sheetName);
//获取第二行第4列
String cell2 = excelTest.getExcelDateByIndex(1, 3);
System.out.println(cell2);
System.out.println("----------------------------------------------");
excelTest.readExcelData();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();//关闭流
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* 根据行和列的索引获取单元格的数据
*
* @param row
* @param column
* @return
*/
public String getExcelDateByIndex(int row, int column) {
XSSFRow xssfRow = sheet.getRow(row);
String cell = xssfRow.getCell(column).toString();
return cell;
}
//打印excel数据
public void readExcelData() {
//获取行数
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
//获取列数
XSSFRow row = sheet.getRow(i);
int columns = row.getPhysicalNumberOfCells();
for (int j = 0; j < columns; j++) {
String cell = row.getCell(j).toString();
System.out.println(cell);
}
}
}
}