import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class excel {
public static void main(String[] args){
//适用于Java和JavaEE
//java从本地读取文件
//web端上传文件为格式 MultipartFile
MultipartFile file;
ReadExcelDevicePart(file);
}
public void ReadExcelDevicePart(MultipartFile file) throws Exception {
String EXCEL_XLS = "xls";
String EXCEL_XLSX = "xlsx";
if (file.isEmpty()){
log.error("文件为空");
throw new GlobalException("文件为空");
}
try {
//根据路径获取这个操作excel的实例
Sheet sheet = null;
Row row = null;
if (file.getOriginalFilename().endsWith(EXCEL_XLS)) {
//用于xls文件的读取
HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());
sheet = wb.getSheetAt(0);
}
else
if (file.getOriginalFilename().endsWith(EXCEL_XLSX)) {
//用于xlsx文件的读取
XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
//根据页面index 获取sheet页
sheet = wb.getSheetAt(0);
}
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
Map<String,String> bodymap=new HashMap<>();
//获取每一行数据
row = sheet.getRow(i);
//表中第一列String类型的列,这里最好使用如下的方法。如果使用直接获取String的方法,会发生在表格数据为数字的情况下的异常
if (row.getCell(0) != null) {
Cell cell = row.getCell(0);
cell.setCellType(CellType.STRING);
System.out.println(cell.getStringCellValue());
}
//数字类型的列
if (row.getCell(1) != null) {//括号中为列数
//platformsDevicePartVo.setType((int)row.getCell(1).getNumericCellValue());
Cell cell = row.getCell(1);
cell.setCellType(CellType.STRING);
System.out.println(cell.getStringCellValue().trim());
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("excel读取错误");
}
}
}
Java读取表格内容
最新推荐文章于 2024-08-20 15:25:52 发布
该文章介绍了一个Java方法,用于处理Web端上传的MultipartFile类型Excel文件(XLS和XLSX),并解析其中的数据,包括字符串和数字类型。
摘要由CSDN通过智能技术生成