Java Poi操作Excel文件

本文提供了一个Java类用于操作Excel文件(.xlsx)的方法实现,包括文件创建、数据读取及写入等核心功能,并附带了一个简单的测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Excel操作类

  1. package excelTest;
  2.    
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.util.List;
  9. import java.util.Map;
  10.    
  11. import org.apache.poi.xssf.usermodel.XSSFCell;
  12. import org.apache.poi.xssf.usermodel.XSSFRow;
  13. import org.apache.poi.xssf.usermodel.XSSFSheet;
  14. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  15.    
  16. public class ExcelOperation {
  17.    private static XSSFWorkbook workbook = null;
  18.    
  19.    /**
  20.     *判断文件是否存在.
  21.     */
  22.    public static boolean fileExist(String fileDir) {
  23.        boolean flag = false;
  24.        File file = new File(fileDir);
  25.        flag = file.exists();
  26.        return flag;
  27.    }
  28.    
  29.    /**
  30.     *判断文件的sheet是否存在.
  31.     */
  32.    public static boolean sheetExist(String fileDir, String sheetName) throws Exception {
  33.        boolean flag = false;
  34.        File file = new File(fileDir);
  35.        if (file.exists()) {
  36.            try {
  37.                workbook = new XSSFWorkbook(new FileInputStream(file));
  38.                XSSFSheet sheet = workbook.getSheet(sheetName);
  39.                if (sheet != null)
  40.                    flag = true;
  41.            } catch (Exception e) {
  42.                throw e;
  43.            }
  44.        } else {
  45.            flag = false;
  46.        }
  47.        return flag;
  48.    }
  49.    
  50.    /**
  51.     *创建新excel
  52.     */
  53.    public static void createExcel(String fileDir, String sheetName, String titleRow[]) throws Exception {
  54.        workbook = new XSSFWorkbook();
  55.        FileOutputStream out = null;
  56.        try {
  57.            XSSFRow row = workbook.createSheet(sheetName).createRow(0);
  58.            for (int i = 0; i < titleRow.length; i++) {
  59.                XSSFCell cell = row.createCell(i);
  60.                cell.setCellValue(titleRow[i]);
  61.            }
  62.            out = new FileOutputStream(fileDir);
  63.            workbook.write(out);
  64.        } catch (Exception e) {
  65.            throw e;
  66.        } finally {
  67.            try {
  68.                if (out != null) {
  69.                    out.close();
  70.                }
  71.            } catch (IOException e) {
  72.                e.printStackTrace();
  73.            }
  74.        }
  75.    }
  76.    
  77.    /**
  78.     *excel中写入mapList.size()行数据
  79.     */
  80.    public static void writeToExcelRow(String fileDir, String sheetName, List<Map<String, String>> mapList, int rowId)
  81.            throws Exception {
  82.        File file = new File(fileDir);
  83.        try {
  84.            workbook = new XSSFWorkbook(new FileInputStream(file));
  85.        } catch (FileNotFoundException e) {
  86.            e.printStackTrace();
  87.        } catch (IOException e) {
  88.            e.printStackTrace();
  89.        }
  90.        FileOutputStream out = null;
  91.        XSSFSheet sheet = workbook.getSheet(sheetName);
  92.        // 获取表格的总行数
  93.        // introwCount = sheet.getLastRowNum() + 1; // 需要加一
  94.        // 获取表头的列数
  95.        int columnCount = sheet.getRow(0).getLastCellNum();
  96.        try {
  97.            XSSFRow titleRow = sheet.getRow(0);
  98.            if (titleRow != null) {
  99.                for (Map<String, String> map : mapList) {
  100.                    XSSFRow newRow = sheet.createRow(rowId++);
  101.                    for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
  102.                        String mapKey = titleRow.getCell(columnIndex).toString().trim();
  103.                        XSSFCell cell = newRow.createCell(columnIndex);
  104.                        cell.setCellValue(map.get(mapKey) == null ? null : map.get(mapKey).toString());
  105.                    }
  106.                }
  107.            }
  108.            
  109.            out = new FileOutputStream(fileDir);
  110.            workbook.write(out);
  111.        } catch (Exception e) {
  112.            throw e;
  113.        } finally {
  114.            try {
  115.                if (out != null) {
  116.                    out.close();
  117.                }
  118.            } catch (IOException e) {
  119.                e.printStackTrace();
  120.            }
  121.        }
  122.    }
  123.    
  124.    /**
  125.     *excel中写入一格数据
  126.     */
  127.    public static void writeToExcelCell(String fileDir, String sheetName, String value, int rowId, int columnId)
  128.            throws Exception {
  129.        File file = new File(fileDir);
  130.        try {
  131.            workbook = new XSSFWorkbook(new FileInputStream(file));
  132.        } catch (FileNotFoundException e) {
  133.            e.printStackTrace();
  134.        } catch (IOException e) {
  135.            e.printStackTrace();
  136.        }
  137.        FileOutputStream out = null;
  138.        XSSFSheet sheet = workbook.getSheet(sheetName);
  139.        // 获取表格的总行数
  140.        // introwCount = sheet.getLastRowNum() + 1; // 需要加一
  141.        // 获取表头的列数
  142.        // intcolumnCount = sheet.getRow(0).getLastCellNum();
  143.        try {
  144.            XSSFRow row = sheet.getRow(rowId);
  145.            if (row != null) {
  146.                XSSFCell cell = row.getCell(columnId);
  147.                if (cell != null) {
  148.                    cell.setCellValue(value == null ? null : value);
  149.                } else {
  150.                    XSSFCell newCell = row.createCell(columnId);
  151.                    newCell.setCellValue(value == null ? null : value);
  152.                }
  153.            }
  154.            
  155.            out = new FileOutputStream(fileDir);
  156.            workbook.write(out);
  157.        } catch (Exception e) {
  158.            throw e;
  159.        } finally {
  160.            try {
  161.                if (out != null) {
  162.                    out.close();
  163.                }
  164.            } catch (IOException e) {
  165.                e.printStackTrace();
  166.            }
  167.        }
  168.    }
  169.    
  170. }

    测试

    1. package excelTest;
    2.     
    3. import java.util.ArrayList;
    4. import java.util.HashMap;
    5. import java.util.List;
    6. import java.util.Map;
    7.     
    8. public class ExcelTest {
    9.     
    10.     public static void main(String[] args) throws Exception{
    11.         String excelFilePath="D:/test.xlsx";
    12.         String sheetName="sheet0";
    13.         String[] titleRow={"id", "name", "password"};
    14.         
    15.         Map<String, String> map1=new HashMap<String, String>();
    16.         map1.put("id","1001");
    17.         map1.put("name", "anna");
    18.         map1.put("password", "ANNA");
    19.         Map<String, String> map2=new HashMap<String, String>();
    20.         map2.put("id","1002");
    21.         map2.put("name", "bob");
    22.         map2.put("password", "BOB");
    23.         List<Map<String, String>> mapList=new ArrayList<Map<String, String>>();
    24.         mapList.add(map1);
    25.         mapList.add(map2);
    26.         
    27.         System.out.println(ExcelOperation.fileExist(excelFilePath));     
    28.         ExcelOperation.createExcel(excelFilePath, sheetName, titleRow);
    29.         System.out.println(ExcelOperation.fileExist(excelFilePath));
    30.         ExcelOperation.writeToExcelRow(excelFilePath, sheetName, mapList, 1);//从表的第二行开始写
    31.     }
    32.     
    33. }

      结果

      这里写图片描述

      jar包

      需要的jar包

      这里写图片描述

      jar包下载:http://poi.apache.org

      ps:本文处理的是.xlsx文件,把代码中XSSF全部改成HSSF即可访问.xls文件。xls文件是07版之前的,一张表最多只能存65536行数据。xlsx是07版之后的Excel,可以存很多很多很多…
      评论
      添加红包

      请填写红包祝福语或标题

      红包个数最小为10个

      红包金额最低5元

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

      抵扣说明:

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

      余额充值