当前位置 : 主页 > 编程语言 > java >

java POI实现导入导出功能

来源:互联网 收集:自由互联 发布时间:2023-09-03
导入POI库的依赖项,在项目中加入以下Maven依赖项: dependency groupIdorg.apache.poi/groupId artifactIdpoi/artifactId version4.1.2/version/dependencydependency groupIdorg.apache.poi/groupId artifactIdpoi-ooxml/artifactId ve
  1. 导入POI库的依赖项,在项目中加入以下Maven依赖项:
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
  1. 导入所需的POI类:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFCell;
  1. 实现导出功能:
public class ExcelExporter {
    public static void exportData(List<List<String>> data, String filePath) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Sheet1");

            int rowNum = 0;
            for (List<String> rowData : data) {
                Row row = sheet.createRow(rowNum++);
                int colNum = 0;
                for (String cellData : rowData) {
                    Cell cell = row.createCell(colNum++);
                    cell.setCellValue(cellData);
                }
            }

            try (FileOutputStream outputStream = new FileOutputStream(filePath)) {
                workbook.write(outputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 实现导入功能:
public class ExcelImporter {
    public static List<List<String>> importData(String filePath) {
        List<List<String>> data = new ArrayList<>();

        try (Workbook workbook = WorkbookFactory.create(new File(filePath))) {
            Sheet sheet = workbook.getSheetAt(0);

            for (Row row : sheet) {
                List<String> rowData = new ArrayList<>();
                for (Cell cell : row) {
                    rowData.add(cell.getStringCellValue());
                }
                data.add(rowData);
            }
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        }

        return data;
    }
}

以上代码示例展示了如何使用POI库实现Excel文件的导入和导出功能。可以根据自己的需求进行修改和扩展。


上一篇:Java List常见面试题
下一篇:没有了
网友评论