转自:http://blog.csdn.net/chen_zw/article/details/8316028
poi是apache的子项目,专门用于处理Microsoft文档,其中HSSF和XSSF专门用于操作Excel表格(HSSF操作的是后缀名为.xls的文档(Excel 2003 以上),XSSF操作的是后缀名为.xlsx的文档(Excel 2007))。
所需jar包:poi-3.9-20121203.jar (当前最新jar包)
Tag1:create Excel
- /**
- * 创建Excle并写入数据
- * @author Ye
- *
- */
- public class CreateExcel {
- //测试数据,用于写入到Excel
- private static List<Student> getStudent() throws Exception{
- List<Student> list = new ArrayList<Student>();
- SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
- Student user1 = new Student(1,"张三","男",16,df.parse("1997-03-12"));
- Student user2 = new Student(2,"李四","男",17,df.parse("1999-08-12"));
- Student user3 = new Student(3,"王五","女",26,df.parse("1985-11-12"));
- list.add(user1);
- list.add(user2);
- list.add(user3);
- return list;
- }
- public static void main(String[] args) throws Exception {
- //第一步,创建一个webbook,对应一个Excel文件
- HSSFWorkbook wb = new HSSFWorkbook();
- //第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
- HSSFSheet studentSheet = wb.createSheet("学生信息");
- //第三步,在sheet中添加表头行(即第0行),注意老版本poi对Excel的行数列数限制为short类型
- HSSFRow studentHeadRow = studentSheet.createRow(0);
- //第四步,创建表头单元格,并设置单元格值居中(方法一:手动设置)
- HSSFCellStyle style = wb.createCellStyle(); //创建单元格样式
- style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //设置样式为居中显示
- HSSFCell studentHeadcell = null;
- studentHeadcell = studentHeadRow.createCell(0);
- studentHeadcell.setCellValue("学号");
- studentHeadcell.setCellStyle(style);
- studentHeadcell = studentHeadRow.createCell(1);
- studentHeadcell.setCellValue("姓名");
- studentHeadcell.setCellStyle(style);
- studentHeadcell = studentHeadRow.createCell(2);
- studentHeadcell.setCellValue("性别");
- studentHeadcell.setCellStyle(style);
- studentHeadcell = studentHeadRow.createCell(3);
- studentHeadcell.setCellValue("年龄");
- studentHeadcell.setCellStyle(style);
- studentHeadcell = studentHeadRow.createCell(4);
- studentHeadcell.setCellValue("出生年月");
- studentHeadcell.setCellStyle(style);
- //方法二:通过反射机制获取类中的所有属性并设为表头
- // try {
- // Class<?> studentClass = Class.forName("Student"); //com.geocompass.model.STSTBPRPModel
- // Field[] fieldList = studentClass.getDeclaredFields();
- // for (int i = 0; i < fieldList.length; i++) {
- // Field fld = fieldList[i];
- // studentHeadRow.createCell(i).setCellValue(fld.getName());
- // }
- // } catch (ClassNotFoundException e) {
- // e.printStackTrace();
- // }
- //第五步,写入实体数据
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
- List<Student> stuList = CreateExcel.getStudent(); //获取实体数据集
- HSSFRow studentRow = null; //数据行
- for(int i=0;i<stuList.size();i++){
- studentRow = studentSheet.createRow(i+1);
- Student stu = (Student) stuList.get(i);
- studentRow.createCell(0).setCellValue(stu.getId());
- studentRow.createCell(1).setCellValue(stu.getName());
- studentRow.createCell(2).setCellValue(stu.getGender());
- studentRow.createCell(3).setCellValue(stu.getAge());
- studentRow.createCell(4).setCellValue(sdf.format(stu.getBirth()));
- }
- //第六步,将文件存到指定位置
- try {
- FileOutputStream fout = new FileOutputStream("D:/student.xls");
- wb.write(fout);
- fout.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- //或弹出下载对话框
- response.setContentType("application/ms-excel");
- response.setHeader("Content-Disposition" ,"attachment;filename="+new String("导出Excel.xls".getBytes(),"utf-8")) ;
- wb.write(response.getOutputStream());
- }
- }
Tag2:read from Excel
- /**
- * 读取Excel
- * @author Ye
- *
- */
- public class ReadExcel {
- public static void main(String[] args) throws IOException, ParseException {
- //第一步:初始化Workbook对象。
- HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("D:/student.xls"));
- List<Student> stuList = new ArrayList<Student>();
- //第二步:循环遍历获取Excel的sheet
- for (int sheetNum = 0; sheetNum < wb.getNumberOfSheets(); sheetNum++) {
- HSSFSheet hssfSheet = wb.getSheetAt(sheetNum);
- if (hssfSheet == null) {
- continue;
- }
- Student stu = null;
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
- //第三步:循环遍历获取第sheetNum个sheet的所有行记录
- for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
- HSSFRow hssfRow = hssfSheet.getRow(rowNum);
- if (hssfRow == null) {
- continue;
- }
- stu = new Student();
- //第四步:获取每个单元格的值并赋值给stu对象
- HSSFCell sid = hssfRow.getCell(0);
- stu.setId(Integer.parseInt(getValue(sid)));
- HSSFCell sname = hssfRow.getCell(1);
- stu.setName(getValue(sname));
- HSSFCell gender = hssfRow.getCell(2);
- stu.setGender(getValue(gender));
- HSSFCell age = hssfRow.getCell(3);
- stu.setAge(Float.parseFloat(getValue(age)));
- HSSFCell birth = hssfRow.getCell(4);
- stu.setBirth(sdf.parse(getValue(birth)));
- stuList.add(stu);
- }
- }
- //测试
- for(Student s:stuList)
- {
- System.out.println(s.getId() + " " + s.getName() +" " + s.getGender() + " "+ s.getAge() + " " + s.getBirth());
- }
- }
- //将Excel单元格中的数据都转化成String类型
- private static String getValue(HSSFCell hssfCell) {
- if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
- return String.valueOf(hssfCell.getBooleanCellValue()); // 返回布尔类型的值
- } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
- return String.valueOf(hssfCell.getNumericCellValue()); // 返回数值类型的值
- } else {
- return String.valueOf(hssfCell.getStringCellValue()); // 返回字符串类型的值
- }
- }
- }
Notice:(1) 之前我一直使用Tomcat服务器运行代码,也没出过错,最近换成用Weblogic服务器,运行该代码时却报错:
java.lang.NoClassDefFoundError: org/apache/poi/hssf/usermodel/HSSFWorkbook
java.lang.ClassNotFoundException: org.apache.poi.hssf.usermodel.HSSFWorkbook
但明明都把poi-3.9-20121203.jar都已放到lib目录下,程序也都是自动部署的,为什么会找不到该jar包中的类呢?赶紧到weblogic服务器的部署目录(D:\Tool\bea\user_projects\domains\base_domain\servers\AdminServer\tmp\_WL_user\CMDB\i3s8gk\war\WEB-INF\lib)去看,果然没给我自动编译加载过来,重启下服务器,问题解决
/**
* 获取合并单元格的值
*
* @param sheet
* @param row
* @param column
* @return
*/
public static String getMergedRegionValue(Sheet sheet, int row, int column) {
sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell);
}
}
}
return null;
}
/**
* 判断指定的单元格是否是合并单元格
*
* @param sheet
* @param row
* @param column
* @return
*/
public static boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();// 得到所有区域/
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
sub = 0;
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
sub = lastRow - firstRow;
return true;
}
}
}
return false;
}
/**
* 获取单元格的值
*
* @param cell
* @return
*/
public static String getCellValue(Cell cell) {
if (cell == null)
return "";
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
return String.valueOf((int) cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf((int) cell.getNumericCellValue());
}
return "";
}