JAVA-获取Excel文件的第一行数据

1、pom.xml引入相关依赖

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.18</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.0.0</version>
        </dependency>

2、读取Excel

    /**
     * 读取excel
     * @param file  excel文件
     * @param Suffix 文件后缀名,判断是不是excel文件,区分excel版本
     * @return
     */
    public static Workbook readExcel(File file, String Suffix){
        Workbook wb = null;
        if(file==null){
            return null;
        }
        InputStream is =  null;
        try {
            is = new FileInputStream(file);
            if("xls".equals(Suffix)){
                return wb = new HSSFWorkbook(is);
            }else if("xlsx".equals(Suffix)){
                return wb = new XSSFWorkbook(is);
            }else{
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

3、读取文件的第一列数据

   /**
     * 获取excel第一个sheet的第一行数据
     * @param file
     * @param suffix
     * @return
     */
    public static LinkedHashSet<String> getTopRow(File file, String suffix){
        LinkedHashSet<String> result = new LinkedHashSet<>();
        Workbook  wb = readExcel(file, suffix); //文件
        Sheet sheet = wb.getSheetAt(0); //sheet
        Row row = sheet.getRow(0);
        for (int i=0; i<row.getLastCellNum(); i++){
            String cellData = (String) getCellFormatValue(row.getCell(i));
            result.add(cellData.replaceAll(" ", ""));
        }
        return result;
    }

4、私有方法getCellFormatValue转换单元格的值

    private static Object getCellFormatValue(Cell cell){
        Object cellValue = null;
        if(cell!=null){
            //判断cell类型
            CellType cellType = cell.getCellType();
            switch(cellType){
                case NUMERIC:{
                    if(DateUtil.isCellDateFormatted(cell)){
                        //excel文件内的日期列若设置单元格格式为日期,读取的值和文件内看到的不一样,
//需要根据num对应的格式进行转换,最好是直接在上传页面强制要求单元格格式为文本一劳永逸,
//因为num对应的日期格式不同版本的jar包不一样,成本太高但是工期够就无所谓了可慢慢研究。
                        short num  = cell.getCellStyle().getDataFormat();
                        String format = ExcelConstant.dateFormatMap.get(num);
                        SimpleDateFormat df = new SimpleDateFormat(format);
                        cellValue = df.format(cell.getDateCellValue());
                    }else{
                        cell.setCellType(CellType.STRING);  //将数值型cell设置为string型
                        cellValue = cell.getStringCellValue();
                    }
                    break;
                }
                case FORMULA:{
                    //判断cell是否为日期格式
                    if(DateUtil.isCellDateFormatted(cell)){
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    }else{
                        //数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case STRING:{
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
            }
        }else{
            cellValue = "";
        }
        return cellValue;
    }

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是一个示例代码,演示如何使用Java下载zip文件并解析其中的Excel文件获取数据。 ```java import java.io.*; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; public class ZipExcelParser { public static void main(String[] args) throws Exception { // Step 1: 下载zip文件 String url = "https://example.com/file.zip"; // zip文件的URL String zipFilePath = "file.zip"; // 下载后的zip文件路径 downloadFile(url, zipFilePath); // Step 2: 解析Excel文件 String excelFilePath = null; // Excel文件路径 try (ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFilePath))) { ZipEntry entry = zip.getNextEntry(); while (entry != null) { String fileName = entry.getName(); if (fileName.endsWith(".xlsx")) { // 只处理.xlsx文件 excelFilePath = fileName; File file = new File(excelFilePath); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = zip.read(bytes)) >= 0) { fos.write(bytes, 0, length); } fos.close(); break; } entry = zip.getNextEntry(); } } // Step 3: 获取Excel数据 List<List<String>> data = new ArrayList<>(); Workbook workbook = new XSSFWorkbook(new FileInputStream(excelFilePath)); Sheet sheet = workbook.getSheetAt(0); // 假设数据在第一个Sheet中 for (Row row : sheet) { List<String> rowData = new ArrayList<>(); for (Cell cell : row) { rowData.add(cell.toString()); } data.add(rowData); } workbook.close(); // 打印数据 for (List<String> rowData : data) { System.out.println(String.join(",", rowData)); } } // 下载文件 private static void downloadFile(String url, String filePath) throws Exception { BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fos = new FileOutputStream(filePath); byte[] dataBuffer = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { fos.write(dataBuffer, 0, bytesRead); } fos.close(); in.close(); } } ``` 请注意,此示例代码使用了Apache POI库来解析Excel文件。如果您尚未安装它,请在项目中添加以下依赖项: ```xml <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> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值