Java uses poi to import and export excel (various ways)

1. Excel import and export

1. Export to Excel through the local export template (suitable for more complicated export of headers)

This is the template I put locally 

The following is the method I exported

I put the queried data into a two-dimensional array and export it by reading the data of the two-dimensional array

 

 

The data after exporting is

 

2. Export data through excel via POI  

Go directly to the code, you need to create a user entity class yourself

@Override
    public void downloadFile(HttpServletRequest request,HttpServletResponse response) {
        try {
            
            User users = new User();
            users.setId("1222");
            users.setUsername("张三");
            users.setPhone("1760767162");
            users.setAddress("深圳塘朗");
            users.setCardno("4325241995086246");
            users.setTitel("java删库到跑路");
            users.setState("");
               //获取数据
            List<User> list = new ArrayList<User>();
             list.add(users);

               // excel title
               String[] title = {"student name", "mobile phone number", "ID number", "address", "course name", "course payment status", "id"};

               // excel file name
               String fileName = "agent"+users.getUsername()+" enrollment information statistics table" + System.currentTimeMillis() + ".xls";
               // CellRangeAddress callRangeAddress = new
               // CellRangeAddress(0, 0,0,6);//start row, end row, start column, end column

               // sheet名
               String sheetName = "招生信息统计表22";
               String[][] content = new String[list.size()][title.length];
               String state = "";
               for (int i = 0; i < list.size(); i++) {
                  // content[i] = new String[title.length];
                  User user = list.get(i);
                  if(null != user.getState()){
                     state="已付费";
                  }else {
                     
                     state = "未付费";
                  }
                  /*
                   * Date date = obj.getReportDate(); content[i][0] =
                   * sDateFormat.format(date);
                   */
                  
                  content[i][0] = user.getUsername();
                  content[i][1] = user.getPhone() + "";
                  content[i][2] = user.getCardno() + "";
                  content[i][3] = user.getAddress() + "";
                  content[i][4] = user.getTitel();
                  content[i][5] = state;
                  content[i][6] = user .getId();
               }
               //The content of the merged cell
               String mergeCell = "Agent"+users.getUsername()+"Total number of students enrolled:"+list.size()+"people";
               Integer cellNum = 5;//Merge 6 columns of cells
               // Create
               HSSFWorkbook // HSSFWorkbook wb1 = new HSSFWorkbook();
               HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null,mergeCell,cellNum);
               // File errFile = new File(CoinConfig.RESOURCE_BASIC_PATH+"/"
               // +fileName);
               // 响应到客户端
               try {
                  this.setResponseHeader(response, fileName);
                  OutputStream os = response.getOutputStream();
                  // OutputStream os = new FileOutputStream(errFile);
                  wb.write(os);
                  os.flush();
                  os.close();
               } catch (Exception e) {
                  e.printStackTrace();
               }
        
        
        } catch (Exception e) {             log.error("Download failed", e);         }     }


        

Tool method

public class ExcelUtil {

   /**
     * Export Excel
     * @param sheetName sheet name
     * @param title title
     * @param values ​​content
     * @param wb HSSFWorkbook object
     * @return
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][ ]values, HSSFWorkbook wb,String mergeCell,Integer cellNum ){

        // The first step is to create a HSSFWorkbook, corresponding to an Excel file
        if(wb == null){             wb = new HSSFWorkbook();         }

        // The second step is to add a sheet to the workbook, corresponding to the sheet
        HSSFSheet sheet in the Excel file = wb.createSheet(sheetName);

        // The third step is to add row 0 of the header to the sheet. Note that the old version of poi has a limit on the number of rows and columns of Excel.
        HSSFRow row = sheet.createRow(0);

        // The fourth step is to create a cell and set the value header. Set the header to be centered.
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // Create a centered format

        //Declare the column object
        HSSFCell cell = null;
        
        if (StringUtils.isNotEmpty(mergeCell)) {            //Merge cell             CellRangeAddress callRangeAddress = new CellRangeAddress(0,0,0,cellNum);//Start row, end row, start Start column, end column             sheet.addMergedRegion(callRangeAddress);             cell = row.createCell(0);             cell.setCellValue(mergeCell);             cell.setCellStyle(style);             row = sheet.createRow(1);          // HSSFCell cell = null ;             //Create title             for(int i=0;i<title.length;i++){                 cell = row.createCell(i);                 cell.setCellValue(title[i]);












                cell.setCellStyle(style);
            }

            //Create content
            for(int i=0;i<values.length;i++){                 row = sheet.createRow(i + 2);                 for(int j=0;j<values[i].length;j++){                     //Assign the content to the corresponding column object in order                     row.createCell(j).setCellValue(values[i][j]);                 }             }       }else{          // HSSFCell cell = null;            //Create title            for(int i =0;i<title.length;i++){                cell = row.createCell(i);                cell.setCellValue(title[i]);                cell.setCellStyle(style);            }







         






           //Create content
           for(int i=0;i<values.length;i++){                row = sheet.createRow(i + 1);                for(int j=0;j<values[i].length;j++){                    //Assign the content to the corresponding column objects in order                    row.createCell(j).setCellValue(values[i][j]);                }            }       }         return wb;     } } 3. You can export by configuring the html template






         




 

Guess you like

Origin blog.csdn.net/qq_39008613/article/details/104994921