友情提示:**过于结构化,没太多润色....码的不好还请诸位海涵并多提意见**
资源 | 类型 | 说明 |
---|---|---|
Workbook | 接口 | Excel工作簿的高级表示。这是大多数用户在阅读或编写工作簿时所构建的第一个对象。它也是创建新表/等的顶级对象 |
WorkbookFactory | 类 | 创建合适的工作簿(HSSFWorkbook或XSSFWorkbook),从提供的输入中自动检测。 |
HSSFWorkbook | 类 | .xls (97版和2003版的格式) |
XSSFWorkbook | 类 | .xlsx (2007之后版本格式) |
Sheet | 接口 | Excel工作表的高级表示。表是工作簿中的中心结构,并且是用户在其电子表格中工作的地方。最常见的表类型是工作表,它表示为单元格网格。工作表单元格可以包含文本、数字、日期和公式。单元格也可以被格式化。 |
Row | 接口 | 行 |
Cell | 接口 | 单元格 |
如果有其他需求可参考官方文档:http://poi.apache.org/apidocs/index.html?overview-summary.html
下载地址:http://download.csdn.net/detail/u013591605/9898273
Tag | 说明 |
---|---|
Cell.CELL_TYPE_STRING | 代表文本 |
Cell.CELL_TYPE_BLANK | 空白格 |
Cell.CELL_TYPE_BOOLEAN: | 布尔型 |
Cell.CELL_TYPE_NUMERIC | 数字 |
Cell.CELL_TYPE_ERROR | 错误 |
Cell.CELL_TYPE_FORMULA | 公式 |
public static Map> readExcel(String path, Class clzz) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List list = new LinkedList();
Map> map = new HashMap>();
File file = new File(path);
FileInputStream fis = null;
Workbook workBook = null;
if (file.exists()) {
try {
fis = new FileInputStream(file);
workBook = WorkbookFactory.create(fis);
int numberOfSheets = workBook.getNumberOfSheets();
for (int s = 0; s < numberOfSheets; s++) { // sheet工作表
Sheet sheetAt = workBook.getSheetAt(s);
// String sheetName = sheetAt.getSheetName(); //获取工作表名称
int rowsOfSheet = sheetAt.getPhysicalNumberOfRows(); // 获取当前Sheet的总列数
System.out.println("当前表格的总行数:" + rowsOfSheet);
for (int r = 0; r < rowsOfSheet; r++) { // 总行
Row row = sheetAt.getRow(r);
if (row == null) {
continue;
} else {
int rowNum = row.getRowNum();
System.out.println("当前行:" + rowNum);
int numberOfCells = row.getPhysicalNumberOfCells();
for (int c = 0; c < numberOfCells; c++) { // 总列(格)
Cell cell = row.getCell(c);
if (cell == null) {
continue;
} else {
int cellType = cell.getCellType();
switch (cellType) {
case Cell.CELL_TYPE_STRING: // 代表文本
String stringCellValue = cell.getStringCellValue();
System.out.print(stringCellValue + "\t");
break;
case Cell.CELL_TYPE_BLANK: // 空白格
String stringCellBlankValue = cell.getStringCellValue();
System.out.print(stringCellBlankValue + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN: // 布尔型
boolean booleanCellValue = cell.getBooleanCellValue();
System.out.print(booleanCellValue + "\t");
break;
case Cell.CELL_TYPE_NUMERIC: // 数字||日期
boolean cellDateFormatted = DateUtil.isCellDateFormatted(cell);
if (cellDateFormatted) {
Date dateCellValue = cell.getDateCellValue();
System.out.print(sdf.format(dateCellValue) + "\t");
} else {
double numericCellValue = cell.getNumericCellValue();
System.out.print(numericCellValue + "\t");
}
break;
case Cell.CELL_TYPE_ERROR: // 错误
byte errorCellValue = cell.getErrorCellValue();
System.out.print(errorCellValue + "\t");
break;
case Cell.CELL_TYPE_FORMULA: // 公式
int cachedFormulaResultType = cell.getCachedFormulaResultType();
System.out.print(cachedFormulaResultType + "\t");
break;
}
}
}
System.out.println(" \t ");
}
System.out.println("");
}
}
if (fis != null) {
fis.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("文件不存在!");
}
return map;
}
@SuppressWarnings("resource")
public static void writeExcel(String path, List list, Class clzz) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Field[] declaredFields = clzz.getDeclaredFields();
File file = new File(path);
FileOutputStream fos = null;
Workbook workbook = null;
try {
if (file.exists()) {
fos = new FileOutputStream(file);
String suffix = getSuffix(path);
if (suffix.equalsIgnoreCase("XLSX")) {
workbook = new XSSFWorkbook();
} else if (suffix.equalsIgnoreCase("XLS")) {
workbook = new HSSFWorkbook();
} else {
throw new Exception("当前文件不是excel文件");
}
Sheet sheet = workbook.createSheet(); // 生成工作表
Row row = sheet.createRow(0);
for (int m = 0; m < declaredFields.length; m++) { // 设置title
Field field = declaredFields[m];
field.setAccessible(true);
Cell cell = row.createCell(m);
String name = field.getName();
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(name);
}
for (int i = 0; i < list.size(); i++) { // 数据
T instance = list.get(i);
row = sheet.createRow(i + 1);
for (int j = 0; j < declaredFields.length; j++) {
Field field = declaredFields[j];
Object value = field.get(instance);
String fieldTypeName = field.getGenericType().getTypeName();
field.setAccessible(true);
Cell cell = row.createCell(j);
switch (fieldTypeName) {// content
case "long":
double d = Double.valueOf(value.toString());
cell.setCellValue(d);
break;
case "float":
CellStyle floatStyle = workbook.createCellStyle();
short format = workbook.createDataFormat().getFormat(".00");// 保留2位精度
floatStyle.setDataFormat(format);
double d1 = Double.parseDouble(String.valueOf(value));
cell.setCellStyle(floatStyle);
cell.setCellValue(d1);
break;
case "int":
double d2 = Double.parseDouble(String.valueOf(value));
cell.setCellValue(d2);
break;
case "java.util.Date":
CellStyle dateStyle = workbook.createCellStyle();
short df = workbook.createDataFormat().getFormat("yyyy-mm-dd");
dateStyle.setDataFormat(df);
cell.setCellStyle(dateStyle);
String format2 = sdf.format(value);
Date date = sdf.parse(format2);
cell.setCellValue(date);
break;
case "java.lang.String":
cell.setCellValue(value.toString());
break;
}
}
workbook.write(fos);
}
} else {
if (file.createNewFile()) {
writeExcel(path, list, clzz);
} else {
System.out.println("创建Excel表格失败!");
}
}
if (fos != null) {
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getSuffix(String path) {
String substring = path.substring(path.lastIndexOf(".") + 1);
return substring;
}