摘要:Java使用poi读写Excel文件

(点击查看所有代码,直接复制即可运行)

1、简介:

Apache POI支持大多数中小规模的应用程序开发,提供API给Java程序对Microsoft Office格式档案读和写的功能,呈现和文本提取是它的主要特点。

2、结构:

       HSSF:
      提供读写Microsoft Excel XLS格式档案的功能。
       XSSF:
      提供读写Microsoft Excel OOXML XLSX格式档案的功能。
       HWPF:
      提供读写Microsoft Word DOC格式档案的功能。
       HSLF:
      提供读写Microsoft PowerPoint PPT格式档案的功能。
       HDGF:
      提供读Microsoft Visio格式档案的功能。
       HPBF:
      提供读Microsoft Publisher格式档案的功能。
       HSMF:
      提供读Microsoft Outlook格式档案的功能。

pom.xml添加maven依赖
<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
</dependency>
导入需要用到的包
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
1. 创建文件对象,并判断Excel文件类型(xls或xlsx),根据不同类型进行对应操作
//1. 创建文件对象,并判断Excel文件类型(xls或xlsx),根据不同类型进行对应操作
		
		//实例化 File 对象
        File file = new File("E:/uuidsss_OTAO_1.xlsx");
        if (excel.isFile() && excel.exists()) {   //判断文件是否存在
            String[] split = excel.getName().split("\\.");  //.是特殊字符,需要转义!!!!!
            
            //创建 Workbook 对象 和 文件流对象
            Workbook wb = null;
            FileInputStream fis = new FileInputStream(excel);   //文件流对象
            
            //根据文件后缀(xls/xlsx)进行判断
            if ("xls".equals(split[1])) {  //xls 文件进行
                wb = new HSSFWorkbook(fis);
            } else if ("xlsx".equals(split[1])) {
                wb = new XSSFWorkbook(fis);
            } else {
                System.out.println("文件类型错误!");
            }
         }
2. java对 Excel 表中关于工作表的操作
//开始解析
            //使用for循环对 Excel 表 中的工作表进行循环操作
            for (int i = 0; i < wb.getNumberOfSheets(); i++) { // getNumberOfSheets()获得工作表的数量

                Sheet sheet = wb.getSheetAt(i);     //读取sheet 0

                //获取工作表的相关信息
                System.out.println("工作表的数量 = " + wb.getNumberOfSheets());
                System.out.println("工作表的名字 = " + wb.getSheetName(i));

                //读首行和尾行的行数
                int firstRowIndex = sheet.getFirstRowNum();
                int lastRowIndex = sheet.getLastRowNum();
                System.out.println("第一行的索引(firstRowIndex) = " + firstRowIndex);
                System.out.println("最后一行的索引(lastRowIndex) = " + lastRowIndex);

                //读取第一行的列数
                Row row0 = sheet.getRow(firstRowIndex);
                int firstCellIndex = row0.getFirstCellNum();
                int lastCellIndex = row0.getLastCellNum();
                System.out.println("第一列的索引(firstCellIndex) = " + firstCellIndex);
                System.out.println("最后一列的索引(lastCellIndex) = " + lastCellIndex);
            }
            //更多操作请参考下表

memory三维数组 三维数组存储图解_用三维数组存储Excel

3. 开始遍历表格并存储在一个三维数组中
//开始遍历表格并给三维数组赋值
                double[][] tmp1 = new double[lastRowIndex + 1][lastCellIndex + 1];
                for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //一行一行地遍历
                    Row row = sheet.getRow(rIndex); //得到一行的数据
                    if (row != null) {
                        double[] tmp2 = new double[lastCellIndex];
                        for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
                            Cell cell = row.getCell(cIndex);
                            if (cell != null) {
                                cell.setCellType(CellType.STRING);
                                if (!cell.getStringCellValue().isEmpty()) {
                                    tmp2[cIndex] = Double.parseDouble(cell.getStringCellValue());
                                   // System.out.println("第"+rIndex+"行,第"+cIndex+"列");
                                    fileOutputStream.write((cell.getStringCellValue()+"\n").getBytes());
                                }
                            }
                        }
                        tmp1[rIndex] = tmp2;
                    }
                }
4. 遍历该三维数组检验数据
// 增强型for循环遍历
            System.out.println("res[i][j][k] : ");
            for (int i = 0; i < res.length; i++) {
                double[][] a = res[i];
                System.out.println("第 " + i + " 个数组");
                System.out.println("[");
                for (int j = 0; j < a.length; j++) {
                    double[] b = a[j];
                    for (int k = 0; k < b.length; k++) {
                        System.out.println(res[i][j][k]);
                    }
                }
                System.out.println("]");
            }

全部 Java 代码

package ****;//改为自己的包名

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

@RestController
@CrossOrigin(originPatterns = "*",allowCredentials="true",allowedHeaders = "*",methods = {})//跨域设置
public class Eli_Code_Excel_Read {
    //         main主类
    public static void main(String args[]) throws Exception {
        //实例化 File 对象
        String file = new String("E:/");//设置文件所在的位置

        //实例化本对象,调用 readPicExcel 方法解析 Excel文件
        Eli_Code_Excel_Read PE = new Eli_Code_Excel_Read();
        PE.readPicExcel(file);
    }
    //读取一个含有多个Sheet的Excel表,并将数据存储在一个三维数组中
    public static double[][][] readPicExcel(@RequestParam("filePath") String filePath) throws Exception {
        String url = filePath + "uuidsss_OTAO_1.xlsx";//要读取的文件名
        double[][][] res = new double[3][][];
        File excel = new File(url);
        if (excel.isFile() && excel.exists()) {   //判断文件是否存在
            String[] split = excel.getName().split("\\.");  //.是特殊字符,需要转义!!!!!
            //创建 Workbook 对象 和 文件流对象
            Workbook wb = null;
            FileInputStream fis = new FileInputStream(excel);   //文件流对象

            //根据文件后缀(xls/xlsx)进行判断
            if ("xls".equals(split[1])) {  //xls 文件进行
                wb = new HSSFWorkbook(fis);
            } else if ("xlsx".equals(split[1])) {
                wb = new XSSFWorkbook(fis);
            } else {
                System.out.println("文件类型错误!");
            }

            //开始解析
            //对 Excel 表 中的工作表进行循环操作
            for (int i = 0; i < wb.getNumberOfSheets(); i++) { // getNumberOfSheets()获得工作表的数量
                Sheet sheet = wb.getSheetAt(i);     //读取sheet

                //获取工作表的相关信息
                System.out.println("工作表的数量 = " + wb.getNumberOfSheets());
                System.out.println("工作表的名字 = " + wb.getSheetName(i));

                //读首行和尾行的行数
                int firstRowIndex = sheet.getFirstRowNum();
                int lastRowIndex = sheet.getLastRowNum();
                System.out.println("第一行的索引(firstRowIndex) = " + firstRowIndex);
                System.out.println("最后一行的索引(lastRowIndex) = " + lastRowIndex);

                //读取第一行的列数
                Row row0 = sheet.getRow(firstRowIndex);
                int firstCellIndex = row0.getFirstCellNum();
                int lastCellIndex = row0.getLastCellNum();
                System.out.println("第一列的索引(firstCellIndex) = " + firstCellIndex);
                System.out.println("最后一列的索引(lastCellIndex) = " + lastCellIndex);


                //打开一个txt文件的输出流,准备将 Excel 中的数据写入 txt 文件
                File filetxt = new File("E:/num_"+i+".txt");
                if(filetxt.exists()){
                    //判断txt文件是否存在,如果不存在就新建一个txt
                    filetxt.createNewFile();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(filetxt);

                //开始遍历表格并赋值
                double[][] tmp1 = new double[lastRowIndex + 1][lastCellIndex + 1];
                for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //一行一行地遍历
                    Row row = sheet.getRow(rIndex); //得到一行的数据
                    if (row != null) {
                        double[] tmp2 = new double[lastCellIndex];
                        for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
                            Cell cell = row.getCell(cIndex);
                            if (cell != null) {
                                cell.setCellType(CellType.STRING);
                                if (!cell.getStringCellValue().isEmpty()) {
                                    tmp2[cIndex] = Double.parseDouble(cell.getStringCellValue());
                                    //System.out.println("第"+rIndex+"行,第"+cIndex+"列");
                                    fileOutputStream.write((cell.getStringCellValue()+"\n").getBytes());
                                }
                            }
                        }
                        tmp1[rIndex] = tmp2;
                    }
                }
                //关闭txt的文件流
                fileOutputStream.flush();
                fileOutputStream.close();
                res[i] = tmp1;
            }

            // 增强型for循环遍历
            System.out.println("res[i][j][k] : ");
            for (int i = 0; i < res.length; i++) {
                double[][] a = res[i];
                System.out.println("第 " + i + " 个数组");
                System.out.println("[");
                for (int j = 0; j < a.length; j++) {
                    double[] b = a[j];
                    for (int k = 0; k < b.length; k++) {
                        System.out.println(res[i][j][k]);
                    }
                }
                System.out.println("]");
            }
            System.out.println(res[0].length);
            return res;
        } else {
            return res;
        }

    }
}