Java Batch Operation Excel File Practice

Abstract: This article was originally published on CSDN by the technical team of Grape City. Please indicate the source of the reprint: Grape City official website , Grape City provides developers with professional development tools, solutions and services to empower developers.

Preface | Problem Background

In the scenario of operating Excel, there are usually some batch operations for Excel. There are generally two meanings of batch:

Operate batches of Excel files. Such as importing multiple Excel files and processing data, or exporting multiple Excel files. In such scenarios, the operation is often very similar, but the Excel file needs to be read and written repeatedly. Perform batch operations on single or multiple. For example, for Excel files, replace text in batches, add formulas in batches or add styles in batches. In such scenarios, generally there are not many Excel files that need to be operated, but specific operations need to be performed repeatedly. In this case, an easy-to-use API is needed to help.

Among the existing Excel components, POI is a very commonly used component, but for the above-mentioned different scenarios, it puts forward two types of requirements for the components.

The first type of scenario reads or writes files repeatedly, and requires components to be well optimized for memory, otherwise it is prone to memory overflow (out of memory) problems.

The second type of scenario requires components to provide easy-to-use APIs, such as replacing strings, if there is no interface API for find (find) or replace (replace). You need to iterate through the cells yourself to find the value.

Although POI may be lacking in the above two requirements, there are other components to choose from, such as EasyExcel, GcExcel, etc.

The following uses GcExcel as an example to list examples for the above two types of scenarios.

What is GcExcel?

Scenario 1 Import Excel files in batches and read data in a specific area

For example, there are multiple Excel files with GUID names. These Excel files come from the reported data, and the contents need to be summarized.

For example, the content of the Excel form is as follows:

It is necessary to fetch the values ​​of the grids from B3 to C6, and the following code can be used to extract the data.

@Test

  public void testImportFormFile() {
    
    

    String folderPath = "path/testFolder"; //使用你的路径

    File folder = new File(folderPath);

    File[] files = folder.listFiles();

    if (files != null) {
    
    

      for (File file: files){
    
    

       if(file.isFile() && file.getName().endsWith(".xlsx")){
    
    

          Workbook wb = new Workbook();

          wb.open(file.getAbsolutePath());

          Object[][] value = (Object[][]) wb.getActiveSheet().getRange("B3:C6").getValue();

          System.out.println(value[0][1]); //小葡萄

          System.out.println(value[1][1]); //20.0

          System.out.println(value[2][1]); //开发部

          System.out.println(value[3][1]); //610123456789012345

           //添加处理数据的逻辑

        }

      }

    }

  }

Get all Excel files through the listFiles() method. Read each file in a loop, and open the Excel file through GcExcel. Use the getValue() method on IRange to read the grid in Excel as a two-dimensional array.

Business logic can then be processed by accessing the two-dimensional array.

Scenario 2 Export Excel files in batches, and write the data in a specific location before exporting

Continuing with the first Excel file as an example, when there is already some data in the database, you want to write and export the data to multiple Excel files or export it as a PDF file.

Real scenarios include, for example, when an enterprise pays wages, it needs to issue an electronic payslip to each employee every month, because the salary slip information of each employee is different. In this scenario, the data needs to be exported in batches as Plural PDFs.

@Test
  public void testExportFormFile() {
    
    
    String outPutPath = "E:/testFolder";
    //给valueList初始化数据,替换为从数据库,CSV或者JSON等中获取数据。
    ArrayList<Object[][]> valueList = new ArrayList<Object[][]>();
    for (Object[][] value : valueList) {
    
    
      Workbook wb = new Workbook();
      wb.getActiveSheet().getRange("B3:C6").setValue(value);
      wb.save(outPutPath + UUID.randomUUID().toString() + ".xlsx");
    }
  }

GcExcel can directly set a two-dimensional array to a range, and after loading the data from the database, it can be sorted into a two-dimensional array.

Then set the two-dimensional array directly on the sheet through GcExcel's SetValue(), and finally save and export it through the save method on the workbook.

Scenario 3 Open the Excel file and replace keywords in batches

In this scenario, you need to use the Excel file as a template, and replace some custom keywords in it with data.

For example, if there is a standard report, the data needs to be filled in. Such as table header, name, report-related entries, data and other information. It is possible to make the report into a template, and then leave the header, name, etc. blank, or use keywords as placeholders. For example, "%Name%" can be used as a placeholder for the name, and %Name% can be replaced when filling in the data.

@Test
    public void testReplaceTemplateFile() {
    
    
        String templateFilePath = "test.xlsx";
        Workbook wb = new Workbook();
        wb.open(templateFilePath);
        IRange usedRange = wb.getActiveSheet().getUsedRange();
        //load data
        ArrayList<Object[]> valueList = new ArrayList<Object[]>();
        for (Object[] value : valueList) {
    
    
            usedRange.replace(value[0],value[1]);
        }
        wb.save("result.xlsx", SaveFileFormat.Xlsx);
    }

Open the template file through the workbook, and after preparing the data, replace the custom keywords directly through the replace method of IRange.

After the replacement, save it as a new Excel.

For more advanced and complex data filling, GcExcel also has a template function. After setting the template, you can directly bind the data source, and GcExcel will automatically fill the data into the template.

Scenario 4 Open the Excel template file and obtain calculation results in batches

For example, there is an Excel file for calculating insurance or industry data. You need to fill in a value at a fixed position, and use a formula in Excel to calculate the result.

@Test
  public void testCalcFormulaByTemplateFile() {
    
    
    String templateFilePath = "E:/testFolder/testFormula.xlsx";
    Workbook wb = new Workbook();
    wb.open(templateFilePath);
	 //``获取特定的值,比如以下
    ArrayList<Object[]> valueList = new ArrayList<Object[]>();
    for (Object[] value : valueList) {
    
    
      
       Object A1Value = value[0];
      Object A2Value = value[1];
      Object result = null;
      wb.getActiveSheet().getRange("A1").setValue(A1Value);
      wb.getActiveSheet().getRange("A2").setValue(A2Value);
      result = wb.getActiveSheet().getRange("A3").getValue();
      System.out.println(result);
    }
  }

The formula calculation of GcExcel is calculated when the value is obtained, so there is no need to display and call methods such as calculate. You only need to prepare the input parameters and put them in a specific cell in Excel to directly obtain the calculation results of the formula. .

The above are some common methods of batch processing Excel. We only use the code of GcExcel Java as an example. The same idea can also be implemented using other components.

Extension link:

GrapeCity Documents for Excel (server-side Excel component) V3.0 is officially released

It is so simple to use it to develop the "online Excel" system!

How to use JavaScript to implement front-end import and export excel files

Guess you like

Origin blog.csdn.net/powertoolsteam/article/details/131539634