JAVA 处理 Excel 的两种常见方法

  • 一、JXL 处理 Excel
  • 1.1 Jxl 写入Excel
  • 1.2 Jxl 读取Excel
  • 1.3 Jxl 读取 Excel 并写入另一个 Excel
  • 二、Poi 处理 Excel
  • 2.1 HSSFWorkbook 处理 Excel
  • 2.1.1 HSSFWorkbook 介绍
  • 2.1.2 HSSFWorkbook 读取 Excel
  • 2.1.3 HSSFWorkbook 写入 Excel
  • 2.2 XSSFWorkbook 处理 Excel
  • 2.2.1 XSSFWorkbook 介绍
  • 2.2.2 XSSFWorkbook 读取 Excel
  • 2.12.3 XSSFWorkbook 写入 Excel


JAVA 处理 Excel 的两种常见方法 Demo地址

一、JXL 处理 Excel

1.1 Jxl 写入Excel

1.1.1 Jxl 依赖
依赖下载地址Jxl依赖地址

<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

1.1.2 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zz</groupId>
    <artifactId>excel-demo</artifactId>
    <version>1.0</version>

    <dependencies>
        <!--jxl-->
        <dependency>
            <groupId>net.sourceforge.jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6.12</version>
        </dependency>
    </dependencies>

</project>

1.1.3 Java 代码

/**
 * <p>
 * Jxl处理Excel
 * </p>
 *
 * @author W
 */
public class JxlForExcel {
    public static void main(String[] args) {
        wirteExcel();
    }

    /**
     * 写入Excel
     */
    public static void wirteExcel() {
        WritableWorkbook wb = null;
        try {
            //文件地址
            File file = new File("D:/ExcelDemo/demo1_write.xls");
            //创建文件
            file.createNewFile();
            //创建Excel
            wb = Workbook.createWorkbook(file);
            //创建Sheet
            WritableSheet sheet1 = wb.createSheet("Sheet1", 1);
            //设置文件第一行的titie
            String[] title = {"姓名", "性别", "成绩"};
            //创建单元格
            Label label = null;
            for (int i = 0; i < title.length; i++) {
                label = new Label(i, 0, title[i]);
                sheet1.addCell(label);
            }
            //手动添加数据
            for (int i = 1; i < 5; i++) {
                //第一行第一列
                label = new Label(0, i, "张三");
                sheet1.addCell(label);
                //第一行第二列
                label = new Label(1, i, "男");
                sheet1.addCell(label);
                //第一行第三列
                label = new Label(2, i, "88");
                sheet1.addCell(label);
            }
            //写入数据到Excel文件
            wb.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

1.2 Jxl 读取Excel

1.1.1 要读取的表格

表格共三个Sheet,其中只有Sheet1和Sheet2有数据,Sheet为空白

java中xls与xlsx java处理xlsx_Jxl 处理 Excel


java中xls与xlsx java处理xlsx_java中xls与xlsx_02

1.1.2 Java 代码

/**
 * <p>
 * Jxl处理Excel
 * </p>
 *
 * @author W
 */
public class JxlForExcel {
    public static void main(String[] args) {
        readExcel();
    }

    /**
     * 读取EXCEL
     */
    public static void readExcel() {
        InputStream is = null;
        Workbook wb = null;
        try {
        	//文件地址
        	File file = new File("D:/ExcelDemo/demo1.xls");
            //读取文件
            is = new FileInputStream(file.getAbsoluteFile());
            wb = Workbook.getWorkbook(is);
            //获取Excel的总sheet数量
            int sheetsNum = wb.getNumberOfSheets();
            for (int i = 0; i < sheetsNum; i++) {
                System.out.println("========== Sheet" + (i + 1) + " ==========");
                //获取Sheet对象
                Sheet sheet = wb.getSheet(i);
                //获取该Sheet的总行数
                int rowsNum = sheet.getRows();
                for (int j = 0; j < rowsNum; j++) {
                    //获取每行的总列数
                    int columnsNum = sheet.getColumns();
                    for (int k = 0; k < columnsNum; k++) {
                        //获取每个单元格的值
                        String content = sheet.getCell(k, j).getContents();
                        System.out.print(content + " ");
                    }
                    System.out.println();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (wb != null) {
                wb.close();
            }
        }
    }
}

(3)输出结果

========== Sheet1 ==========
序号 姓名 性别 
1 张三 男 
2 李四 女 
3 王二 男 
4 赵六 女 
5 吴七 保密 
========== Sheet2 ==========
序号 姓名 成绩 
1 张三 98 
2 李四 85 
3 王二 73 
4 赵六 45 
5 吴七 34 
========== Sheet3 ==========

1.3 Jxl 读取 Excel 并写入另一个 Excel

1.3.1 Java 代码

/**
 * <p>
 * Jxl处理Excel
 * </p>
 *
 * @author W
 */
public class JxlForExcel {
    public static void main(String[] args) {
        readAndWriteExcel();
    }

    /**
     * 读取并写入Excel
     */
    public static void readAndWriteExcel() {
        InputStream is = null;
        WritableWorkbook wwb = null;
        Workbook wb = null;
        try {
            //原Excel文件地址
            File oldFile = new File("D:/ExcelDemo/demo1.xls");
            //新Excel文件地址
            File newFile = new File("D:/ExcelDemo/new_demo1.xls");
            //创建新Excel文件
            newFile.createNewFile();
            //创建Excel
            wwb = Workbook.createWorkbook(newFile);
            //读取原Excel文件
            is = new FileInputStream(oldFile.getAbsoluteFile());
            wb = Workbook.getWorkbook(is);
            //获取原Excel的总sheet数量
            int sheetsNum = wb.getNumberOfSheets();
            for (int i = 0; i < sheetsNum; i++) {
                //在新Excel创建Sheet
                WritableSheet newSheet = wwb.createSheet("Sheet" + i, i);
                //获取Sheet对象
                Sheet oldSheet = wb.getSheet(i);
                //获取该Sheet的总行数
                int rowsNum = oldSheet.getRows();
                for (int j = 0; j < rowsNum; j++) {
                    //获取每行的总列数
                    int columnsNum = oldSheet.getColumns();
                    Label label = null;
                    for (int k = 0; k < columnsNum; k++) {
                        //获取每个单元格的值
                        String content = oldSheet.getCell(k, j).getContents();
                        //在新Excel中创建单元格
                        label = new Label(k, j, content);
                        //设置单元格值
                        newSheet.addCell(label);
                    }
                }
            }
            //写入数据到新Excel
            wwb.write();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (wwb != null) {
                try {
                    wwb.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (wb != null) {
                try {
                    wb.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

二、Poi 处理 Excel

2.1 HSSFWorkbook 处理 Excel

2.1.1 HSSFWorkbook 介绍

(1)HSSFWorkbook 介绍
HSSFWorkbook 是操作Excel2003以前(包括2003)的版本,扩展名是.xls

(2)常用组件

HSSFWorkbook                      excel的文档对象
HSSFSheet                         excel的表单
HSSFRow                           excel的行
HSSFCell                          excel的格子单元
HSSFFont                          excel字体
HSSFDataFormat                    日期格式
HSSFHeader                        sheet头
HSSFFooter                        sheet尾(只有打印的时候才能看到效果)

(3)样式

HSSFCellStyle                       cell样式

(3)辅助操作

HSSFDateUtil                        日期
HSSFPrintSetup                      打印
HSSFErrorConstants                  错误信息表

(4)HSSFWorkbook 依赖

<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>

2.1.2 HSSFWorkbook 读取 Excel

(1)Java 代码
要读取的表格内容同上

/**
 * HSSFWorkbook 解析 .xls文件
 *
 * @author W
 */
public class ReadExcelByHSSF {
    public static void main(String[] args) {
        InputStream is = null;
        HSSFWorkbook wb = null;
        try {
            //文件地址
            File file = new File("D:/ExcelDemo/demo1.xls");
            //读取文件
            is = new FileInputStream(file);
            wb = new HSSFWorkbook(is);
            //获取Excel的总sheet数量
            int sheetsNum = wb.getNumberOfSheets();
            for (int i = 0; i < sheetsNum; i++) {
                System.out.println("========== Sheet" + (i + 1) + " ==========");
                //获取Sheet对象
                HSSFSheet sheet = wb.getSheetAt(i);
                //获取该Sheet的总行数
                int rowNum = sheet.getLastRowNum();
                for (int j = 0; j < rowNum; j++) {
                    //获取该行对象
                    HSSFRow rows = sheet.getRow(j);
                    //获取每行的总单元格数
                    short cellNum = rows.getLastCellNum();
                    for (int k = 0; k < cellNum; k++) {
                        //获取每个单元格的值
                        HSSFCell cell = rows.getCell(k);
                        //获取单元格的数据类型
                        int cellType = cell.getCellType();
                        switch (cellType) {
                            //数字类型
                            case Cell.CELL_TYPE_NUMERIC:
                                int numValue = (int) cell.getNumericCellValue();
                                System.out.print(numValue + " ");
                                break;
                            //字符串类型
                            case Cell.CELL_TYPE_STRING:
                                String stringValue = cell.getStringCellValue();
                                System.out.print(stringValue + " ");
                                break;
                        }
                    }
                    System.out.println();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

(2)输出结果

========== Sheet1 ==========
序号 姓名 性别 
1 张三 男 
2 李四 女 
3 王二 男 
4 赵六 女 
========== Sheet2 ==========
序号 姓名 成绩 
1 张三 98 
2 李四 85 
3 王二 73 
4 赵六 45 
========== Sheet3 ==========

2.1.3 HSSFWorkbook 写入 Excel

(1)Java 代码

/**
 * HSSFWorkbook 写入 .xls文件
 * 创建一个包含3个sheet,每个sheet为5行3列的 .xls文件
 *
 * @author W
 */
public class WriteExcelByHSSF {

    public static void main(String[] args) {
        FileOutputStream os = null;
        HSSFWorkbook wb = null;
        try {
            //文件地址
            File file = new File("D:/ExcelDemo/HSSFWorkbook_write.xls");
            os = new FileOutputStream(file);
            //创建文件
            file.createNewFile();
            //创建工作对象
            wb = new HSSFWorkbook();
            //创建Sheet
            for (int i = 0; i < 3; i++) {
                HSSFSheet sheet = wb.createSheet("sheet" + i);
                //创建行
                for (int j = 0; j < 5; j++) {
                    HSSFRow row = sheet.createRow(j);
                    //创建单元格
                    for (int k = 0; k < 3; k++) {
                        //给单元格赋值
                        HSSFCell cell = row.createCell(k);
                        cell.setCellValue("第" + j + "行,第" + k + "列");
                    }
                }

            }
            //写入数据到Excel文件
            wb.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

(2)输出结果

java中xls与xlsx java处理xlsx_Poi 处理 Excel_03

2.2 XSSFWorkbook 处理 Excel

2.2.1 XSSFWorkbook 介绍

(1)XSSFWorkbook 介绍
XSSFWorkbook 是操作Excel2007的版本,扩展名是.xlsx。

(2)XSSF的常用类

XSSFWorkbook:Excel文档对象
XSSFSheet:Excel的表单
XSSFRow:Excel的行
XSSFCell:Excel的单元格
XSSFCellStyle:Excel单元格的实现
XSSFCellHeader:Excel的表单头部
XSSFCellFooter:Excel的表单尾部

(3)依赖

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

2.2.2 XSSFWorkbook 读取 Excel

(1)Java 代码
要读取的表格内容同上

/**
 * XSSFWorkbook 解析 .xlsx文件
 *
 * @author W
 */
public class ReadExcelByXSSF {

    public static void main(String[] args) {
        FileInputStream is = null;
        XSSFWorkbook wb = null;
        try {
            //文件地址
            File file = new File("D:/ExcelDemo/demo1.xlsx");
            //读取文件
            is = new FileInputStream(file);
            //获取工作簿对象
            wb = new XSSFWorkbook(is);
            //获取Excel的总sheet数量
            int sheetsNum = wb.getNumberOfSheets();
            for (int i = 0; i < sheetsNum; i++) {
                System.out.println("========== Sheet" + (i + 1) + " ==========");
                //获取Sheet对象
                XSSFSheet sheet = wb.getSheetAt(i);
                //获取该sheet的总行数
                int rowNum = sheet.getLastRowNum();
                for (int j = 0; j < rowNum; j++) {
                    //获取行对象row
                    XSSFRow row = sheet.getRow(j);
                    //获取每行的单元格数
                    short cellNum = row.getLastCellNum();
                    for (int k = 0; k < cellNum; k++) {
                        //获取单元格对象
                        XSSFCell cell = row.getCell(k);
                        //根据单元格数据类型进行取值
                        switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                int numValue = (int) cell.getNumericCellValue();
                                System.out.print(numValue + " ");
                                break;
                            case Cell.CELL_TYPE_STRING:
                                String stringValue = cell.getStringCellValue();
                                System.out.print(stringValue + " ");
                                break;
                        }
                    }
                    System.out.println("");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

(2)输出结果

========== Sheet1 ==========
序号 姓名 性别 
1 张三 男 
2 李四 女 
3 王二 男 
4 赵六 女 
========== Sheet2 ==========
序号 姓名 成绩 
1 张三 98 
2 李四 85 
3 王二 73 
4 赵六 45 
========== Sheet3 ==========

2.12.3 XSSFWorkbook 写入 Excel

(1)Java 代码

/**
 * XSSFWorkbook 写入 .xlsx文件
 * 创建一个包含3个sheet,每个sheet为5行3列的 .xls文件
 *
 * @author W
 */
public class WriteExcelByXSSF {

    public static void main(String[] args) {
        FileOutputStream os = null;
        XSSFWorkbook wb = null;
        try {
            //文件地址
            File file = new File("D:/ExcelDemo/XSSFWorkbook_write.xlsx");
            os = new FileOutputStream(file);
            //创建文件
            file.createNewFile();
            //创建工作对象
            wb = new XSSFWorkbook();
            //创建Sheet
            for (int i = 0; i < 3; i++) {
                XSSFSheet sheet = wb.createSheet("sheet" + i);
                //创建行
                for (int j = 0; j < 5; j++) {
                    XSSFRow row = sheet.createRow(j);
                    //创建单元格
                    for (int k = 0; k < 3; k++) {
                        //给单元格赋值
                        XSSFCell cell = row.createCell(k);
                        cell.setCellValue("第" + j + "行,第" + k + "列");
                    }
                }

            }
            //写入数据到Excel文件
            wb.write(os);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

(2)输出结果

java中xls与xlsx java处理xlsx_HSSFWorkbook_04