用Java实现对Excel的读写操作(POI)

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

import java.io.*;
import java.util.HashMap;
import java.util.Map;


public class POIReadAndWriteExcel {

    public static void main(String[] args) throws IOException {
        java.util.Map<String, Object> sheetMap = new HashMap();
        readExcel(sheetMap);
        System.out.println("中间没有业务逻辑!");
        outPutExcel(sheetMap);
    }

    public static void readExcel(java.util.Map<String, Object> sheetMap) {
        try {
            //数据流
            //使用到的Excel文件路径   C:\Users\dell\Desktop\excel\xx.xlsx
            //使用到的Excel文件路径   C:\Users\dell\Desktop\UUID.txt
            String filePath = "C:\\Users\\dell\\Desktop\\excel\\xx.xlsx";
            InputStream inp = new FileInputStream(new File(filePath));//输入流
            System.out.println("1.工作流,路径:" + filePath);
            //解析工作簿
            System.out.println("2.解析生成工作簿");
            String extString = filePath.substring(filePath.lastIndexOf("."));
            Workbook workbook = null;
            if (extString.equals(".xls")) workbook = new HSSFWorkbook(inp);//一个excel用一个HSSFWorkbook
            else if (extString.equals(".xlsx")) workbook = new XSSFWorkbook(inp);
            else {
                System.out.println("错误的文件类型:" + extString);
                return;
            }
            //解析工作表
            int size = workbook.getNumberOfSheets();
            System.out.println("一共有" + size + "个工作表Sheet");
            //循环处理读取每一个工作表中的数据
            for (int i = 0; i < size; i++) {
                Sheet sheet = workbook.getSheetAt(i);//每个sheet需要一个HSSFSheet
                System.out.println("读取当前工作表名称" + sheet.getSheetName());
                //得到有效行数
                int rowNumber = sheet.getPhysicalNumberOfRows();
                int columnNum = sheet.getRow(0).getPhysicalNumberOfCells();
                System.out.println("有效行数" + rowNumber);
                Object[][] value = null;
                value = new Object[rowNumber][];
                for (int rowIndex = 0; rowIndex < rowNumber; rowIndex++) {
                    System.out.println("读取第" + (rowIndex + 1) + "行的数据");
                    Row row = sheet.getRow(rowIndex);
                    value[rowIndex] = new Object[columnNum];
                    for (int cellIndex = 0; cellIndex < columnNum; cellIndex++) {
                        Cell cell = row.getCell(cellIndex);
                        Object cellValue = null;
                        if (cell == null) {
                            System.out.println("列值 null");
                            value[rowIndex][cellIndex] = "null";
                            continue;
                        }
                        int cellType = cell.getCellType();
                        switch (cellType) {
                            /**
                             * 数字
                             */
                            case Cell.CELL_TYPE_NUMERIC: {
                                cellValue = cell.getNumericCellValue();
                                value[rowIndex][cellIndex] = cell.getNumericCellValue();
                                break;
                            }
                            /**
                             * 字符串
                             */
                            case Cell.CELL_TYPE_STRING: {
                                cellValue = cell.getStringCellValue();
                                value[rowIndex][cellIndex] = cell.getStringCellValue();
                                break;
                            }
                            /**
                             * 布尔
                             */
                            case Cell.CELL_TYPE_BOOLEAN: {
                                break;
                            }
                            /**
                             * 公式
                             */
                            case Cell.CELL_TYPE_FORMULA: {
                                break;
                            }
                            default:
                                break;
                        }
                        System.out.println("列值:" + cellValue);
                    }
                }
                System.out.println("*************该sheet页内容********************");
                for (int x = 0; x < rowNumber; x++) {
                    for (int y = 0; y < columnNum; y++) {
                        System.out.print(value[x][y] + " ");
                    }
                    System.out.println();
                }
                System.out.println("*************该sheet页内容********************");
                sheetMap.put(sheet.getSheetName(), value);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void outPutExcel(java.util.Map<String, Object> sheetMap) {
        try {
            String filePath = "C:\\Users\\dell\\Desktop\\excel\\test_out.xlsx";
            OutputStream os = new FileOutputStream(new File(filePath));
            String extString = filePath.substring(filePath.lastIndexOf("."));
            Workbook workbook = null;
            if (extString.equals(".xls")) workbook = new HSSFWorkbook();//一个excel用一个HSSFWorkbook
            else if (extString.equals(".xlsx")) workbook = new XSSFWorkbook();
            else {
                System.out.println("错误的文件类型:" + extString);
                return;
            }
            // map无序
            for (Map.Entry<String, Object> stringObjectEntry : sheetMap.entrySet()) {
                Sheet sheet = workbook.createSheet("new-" + stringObjectEntry.getKey());
                Object[][] value = (Object[][])stringObjectEntry.getValue();
                for (int i = 0; i < value.length; i++) {
                    Row row = sheet.createRow(i);
                    for (int j = 0; j < value[i].length; j++) {
                        Cell cell = row.createCell(j);
                        if (cell == null) System.out.println("cell is null");
                        if (value[i][j] != "null") {
                            if (value[i][j] instanceof String) cell.setCellValue(value[i][j].toString());
                            if (value[i][j] instanceof Double) cell.setCellValue((double) value[i][j]);
                        }
                    }
                }
            }
            workbook.write(os);
            System.out.println("\n已生成test_out.xlsx,路径:" + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值