1.根据上传的文档判断Excel的版本,然后利用POI中对应的类来创建一个Workbook来读取上传文件的内容。
if (file == null || fileName == null && "".equals(fileName)) {
throw new RuntimeException("上传文件有误");
}
if (importMap == null) {
importMap = new HashMap<Integer, Object>();
}
String name = "";
try {
name = fileName.substring(fileName.lastIndexOf(".") + 1);
}
catch (Exception e) {
System.out.println("test" + "上传文件有误");
throw new RuntimeException("上传文件有误");
}
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
}
catch (Exception e) {
System.out.println("文件错误异常");
throw new RuntimeException(e);
}
// 判断上传文件的格式
boolean b = name.equalsIgnoreCase("xls"); // 03以及之前的版本
Workbook workbook = b ? new HSSFWorkbook(fileInputStream) : new XSSFWorkbook(fileInputStream);
2.创建了workbook以后就可以用该对象来操作Excel了;比如去获取一个单元格的内容,样式等等。但是在这之前还必须去获取到需要操作的工作薄。
Sheet sheet = workbook.getSheetAt(0);
3.获取到一个工作薄以后就可以去获取该工作薄中的表以及单元格了。
//获取该工作薄中的第三行
Row row = sheet.getRow(3);
//获取第三行第三列的单元格
Cell cell = row.getCell(3);
4.每一个单元格中保存的就是实际的内容,其实操作Excel就是为了获取到数据;
//获取boolean值
cell.getBooleanCellValue();
//字符串
cell.getStringCellValue();
//cell的样式
cell.getCellStyle();
//当前行号
cell.getColumnIndex();
//日期
cell.getDateCellValue();
//double
cell.getNumericCellValue();
当Excel表格中上传的数据为String类型的字符串数字的时候,该字符串会可能会被Excel表格转换成一个用科学计数法计数的数据,因此在后台可以利用BigDecimal来处理一下。
try{
s = cell,getStringCellValue();
}catch(Exception e){
s = BigDecimal.valueOf((Double) o).toString();
}
4.如下所示的代码是在学习了POI后写的一段代码;
package net.wanpen.eis.util.poi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
public class ImportExcel {
/*
* 导入Excel表格
*
* @param file上传文件
*
* @param fileName上传文件名
*
* @param importMap上传文件内容保存的集合
*
* @param files对象中的属性值
*
* @param clazz实体对象的Class值
*
* @param err记录有错的数据行
*
* @retrun 返回出错记录的行号
*/
public static List<Integer> importExcel(File file, String[] files, Map<Integer, Object> importMap, String fileName,
Class clazz) throws IOException, InstantiationException, IllegalAccessException, SecurityException,
NoSuchMethodException {
if (file == null || fileName == null && "".equals(fileName)) {
throw new RuntimeException("上传文件有误");
}
if (importMap == null) {
importMap = new HashMap<Integer, Object>();
}
String name = "";
try {
name = fileName.substring(fileName.lastIndexOf(".") + 1);
}
catch (Exception e) {
System.out.println("test" + "上传文件有误");
throw new RuntimeException("上传文件有误");
}
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
}
catch (Exception e) {
System.out.println("文件错误异常");
throw new RuntimeException(e);
}
// 判断上传文件的格式
boolean b = name.equalsIgnoreCase("xls"); // 03以及之前的版本
Workbook workbook = b ? new HSSFWorkbook(fileInputStream) : new XSSFWorkbook(fileInputStream);
// 获取上传的工作薄
Sheet sheet = workbook.getSheetAt(0);
List<Integer> error = new ArrayList<Integer>();
// 遍历工作薄
if (sheet.getPhysicalNumberOfRows() > 2) {
// 反射获取到真正的实体
Object obj = null;
System.out.println(sheet.getPhysicalNumberOfRows());
// 遍历每一行
for (int k = 2; k < sheet.getPhysicalNumberOfRows(); k++) {
boolean err = true;
Row row = sheet.getRow(k);
// 获取第一个单元格的内容
obj = clazz.newInstance();
Field[] f = clazz.getDeclaredFields();
// 获取字段名
// excel表格中有的数据的个数与files中的一样
// 单元格
Cell cell;
for (int m = 0; m < files.length; m++) {
if (err == false) {
err = true;
break;
}
// 取出一个单元格
cell = row.getCell(m);
Object o;
try {
o = cell.getStringCellValue();
}
catch (Exception e) {
try {
o = cell.getBooleanCellValue();
}
catch (Exception e2) {
try {
o = cell.getNumericCellValue();
}
catch (Exception e3) {
try {
o = cell.getColumnIndex();
}
catch (Exception e4) {
o = cell.getDateCellValue();
o = new SimpleDateFormat("yyyy-MM-dd").format((Date) o);
}
}
}
}
Method method;
// 遍历类中的属性
for (int i = 0; i < f.length; i++) {
// 暴力方式获取私有属性
f[i].setAccessible(true);
String fName = f[i].getName();
Type type = f[i].getType();
String ty = type.toString().substring(type.toString().indexOf(" ") + 1);
Class tt = null;
try {
tt = Class.forName(ty);
}
catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
if (files[m].equalsIgnoreCase(fName)) {
method = clazz.getMethod("set" + files[m], tt);
try {
System.out.println(o + "::" + method.toString());
method.invoke(obj, o);
}
catch (IllegalArgumentException e) {
// 上传数据是全数字的String会被转换成BigDecimal
try {
String s = BigDecimal.valueOf((Double) o).toString();
method.invoke(obj, s);
}
catch (Exception e2) {
// 有错误数据
err = false;
// 记录第几行出错了
error.add(k);
break;
}
}
catch (InvocationTargetException e) {
err = false;
// 记录第几行出错了
error.add(k);
break;
}
}
}
}
if (err) {
importMap.put(k, obj);
}
}
}
return error;
}
}