依赖jar包:
Maven工程,在pom.xml文件中加入依赖项::
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
普通java工程引用jar包:
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
public class NewsInStream {
public static void main(String args[]) throws Exception{
String inputFilePath = "C:/Users/worker03/Desktop/9b_ReptileModel/9bReptileData/newsdata.xlsx";
int rowBegin = 0;
test(inputFilePath,rowBegin);
}
public static void test(String inputFilePath, int rowBegin) throws Exception{
FileInputStream fileInput = new FileInputStream(inputFilePath);//创建文件输入流
XSSFWorkbook wb = new XSSFWorkbook(fileInput);//由输入流文件得到工作簿对象
XSSFSheet sheet = wb.getSheetAt(0);//获取第一个sheet
int lastRowNum = sheet.getLastRowNum(); //获取表格内容的最后一行的行数
//rowBegin代表要开始读取的行号,下面这个循环的作用是读取每一行内容
for (int i = rowBegin; i <= lastRowNum; ++i) {
XSSFRow row = sheet.getRow(i);//获取每一行
int columnNum = row.getLastCellNum();//获取每一行的最后一列的列号,即总列数
for (int j=0; j<columnNum; ++j) {
// row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
XSSFCell cell = row.getCell(j);//获取每个单元格
if (j == 0) { //对第一列日期进行特殊处理
System.out.println(cell.getStringCellValue());
} else if (CellType.NUMERIC.equals(cell.getCellType())) {
System.out.println(cell.getNumericCellValue());
} else {
System.out.println(cell.getStringCellValue());
}
}
System.out.println();
}
wb.close();
fileInput.close();
}
}