适用场景:java读取excel对应xls或xlsx格式文件
1.桌面对应文件xls与xlsx
2.文件中的内容
xls:
xlsx:
注意点:excel格式文件列中对应是数值时需要变成文本,如下图
3.运行代码
代码:
package com.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestExcel {
@Test
public void testReadExel() {
System.out.println("------开始xls文件读取------");
//对应桌面地址的xls格式文件
String xlsPath="C:\\Users\\Administrator\\Desktop\\cs.xls";
System.out.println(analyzeExcel(xlsPath));
System.out.println("------开始xlsx文件读取------");
//对应桌面地址的xlsx格式文件
String xlsxPath="C:\\Users\\Administrator\\Desktop\\cs.xlsx";
System.out.println(analyzeExcel(xlsxPath));
}
public String analyzeExcel(String path) {
StringBuffer tempBuffer = new StringBuffer();
InputStream in = null;
// 错误信息接收器
StringBuffer errorBuffer = new StringBuffer();
try{
in = new FileInputStream(path);
//根据版本选择创建Workbook的方式
Workbook wb = null;
//根据文件名判断文件是2003版本还是2007版本
if (path.endsWith(".xlsx")) {
wb = new XSSFWorkbook(in);
} else {
wb = new HSSFWorkbook(in);
}
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
int totalRows = sheet.getPhysicalNumberOfRows();
// 总列数
int totalCells = 0;
// 得到Excel的列数(前提是有行数),从第二行算起
if (totalRows >= 2 && sheet.getRow(1) != null) {
totalCells = sheet.getRow(1).getPhysicalNumberOfCells();
}
String br = "\n";
// 循环Excel行数,从第二行开始
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null) {
errorBuffer.append(br).append("第" + (r + 1) + "行数据有问题,请仔细检查!");
continue;
}
// 循环Excel的列
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
if(cell == null) {
errorBuffer.append(br).append("第" + (c + 1) + "列数据有问题,请仔细检查!");
continue;
}
//对应第几行第1列数据
if (c == 0) {
tempBuffer.append("第"+(r+1)+"行第1列数据="+cell.getStringCellValue());
}
//对应第几行第2列数据
else if (c == 1) {
tempBuffer.append("第"+(r+1)+"行第2列数据="+cell.getStringCellValue());
}
//对应第几行第3列数据
else if (c == 2) {
tempBuffer.append("第"+(r+1)+"行第3列数据="+cell.getStringCellValue()).append(br);
}
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(errorBuffer.length() >0) {
return errorBuffer.toString();
}
return tempBuffer.toString();
}
}