JAVA-POI-读取excel文件
程序员文章站
2022-07-13 13:15:31
...
使用Apache POI读取excel文件,兼容.xlsx和.xls
POM
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
ExcelTest
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.IOException;
/**
* @author wzx
* @time 2018/8/19
*/
public class ExcelTest {
public static final String SAMPLE_XLSX_FILE_PATH = "D:\\test1.xlsx";
public static final String SAMPLE_XLSX_FILE_PATH2 = "D:\\test2.xls";
public static void main(String[] args) throws IOException, InvalidFormatException {
readExcel();
}
public static void readExcel() throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH2));
System.out.println("sheets" + workbook.getNumberOfSheets());
//获取第一张表
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
int index = 0;
for (Cell cell : row) {
//读取数据前设置单元格类型
// cell.setCellType(CellType.STRING);
// String value = cell.getStringCellValue();
// System.out.print("value:" + value + " ");
if(index == 0) {
//先设置单元格类型,再读取数据
cell.setCellType(CellType.STRING);
String value = cell.getStringCellValue();
System.out.print("value:" + value + " ");
}
if(index == 1) {
//先设置单元格类型,再读取数据
cell.setCellType(CellType.NUMERIC);
Double value = cell.getNumericCellValue();
System.out.print("value:" + value + " ");
}
index++;
}
System.out.println();
}
}
}
上一篇: golang 读取excel(xlsx文件) 时间格式解析
下一篇: 读取Excel的数据