一、引入依赖
<!--读取excel文件,配置POI框架的依赖-->
<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>
二、数据对象ExcelDataVO
public class ExcelDataVO {
private String name;
private Integer age;
private String location;
private String job;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "ExcelDataVO{" +
"name='" + name + '\'' +
", age=" + age +
", location='" + location + '\'' +
", job='" + job + '\'' +
'}';
}
}
三、读取Excel文件类ExcelReader
public class ExcelReader {
private static Logger logger = Logger.getLogger(ExcelReader.class.getName());
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
public static List<ExcelDataVO> readExcel(String fileName) {
Workbook workbook = null;
FileInputStream inputStream = null;
try {
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
File excelFile = new File(fileName);
if (!excelFile.exists()) {
logger.warning("指定的Excel文件不存在!");
return null;
}
inputStream = new FileInputStream(excelFile);
workbook = getWorkbook(inputStream, fileType);
List<ExcelDataVO> resultDataList = parseExcel(workbook);
return resultDataList;
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + fileName + " 错误信息:" + e.getMessage());
return null;
} finally {
try {
if (null != workbook) {
workbook.close();
}
if (null != inputStream) {
inputStream.close();
}
} catch (Exception e) {
logger.warning("关闭数据流出错!错误信息:" + e.getMessage());
return null;
}
}
}
public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
Workbook workbook = null;
if(fileType.equalsIgnoreCase(XLS)){
workbook = new XSSFWorkbook(inputStream);
}else if(fileType.equalsIgnoreCase(XLSX)){
workbook = new HSSFWorkbook(inputStream);
}
return workbook;
}
private static List<ExcelDataVO> parseExcel(Workbook workbook) {
List<ExcelDataVO> resultDataList = new ArrayList<ExcelDataVO>();
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
Sheet sheet = workbook.getSheetAt(sheetNum);
if (sheet == null) {
continue;
}
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
if (null == firstRow) {
logger.warning("解析Excel失败,在第一行没有读取到任何数据!");
}
int rowStart = firstRowNum + 1;
int rowEnd = sheet.getPhysicalNumberOfRows();
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row row = sheet.getRow(rowNum);
if (null == row) {
continue;
}
ExcelDataVO resultData = convertRowToData(row);
if (null == resultData) {
logger.warning("第 " + row.getRowNum() + "行数据不合法,已忽略!");
continue;
}
resultDataList.add(resultData);
}
}
return resultDataList;
}
private static ExcelDataVO convertRowToData(Row row) {
ExcelDataVO resultData = new ExcelDataVO();
Cell cell;
int cellNum = 0;
cell = row.getCell(cellNum++);
String name = convertCellValueToString(cell);
resultData.setName(name);
cell = row.getCell(cellNum++);
String ageStr = convertCellValueToString(cell);
if (null == ageStr || "".equals(ageStr)) {
resultData.setAge(null);
} else {
resultData.setAge(Integer.parseInt(ageStr));
}
cell = row.getCell(cellNum++);
String location = convertCellValueToString(cell);
resultData.setLocation(location);
cell = row.getCell(cellNum++);
String job = convertCellValueToString(cell);
resultData.setJob(job);
return resultData;
}
private static String convertCellValueToString(Cell cell) {
if(cell==null){
return null;
}
String returnValue = null;
switch (cell.getCellTypeEnum()) {
case NUMERIC:
Double doubleValue = cell.getNumericCellValue();
DecimalFormat df = new DecimalFormat("0");
returnValue = df.format(doubleValue);
break;
case STRING:
returnValue = cell.getStringCellValue();
break;
case BOOLEAN:
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case BLANK:
break;
case FORMULA:
returnValue = cell.getCellFormula();
break;
case ERROR:
break;
default:
break;
}
return returnValue;
}
}
四、生成Excel并写入数据信息ExcelWriter
public class ExcelWriter {
private static List<String> CELL_HEADS;
static{
CELL_HEADS = new ArrayList<String>();
CELL_HEADS.add("姓名");
CELL_HEADS.add("年龄");
CELL_HEADS.add("居住城市");
CELL_HEADS.add("职业");
}
public static Workbook exportData(List<ExcelDataVO> dataList){
Workbook workbook = new SXSSFWorkbook();
Sheet sheet = buildDataSheet(workbook);
int rowNum = 1;
for (Iterator<ExcelDataVO> it = dataList.iterator(); it.hasNext(); ) {
ExcelDataVO data = it.next();
if (data == null) {
continue;
}
Row row = sheet.createRow(rowNum++);
convertDataToRow(data, row);
}
return workbook;
}
private static Sheet buildDataSheet(Workbook workbook) {
Sheet sheet = workbook.createSheet();
for (int i=0; i<CELL_HEADS.size(); i++) {
sheet.setColumnWidth(i, 4000);
}
sheet.setDefaultRowHeight((short) 400);
CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());
Row head = sheet.createRow(0);
for (int i = 0; i < CELL_HEADS.size(); i++) {
Cell cell = head.createCell(i);
cell.setCellValue(CELL_HEADS.get(i));
cell.setCellStyle(cellStyle);
}
return sheet;
}
private static CellStyle buildHeadCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
return style;
}
private static void convertDataToRow(ExcelDataVO data, Row row){
int cellNum = 0;
Cell cell;
cell = row.createCell(cellNum++);
cell.setCellValue(null == data.getName() ? "" : data.getName());
cell = row.createCell(cellNum++);
if (null != data.getAge()) {
cell.setCellValue(data.getAge());
} else {
cell.setCellValue("");
}
cell = row.createCell(cellNum++);
cell.setCellValue(null == data.getLocation() ? "" : data.getLocation());
cell = row.createCell(cellNum++);
cell.setCellValue(null == data.getJob() ? "" : data.getJob());
}
}
五、测试类
public class Main {
private static Logger logger = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
testExcelWriter();
}
static void testExcelWriter(){
List<ExcelDataVO> dataVOList = new ArrayList<ExcelDataVO>(2);
ExcelDataVO dataVO = new ExcelDataVO();
dataVO.setName("小明");
dataVO.setAge(18);
dataVO.setLocation("广州");
dataVO.setJob("大学生");
ExcelDataVO dataVO2 = new ExcelDataVO();
dataVO2.setName("小花");
dataVO2.setAge(19);
dataVO2.setLocation("深圳");
dataVO2.setJob("大学生");
dataVOList.add(dataVO);
dataVOList.add(dataVO2);
Workbook workbook = ExcelWriter.exportData(dataVOList);
FileOutputStream fileOut = null;
try {
String exportFilePath = "D:\\下载\\aa.xls";
File exportFile = new File(exportFilePath);
if (!exportFile.exists()) {
exportFile.createNewFile();
}
fileOut = new FileOutputStream(exportFilePath);
workbook.write(fileOut);
fileOut.flush();
} catch (Exception e) {
logger.warning("输出Excel时发生错误,错误原因:" + e.getMessage());
} finally {
try {
if (null != fileOut) {
fileOut.close();
}
if (null != workbook) {
workbook.close();
}
} catch (IOException e) {
logger.warning("关闭输出流时发生错误,错误原因:" + e.getMessage());
}
}
}
static void testExcelReader(){
String excelFileName = "D:\\下载\\aa.xls";
List<ExcelDataVO> readResult = ExcelReader.readExcel(excelFileName);
System.out.println(readResult.toString());
}
}