使用Java POI导入导出Excel数据

一、准备

笔者使用:JDK1.5 + POI 3.6,本代码既支持Excel2003又支持Excel2007。

POI 3.6 可以从 http://poi.apache.org/ 下载

需要导入的jar包:

Excel 数据文件:

姓名性别国籍学号年龄专业入学日期
陈美嘉中国0541257824计算机科学与技术2009/9/1
陆展博中国0541257924计算机科学与技术2009/9/2
关谷神奇日本0541258024计算机科学与技术2009/9/3
张伟中国0541258124计算机科学与技术2009/9/4
林宛瑜中国0541258224计算机科学与技术2009/9/5
曾小贤中国0541258324计算机科学与技术2009/9/6
吕子乔韩国0541258424计算机科学与技术2009/9/7
胡一菲中国0541258524计算机科学与技术2009/9/8

 

二、代码

Bean:

创建bean对象,bean对象保存数据。

package com.test;
/**
 * 
 * Student Bean
 * 
 */
public class Student
{
    private String name;
    
    private String sex;
    
    private String age;
    
    private String country;
    
    private String studentID;
    
    private String specialty;
    
    private String admissionTime;
    
    public String getName()
    {
        return name;
    }
    
    public void setName(String name)
    {
        this.name = name;
    }
    
    public String getSex()
    {
        return sex;
    }
    
    public void setSex(String sex)
    {
        this.sex = sex;
    }
    
    public String getAge()
    {
        return age;
    }
    
    public void setAge(String age)
    {
        this.age = age;
    }
    
    public String getCountry()
    {
        return country;
    }
    
    public void setCountry(String country)
    {
        this.country = country;
    }
    
    public String getStudentID()
    {
        return studentID;
    }
    
    public void setStudentID(String studentID)
    {
        this.studentID = studentID;
    }
    
    public String getSpecialty()
    {
        return specialty;
    }
    
    public void setSpecialty(String specialty)
    {
        this.specialty = specialty;
    }
    
    public String getAdmissionTime()
    {
        return admissionTime;
    }
    
    public void setAdmissionTime(String admissionTime)
    {
        this.admissionTime = admissionTime;
    }
    
    @Override
    public String toString()
    {
        StringBuffer sb = new StringBuffer();
        sb.append("[name=" + this.name + "]")
            .append(",")
            .append("[sex=" + this.sex + "]")
            .append(",")
            .append("[age=" + this.age + "]")
            .append(",")
            .append("[country=" + this.country + "]")
            .append(",")
            .append("[studentID=" + this.studentID + "]")
            .append(",")
            .append("[specialty=" + this.specialty + "]")
            .append(",")
            .append("[admissionTime=" + this.admissionTime + "]");
        return sb.toString();
    }
    
}

 

导入操作类:

1、使用WorkbookFactory.create方法将Excel数据文件加载到工厂中,根据不同的文件类型(2007还是2003)得到不同的Workbook。

2、调用Workbook.getSheetAt(0),获取第一个工作簿。

3、获取总行数,根据总行数迭代获取每一行(Row表示行)的数据。

4、使用Row的getCell获取数据,获取数据时需要注意获取的每一列的数据类型,根据不同的数据类型转换成字符串。

5、将列中数据一一对应封装到bean对象中。

package com.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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;

/**
 * 
 * 操作Excel表格的功能类
 * 
 */
public final class ExcelReader
{
    /**
     * 读取Excel数据内容
     * @param excelDataFile 待解析的文件
     * @return List<Student> 学生集合
     */
    public static List<Student> readExcelContent(File excelDataFile)
    {
        List<Student> students = new ArrayList<Student>();
        
        Workbook workbook = null;
        
        // Partner Excel 数据文件流
        InputStream inputStream = null;
        
        try
        {
            inputStream = new FileInputStream(excelDataFile);
            workbook = WorkbookFactory.create(inputStream);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (InvalidFormatException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                if (null != inputStream)
                {
                    inputStream.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        
        // 获取第一个工作簿
        Sheet sheet = workbook.getSheetAt(0);
        
        //得到总行数
        int rowNum = sheet.getLastRowNum();
        
        // 数据行
        Row row = null;
        
        //正文内容应该从第二行开始,第一行为表头的标题
        for (int i = 1; i <= rowNum; i++)
        {
            // 获取第二行(内容行)
            row = sheet.getRow(i);
            if (null != row)
            {
                students.add(buildStudent(row));
            }
        }
        
        return students;
    }
    
    /**
     * 构建Partner对象
     * @param row Excel数据行
     * @return 构建好的Student对象
     * @see [类、类#方法、类#成员]
     */
    private static Student buildStudent(Row row)
    {
        Student student = new Student();
        
        // 获取每一列的数据
        
        // i < 7 表示只读取7列数据,如果想动态获取列数,则获取表头的列数即可,调用  HSSFRow 的getPhysicalNumberOfCells()。
        //        for (int i = 0; i < 7; i++)
        //        {
        //            getStringCellValue(row.getCell(i));
        //        }
        
        // 获取每一列
        student.setName(getStringCellValue(row.getCell(0)));
        student.setSex(getStringCellValue(row.getCell(1)));
        student.setCountry(getStringCellValue(row.getCell(2)));
        student.setStudentID(getStringCellValue(row.getCell(3)));
        student.setAge(getStringCellValue(row.getCell(4)));
        student.setSpecialty(getStringCellValue(row.getCell(5)));
        student.setAdmissionTime(getStringCellValue(row.getCell(6)));
        
        return student;
    }
    
    /**
     * 根据不同的类型获取Excel单元格中的数据
     * @param cell Excel单元格
     * @return String 单元格数据内容
     */
    private static String getStringCellValue(Cell cell)
    {
        String strCell = "";
        if (null != cell)
        {
            switch (cell.getCellType())
            {
                case HSSFCell.CELL_TYPE_STRING:
                    strCell = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    // true:日期类型;false:数字类型 
                    if (DateUtil.isCellDateFormatted(cell))
                    {
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        strCell = dateFormat.format(date);
                    }
                    else
                    {
                        Double doubleValue = cell.getNumericCellValue();
                        strCell = String.valueOf(doubleValue.longValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    strCell = String.valueOf(cell.getBooleanCellValue());
                    break;
                default:
                    break;
            }
        }
        return strCell;
    }
    
    public static void main(String[] args)
    {
        // Excel 2003
        String excelFilePath = "D://student.xls";
        
        // Excel 2007
        //String excelFilePath = "D://student.xlsx";
        
        //对读取Excel表格内容测试
        List<Student> students =
            ExcelReader.readExcelContent(new File(excelFilePath));
        System.out.println("获得Excel表格的内容:");
        for (Student student : students)
        {
            System.out.println(student);
        }
    }
}

导入测试结果:

 

导出操作类:

1、new HSSFWorkbook 或者 new XSSFWorkbook。

2、创建Sheet并设置标题,Workbook 的 createSheet 方法。

3、创建表头,Sheet.createRow(0),0 表示第一行,一般第一行都作为表头标题。

4、循环读取集合中的数据。此处注意要从1(数据行)开始,因为0为表头,Sheet.createRow(1),以此类推,集合中有多少条记录,则创建多少行。

5、创建新行的每一列并将数据赋值到对应的列中Row.createCell(0),0表示第一列,以此类推,然后调用Cell的setCellValue方法赋值。

6、创建文件流,然后调用Workbook的write写入到文件流中,关闭流,注意导出的文件名称。

package com.test;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;

/**
 * 
 * 操作Excel表格的功能类
 * 支持2007和2003
 * 
 */
public final class ExcelExport
{
    /**
     * 将数据导出到Excel中
     * @param students 数据集合
     * @param filePath 导出文件路径及文件名称
     */
    public static void exportExcel(List<Student> students, String filePath)
    {
        // 创建一个工作簿
        
        // Excel 2003
        //Workbook workbook = new HSSFWorkbook();
        
        // Excel 2007
        Workbook workbook = new XSSFWorkbook();
        
        // 创建Sheet并设置标题
        Sheet sheet = workbook.createSheet("基本信息");
        
        // 创建表头
        Row headRow = sheet.createRow(0);
        headRow.createCell(0).setCellValue("姓名");
        headRow.createCell(1).setCellValue("性别");
        headRow.createCell(2).setCellValue("国籍");
        headRow.createCell(3).setCellValue("学号");
        headRow.createCell(4).setCellValue("年龄");
        headRow.createCell(5).setCellValue("专业");
        headRow.createCell(6).setCellValue("入学日期");
        
        // 读取集合中的数据,此处注意要从1(数据行)开始,因为0为表头
        for (int i = 1; i <= students.size(); i++)
        {
            // 获取一条数据
            Student student = students.get(i - 1);
            
            // 创建新行
            Row row = sheet.createRow(i);
            
            // 创建新行的每一列并将数据赋值到对应的列中
            row.createCell(0).setCellValue(student.getName());
            row.createCell(1).setCellValue(student.getSex());
            row.createCell(2).setCellValue(student.getCountry());
            row.createCell(3).setCellValue(student.getStudentID());
            row.createCell(4).setCellValue(student.getAge());
            row.createCell(5).setCellValue(student.getSpecialty());
            row.createCell(6).setCellValue(student.getAdmissionTime());
        }
        
        FileOutputStream outputStream = null;
        try
        {
            // 输出的文件路径及名称
            outputStream = new FileOutputStream(filePath);
            // 将数据写入工作簿中
            workbook.write(outputStream);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                // 关闭流
                if (null != outputStream)
                {
                    outputStream.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args)
    {
        // 数据集合
        List<Student> students = new ArrayList<Student>();
        
        // 待导出的数据
        students.add(new Student("陈美嘉", "女 ", "中国", "05412578", "24", "计算机科学与技术", "2009/9/1"));
        students.add(new Student("陆展博", "男", "中国", "05412579", "24", "计算机科学与技术", "2009/9/2"));
        students.add(new Student("关谷神奇", "男", "日本", "05412580", "24", "计算机科学与技术", "009/9/3"));
        
        // Excel 2003
        //String excelFilePath = "D:\\学生信息.xls";
        
        // Excel 2007
        String excelFilePath = "D:\\学生信息.xlsx";
        
        // 导出
        ExcelExport.exportExcel(students, excelFilePath);
        System.out.println("导出成功!");
    }
}

导出测试结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值