Java用poi解析Excel,支持xls/xlsx

由于JXL不能支持.xlsx的Excel文件,因此采用POI。
这里要用到的Jar包只需要:org.apache.poi 3.15和org.apache.poi-ooxml 3.15
在POI中,解析.XLS使用的是HSSFWorkbook,解析.XLSX的解析用的是XSSFWorkbook,需要判断处理

import java.io.File;  
import java.io.FileInputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.text.SimpleDateFormat;  

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

public class ExcelToDB {
    private static final String EXCEL_XLS = "xls";  
    private static final String EXCEL_XLSX = "xlsx";  
    //判断Excel的版本,获取Workbook 
    public static Workbook getWorkbok(InputStream in,File file) throws IOException{  
        Workbook wb = null;  
        if(file.getName().endsWith(EXCEL_XLS)){  //Excel 2003  
        wb = new HSSFWorkbook(in);  
        }else if(file.getName().endsWith(EXCEL_XLSX)){  // Excel 2007/2010  
            wb = new XSSFWorkbook(in);  
        }  
        return wb;  
    }  

    //判断文件是否是excel 
    public static void checkExcelVaild(File file) throws Exception{  
        if(!file.exists()){  
            throw new Exception("文件不存在");  
        }  
        if(!(file.isFile() && (file.getName().endsWith(EXCEL_XLS) || file.getName().endsWith(EXCEL_XLSX)))){  
            throw new Exception("文件不是Excel");  
        }  
    }  

    //由指定的Sheet导出至List 
    public static void exportListFromExcel() throws IOException {  

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");  
     try {  
            // 同时支持Excel 2003、2007  
            File excelFile = new File("D:/123.xls"); // 创建文件对象  
            FileInputStream is = new FileInputStream(excelFile); // 文件流  
            checkExcelVaild(excelFile);  
            Workbook workbook = getWorkbok(is,excelFile);  
            //Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel2003/2007/2010都是可以处理的  

            int sheetCount = workbook.getNumberOfSheets(); // Sheet的数量  
            /** 
             * 设置当前excel中sheet的下标:0开始 
             */  
            Sheet sheet = workbook.getSheetAt(0);   // 遍历第一个Sheet  

            // 为跳过第一行目录设置count  
            int count = 0;  

            for (Row row : sheet) {  
                // 跳过第一行的目录  
                if(count == 0){  
                    count++;  
                    continue;  
                }  
                // 如果当前行没有数据,跳出循环  
                if(row.getCell(0).toString().equals("")){  
                    return ;  
                }  
                String rowValue = "";  
                for (Cell cell : row) {  
                    if(cell.toString() == null){  
                        continue;  
                    }  
                    int cellType = cell.getCellType();  
                    String cellValue = "";  
                    switch (cellType) {  
                        case Cell.CELL_TYPE_STRING:     // 文本  
                            cellValue = cell.getRichStringCellValue().getString() + "#";  
                            break;  
                        case Cell.CELL_TYPE_NUMERIC:    // 数字、日期  
                            if (DateUtil.isCellDateFormatted(cell)) {  
                                cellValue = fmt.format(cell.getDateCellValue()) + "#";  
                            } else {  
                                cell.setCellType(Cell.CELL_TYPE_STRING);  
                                cellValue = String.valueOf(cell.getRichStringCellValue().getString()) + "#";  
                            }  
                            break;  
                        case Cell.CELL_TYPE_BOOLEAN:    // 布尔型  
                            cellValue = String.valueOf(cell.getBooleanCellValue()) + "#";  
                            break;  
                        case Cell.CELL_TYPE_BLANK: // 空白  
                            cellValue = cell.getStringCellValue() + "#";  
                            break;  
                        case Cell.CELL_TYPE_ERROR: // 错误  
                            cellValue = "错误#";  
                            break;  
                        case Cell.CELL_TYPE_FORMULA:    // 公式  
                            // 得到对应单元格的公式  
                            //cellValue = cell.getCellFormula() + "#";  
                            // 得到对应单元格的字符串  
                            cell.setCellType(Cell.CELL_TYPE_STRING);  
                            cellValue = String.valueOf(cell.getRichStringCellValue().getString()) + "#";  
                            break;  
                        default:  
                            cellValue = "#";  
                    }  
                    //System.out.print(cellValue);  
                    rowValue += cellValue;  
                }    
                System.out.println(rowValue);  
                System.out.println();  
            }   
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally{    
        }  
    } 
}

常见错误:解析.XLSX时出现“java.lang.NoSuchFieldError: RAW_XML_FILE_HEADER ”
原因是在我引入了3.15的版本后又不小心引入了3.14版本,把3.14版本的Jar包移除,使用正确的3.15问题就不会发生。

感谢原文作者,点击查看原文

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
你可以使用Apache POI库来解析Excel文件。下面是一个使用Java解析Excel文件的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExcelParser { public static void main(String[] args) { String filePath = "path/to/your/excel/file.xlsx"; // 替换为你的Excel文件路径 try { FileInputStream fis = new FileInputStream(new File(filePath)); Workbook workbook; if (filePath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(fis); // 处理.xlsx文件 } else if (filePath.endsWith(".xls")) { workbook = new HSSFWorkbook(fis); // 处理.xls文件 } else { throw new IllegalArgumentException("The specified file is not Excel file"); } Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 for (Row row : sheet) { for (Cell cell : row) { CellType cellType = cell.getCellType(); if (cellType == CellType.STRING) { System.out.print(cell.getStringCellValue() + " "); } else if (cellType == CellType.NUMERIC) { System.out.print(cell.getNumericCellValue() + " "); } else if (cellType == CellType.BOOLEAN) { System.out.print(cell.getBooleanCellValue() + " "); } } System.out.println(); } workbook.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 请将代码中的`"path/to/your/excel/file.xlsx"`替换为你实际的Excel文件路径。该代码会打开Excel文件并输出每个单元格的值。你可以根据需要对解析的内容进行进一步处理。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值