文章主要记录了如何按照需求生成excel模版,以及如何从excel中解析数据成为我们需要的处理对象,为实现以上功能,本次所依赖的jar包如下:poi-3.10.1.jar,poi-ooxml-3.10.1.jar。
Excel的所有操作方法都定义在一个工具类当中并声明为静态方法,便于以后的调用。
- 生成一个Excel的辅助类:
package com.excel.util;
public class ExcelModel {
/**
* @Description: 将要生成的excel的第一行字段
*/
private String[] excelHeader;
/**
* @Description: excel的sheet工作面名称
*/
private String sheetName;
/**
* @Description: 生成的excel的文件名
*/
private String fileName;
public String[] getExcelHeader() {
return excelHeader;
}
public void setExcelHeader(String[] excelHeader) {
this.excelHeader = excelHeader;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
- 定义Excel操作的完整工具类,便于调用:
package com.excel.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Font;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
static final String XLS_TYPE = "XLS";
static final String XLSX_TYPE = "XLSX";
private ExcelUtil(){}
/**
* @Title: createWorkbookByType
* @Description: 第一步:按照文件类型生成对应的Workbook
* @param type 通常有xls xlsx两种excel文件
* @return
* @return: Workbook
* @author: zengchao
* @date: 2015年10月13日 下午2:58:53
*/
public static Workbook createWorkbookByType(String type){
Workbook workbook = null;
if(XLS_TYPE.equals(type)){
workbook = new HSSFWorkbook();
}else if(XLSX_TYPE.equals(type)){
workbook = new XSSFWorkbook();
}
return workbook;
}
/**
* @Title: createSheet
* @Description: 第二步:生成workbook对应的sheet工作面
* @param workbook
* @param sheetNo sheet的序号,一个workbook可以有多个工作面
* @param sheetName sheet的名称
* @return
* @return: Sheet
* @author: zengchao
* @date: 2015年10月13日 下午3:00:05
*/
public static Sheet createSheet(Workbook workbook, int sheetNo, String sheetName){
Sheet sheet = null;
if(workbook != null){
sheet = workbook.createSheet();
if(sheetName == ""||sheetName == null){
sheetName = "sheet" + sheetNo;
}
workbook.setSheetName(sheetNo, sheetName);
}
return sheet;
}
/**
* @Title: createCellStyle
* @Description: 第三步:生成workbook的行样式
* @param workbook
* @return
* @return: CellStyle
* @author: zengchao
* @date: 2015年10月13日 下午3:02:48
*/
public static CellStyle createCellStyle(Workbook workbook){
CellStyle cellStyle = null;
if(workbook != null){
cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
font.setColor(HSSFFont.COLOR_NORMAL);
cellStyle.setFont(font);
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
}
return cellStyle;
}
/**
* @Title: createHeader
* @Description: 第四步:生成对应sheet的头信息(即:sheet的第一行)
* @param sheet
* @param excelHeader
* @param cellStyle
* @return: void
* @author: zengchao
* @date: 2015年10月13日 下午2:59:48
*/
public static void createHeader(Sheet sheet, String[] excelHeader, CellStyle cellStyle){
if(sheet != null && excelHeader != null){
Row titleRow = sheet.createRow(0);
for(int i = 0;i < excelHeader.length;i++){
sheet.setColumnWidth(i, 2000);
Cell cell = titleRow.createCell(i, 0);
cell.setCellStyle(cellStyle);
cell.setCellValue(excelHeader[i]);
sheet.setDefaultColumnStyle(i, cellStyle);
}
}
}
/**
* @Title: downloadExcel
* @Description: 第五步:通过workbook提供的write()方法将生成的excel写入的输出流中
* @param workbook
* @param outPath
* @return: void
* @author: zengchao
* @date: 2015年10月13日 下午3:08:01
*/
private static void downloadExcel(Workbook workbook, String outPath){
OutputStream os = null;
try {
os = new FileOutputStream(new File(outPath));
workbook.write(os);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//提供统一的公共接口方法
public static void createExcelModel(ExcelModel excelModel, String outPath){
if(excelModel != null && outPath != null){
Workbook workbook = createWorkbookByType(XLS_TYPE);
Sheet sheet = createSheet(workbook, 0, excelModel.getSheetName());
CellStyle cellStyle = createCellStyle(workbook);
createHeader(sheet, excelModel.getExcelHeader(), cellStyle);
downloadExcel(workbook, outPath);
}
}
/**
*
* @Description: 以下部分为导入的excel数据解析部分
*/
/**
* @Title: getWorkbook
* @Description: 第一步:从输入流中读取excel文件的workbook
* @param is
* @return
* @return: Workbook
* @author: zengchao
* @date: 2015年10月13日 下午3:11:36
*/
public static Workbook getWorkbook(InputStream is){
Workbook workbook = null;
if(is != null){
try {
workbook = WorkbookFactory.create(is);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return workbook;
}
/**
* @Title: getAllData
* @Description: 第二步:从workbook中读取所有的数据信息
* @param path excel文件存放的路径
* @param sheetNo 要获取数据的sheet工作面的序号
* @return
* @return: List<String[]>
* @author: zengchao
* @date: 2015年10月13日 下午3:12:11
*/
public static List<String[]> getAllData(String path, int sheetNo){
List<String[]> datas = null;
Workbook workbook = null;
try {
workbook = getWorkbook(new FileInputStream(new File(path)));
Sheet sheet = workbook.getSheetAt(sheetNo);
datas = getAllSheetData(sheet);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return datas;
}
private static List<String[]> getAllSheetData(Sheet sheet){
List<String[]> datas = new ArrayList<String[]>();
int columnNum = 0;
if(sheet.getRow(0) != null){
columnNum = sheet.getRow(0).getLastCellNum() - sheet.getRow(0).getFirstCellNum();
}
if(columnNum > 0){
for(Row row : sheet){
String[] singleRow = new String[columnNum];
for(int i = 0;i < columnNum;i++){
Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
switch (cell.getCellType()){
case Cell.CELL_TYPE_BLANK:
singleRow[i] = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
singleRow[i] = Boolean.toString(cell.getBooleanCellValue());
break;
// 数值
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
singleRow[i] = String.valueOf(cell.getDateCellValue());
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String temp = cell.getStringCellValue();
// 判断是否包含小数点,如果不含小数点,则以字符串读取,如果含小数点,则转换为Double类型的字符串
if (temp.indexOf(".") > -1) {
singleRow[i] = String.valueOf(new Double(temp)).trim();
} else {
singleRow[i] = temp.trim();
}
}
break;
case Cell.CELL_TYPE_STRING:
singleRow[i] = cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_ERROR:
singleRow[i] = "";
break;
case Cell.CELL_TYPE_FORMULA:
cell.setCellType(Cell.CELL_TYPE_STRING);
singleRow[i] = cell.getStringCellValue();
if (singleRow[i] != null) {
singleRow[i] = singleRow[i].replaceAll("#N/A", "").trim();
}
break;
default:
singleRow[i] = "";
break;
}
}
datas.add(singleRow);
}
}
return datas;
}
public static void main(String[] args) {
String[] excelHeader = {"姓名","学号","班级"};
ExcelModel excelModel = new ExcelModel();
excelModel.setFileName("学生导入.xls");
excelModel.setSheetName("");
excelModel.setExcelHeader(excelHeader);
createExcelModel(excelModel, "F:/学生导入.xls");
System.out.println("生成学生导入模版成功!");
}
}
通过以上方法,我们就可以根据我们的需求生成我们想要的excel文件,但是在大多数情况下,我们仅仅能够生成excel模版是远远不够的。我们还需要从导入的excel文件中解析出对应的数据并生成我们可以操作的对象。因此,一下提供的即为如何从excel中解析数据。
- 生成需要解析成的对象
package com.excel.util;
public class Student {
/**
* @Description: 学生姓名
*/
private String name;
/**
* @Description: 学生学号
*/
private String studentNo;
/**
* @Description: 学生班级
*/
private String clazzName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
}
public String getClazzName() {
return clazzName;
}
public void setClazzName(String clazzName) {
this.clazzName = clazzName;
}
}
- 解析excel数据
package com.excel.util;
import java.util.ArrayList;
import java.util.List;
public class StudentExcelParse {
static final String[] HEADERS = {"姓名","学号","班级"};
/**
* @Title: parseExcelModel
* @Description: 解析excel数据为对应的模型
* @param filePath
* @return
* @return: List<Student>
* @author: zengchao
* @date: 2015年10月13日 下午3:26:00
*/
public static List<Student> parseExcelModel(String filePath){
List<Student> list = new ArrayList<Student>();
List<String[]> datas = ExcelUtil.getAllData(filePath, 0);
String[] excelHeaders = datas.get(0);
for(int j = 1;j < datas.size();j++){
String[] data = datas.get(j);
Student student = new Student();
if(excelHeaders.length > 0){
for(int i = 0;i < excelHeaders.length;i++){
if(excelHeaders[i].equals(HEADERS[0])){
student.setName(data[i]);
} else if(excelHeaders[i].equals(HEADERS[1])){
student.setStudentNo(data[i]);
} else if(excelHeaders[i].equals(HEADERS[2])){
student.setClazzName(data[i]);
}
}
}
list.add(student);
}
return list;
}
public static void main(String[] args) {
List<Student> list =parseExcelModel("F:/学生导入.xls");
for(Student stu : list){
System.out.println(stu.getName() + "--->" + stu.getStudentNo());
}
}
}
以上即为excel完整的操作流程,本次文章用于个人的总结学习,如果有不合适的地方请大家包含!