POI parsing Excel table .xls and .xlsx general solution

Some time ago, I saw that the import and export operations of Excel documents were given on other websites, which seemed very cool, so I learned how to use POI to perform Excel operations, and now I will summarize the previous learning process.

1. There are two types of Excel documents, xls and xlsx, which are commonly used now. Excel documents in xls format are further divided into 5.0/95 workbooks and 97-2003 workbooks. It should be noted that because the version of the 5.0/95 workbook is too low, the current POI document no longer supports the reading of this type of Excel document. When trying to read this type of Excel document, POI will throw a An exception (OldExcelFormatException) is thrown. The POI I am using now is version 3.14.

2. Creation of Workbook

1. Since there are two formats of xls and xlsx in Excel, the creation methods are also different. For documents in xls format, you need to use HSSFWorkbook to create workbook objects, and for Excel documents in xlsx format, you need to use XSSFWrokbook to create workbooks. One thing to note is that the two classes, HSSFWorkbook and XSSFWorkbook, are actually an implementation class of the Workbook interface. Well, here is the code to create the workbook object:

//Create a non-existing excel file
    private static Workbook createWorkbookIfNotExist(String fileName) throws Exception {
        Workbook wb = null;
        
        if(fileName.endsWith(".xls")) {
            wb = new HSSFWorkbook();
        } else if(fileName.endsWith(".xlsx")) {
            wb = new XSSFWorkbook();
        } else {
            throw new Exception("File type error!");
        }
        
        try{
            OutputStream output = new FileOutputStream(fileName);
            wb.write(output);
        }catch(FileNotFoundException e) {
            System.out.println("File creation failed, the reason for the failure is: " + e.getMessage());
            throw new FileNotFoundException();
        }
        System.out.println(fileName + "The file was created successfully!");
        
        return wb;
    }
    
    //Create a Workbook for a new or existing Excel document
    public static Workbook createWorkbook(String fileName) throws Exception {
        InputStream input = null;
        Workbook wb = null;
        
        try{
            input = new FileInputStream(fileName);
            wb = WorkbookFactory.create(input);
        } catch(FileNotFoundException e) {
            System.out.println("The file to be opened does not exist, trying to create it, please wait...!");
            wb = createWorkbookIfNotExist(fileName);
        } catch(OldExcelFormatException e) {
            System.out.println("Failed to open the file, reason: the version of the Excel file to be opened is too low!");
            throw new OldExcelFormatException("The file version is too old");
        } finally {
            if(input != null) {
                input.close();
            }
        }
        
        return wb;
    }
2. When creating a Sheet, there are also two types of HSSFSheet and XSSHSheet. The same HSSFSheet and XSSFSheet classes are also the implementation classes of the Sheet interface. If you directly use the implementation class to create a Sheet, then, for different formats, you need to use different implementation methods, although the implementation methods are the same. Due to Java's polymorphism, here I use the Sheet interface for processing. Code:
//create sheet
    public static Sheet createSheet(Workbook wb , String sheetName) {
        Sheet sheet = wb.getSheet(sheetName);
        
        if(sheet == null) {
            System.out.println("Form" + sheetName + "Does not exist, try to create the sheet, please wait...");
            sheet = wb.createSheet(sheetName);
            System.out.println("名为" + sheetName +"的sheet创建成功!");
        }
        
        return sheet;
    }
3、对于Row的创建,也是一样,也是使用Row这个接口进行实现。代码:
//创建行row
    public static Row createRow(Sheet sheet , int rowNum) {
        Row row = sheet.getRow(rowNum);
        
        if(row == null) {
            System.out.println("行号为:" + rowNum + "的行不存在,正试图创建该行,请稍后……");
            row = sheet.createRow(rowNum);
            System.out.println("行号为:" + rowNum + "的行创建成功!");
        }
        
        return row;
    }

4、对于Cell也是一样,同样使用Cell接口进行编程。代码:
//创建单元格cell
    public static Cell createCell(Row row , int cellNum) {
        Cell cell = row.getCell(cellNum);
        
        if(cell == null) {
            System.out.println("该单元格不存在,正在试图创建该单元格,请稍后……");
            cell = row.createCell(cellNum);
            System.out.println("The cell was created successfully!");
        }
        
        return cell;
    }
The above operations are the creation of Workbook, Sheet, Row, and Cell. In addition, when the operation on the Excel document is completed, you need to use the write method of Workbook to save it, and then the above changes will be saved in the Excel document you created. Code:
wb03.write(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\03styleExcel.xls"));
wb07.write(new FileOutputStream("C:\\Users\\Administrator\\Desktop\\07styleExcel.xlsx"));

Well, this blog post ends here. If there are any mistakes or deficiencies in the article, I hope you will give pointers. The following blog posts will introduce how to write data in different formats into Excel documents, as well as operations such as borders, pictures, merging cells, hiding and showing rows, etc.

My summary: You can judge whether to create an HSSFWorkbook or an XSSFWorkbook based on the suffix name of the uploaded Excel file, and then use Sheet, Row, and Cell later, so that a method can be used universally.

Reprinted with https://www.cnblogs.com/jiang2016/p/5728102.html

Intrusion



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324597252&siteId=291194637