poi achieve import and export data excel

Content from the network, intrusion deleted.

1, the required jar package

 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi</artifactId>
     <version>3.14</version>
 </dependency>
 <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
       <version>3.14</version>
 </dependency>

2, kits, packages may be adjusted based on actual business tool

Package Comkjbfakutil;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/*********************************
 * Class Description:
 * @author huangsz
 * @date 2019/11/21
 * @version v1.0
 **********************************/
public class ExcelUtil {

    public static void main(String[] args) throws Exception{
    }

    public static void exportExcel(HttpServletResponse response,
                                   String title, String subheading,
                                   List<String> header,
                                   List <List <String >> dataList) throws Exception {
         // create a workbook 
        HSSFWorkbook Workbook = new new HSSFWorkbook ();
         // create a row 
        HSSFCellStyle CellStyle = workbook.createCellStyle ();
         // centered 
        cellStyle.setAlignment (HSSFCellStyle.ALIGN_CENTER);
         // create a Sheet 
        HSSFSheet Sheet = workbook.createSheet ( "Sheet name" );
         // create a title 
        CellRangeAddress CellRangeAddress = new new CellRangeAddress (0, 0, 0 , header.size ());
         //Create a subtitle 
        CellRangeAddress cellRangeAddress2 = new new CellRangeAddress (. 1,. 1, 0 , header.size ());
        sheet.addMergedRegion(cellRangeAddress);
        sheet.addMergedRegion(cellRangeAddress2);

        // title, centered 
        HSSFRow ROW0 = sheet.createRow (0 );
        HSSFCell cell0 = row0.createCell(0);
        cell0.setCellValue(title);
        cell0.setCellStyle(cellStyle);

        // first row 
        HSSFRow sheet.createRow ROW1 = (. 1 );
        HSSFCell cell1 = row1.createCell(0);
        // 副标题
        cell1.setCellValue(subheading);
        cell1.setCellStyle(cellStyle);

        // 表头
        HSSFRow row = sheet.createRow(2);
        HSSFCell cell = null;
        for (int i = 0; i < header.size(); i++) {
            cell =  row.createCell(i);
            cell.setCellValue(header.get(i));
            cell.setCellStyle(cellStyle);
        }

        // 数据
        for (int i = 0; i < dataList.size(); i++) {
            row = sheet.createRow(i + 3);
            for (int j = 0; j < dataList.get(i).size(); j++) {
                row.createCell(j).setCellValue(dataList.get(i).get(j));
            }
        }

        OUT OutputStream = response.getOutputStream ();
         // set the page does not cache 
        response.reset ();
        String fileName = URLEncoder.encode(title, "UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
        response.setContentType("application/msexcel");
        workbook.write(out);
        out.close();
    }

    /**
     * Import Data
     * @Param File Table
     * @Param sheetIndex Sheet index value
     * @Param headerIndex index header (used to obtain a total of how many columns and start reading the first few lines of data)
     * @return
     * @throws Exception
     */
    public static List<List<Object>> importExcel(MultipartFile file, int sheetIndex, int headerIndex) throws Exception {
        List<List<Object>> data = new ArrayList<>();
        Workbook workbook = getWorkbook(file);
        // 导入某页sheet
        if (sheetIndex >-1) {
            Sheet sheet = workbook.getSheetAt(sheetIndex);
            List<List<Object>> lists = importSheet(sheet, headerIndex);
            data.addAll(lists);
        } The else {
             // Import All
             // import all 
            for ( int I = 0; I <workbook.getNumberOfSheets (); I ++ ) {
                Sheet sheet = workbook.getSheetAt(i);
                if (sheet == null) {
                    continue;
                }
                List<List<Object>> lists = importSheet(sheet, headerIndex);
                data.addAll(lists);
            }
        }
        return data;
    }

    private static List<List<Object>> importSheet(Sheet sheet, int headerIndex) throws Exception {
        List <List <Data Object >> = new new the ArrayList <> ();
         // get the number of rows 
        int Row = sheet.getLastRowNum ();
         // Row = -1 no data table
         // Row = headerIndex form the following table header no data (means no useful data) 
        IF (Row Row == == -1 || headerIndex) {
             the throw  new new Exception ( "no useful data table!" );
        }
        // Get the number of columns 
        int columnNum = sheet.getRow (headerIndex) .getPhysicalNumberOfCells ();
         // starts to fetch data from the next line header 
        for ( int I = headerIndex +. 1; I <= Row; I ++ ) {
            Row row1 = sheet.getRow(i);
            List<Object> list = new ArrayList<>();
            if (row1 != null) {
                for (int j = 0; j < columnNum; j++) {
                    list.add(getCellValue(row1.getCell(j)));
                }
            }
            data.add(list);
        }
        return data;
    }

    private static Object getCellValue(Cell cell) {
        String cellValue = "";
        DecimalFormat df = new DecimalFormat("#");
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_STRING:
                cellValue = cell.getRichStringCellValue().getString().trim();
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                cellValue = df.format(cell.getNumericCellValue());
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue()).trim();
                break;
            case HSSFCell.CELL_TYPE_FORMULA:
                cellValue = cell.getCellFormula();
                break;
            default:
                cellValue = "";
        }
        return cellValue.trim();
    }


    private static Workbook getWorkbook(MultipartFile file) throws Exception{
        Workbook workbook = null;
        String xls = "xls";
        XLSX String = "XLSX" ;
         // get the file name 
        String fileName = file.getOriginalFilename ();
         IF (fileName.endsWith (XLS)) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else if(fileName.endsWith(xlsx)){
            workbook = new XSSFWorkbook(file.getInputStream());
        } The else {
             the throw  new new Exception ( "file formats bad!" );
        }
        return workbook;
    }
}

3. Verify

@GetMapping("/exe")
    public void excel(HttpServletResponse response) {
        List<String> header = new ArrayList<>();
        header.add ( "comment Id" );
        header.add ( "the commentator Id" );
        header.add ( "Content" );
        TestBean bean = new TestBean();
        List<List<String>> dataList = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            List<String> data = new ArrayList<>();
            data.add(i+"");
            data.add(i+1+"");
            data.add ( "first" + i + "reviews" );
            dataList.add(data);
        }
        try {
            ExcelUtil.exportExcel (the Response, "title", "subtitle" , header, dataList);
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

    @PostMapping("/up")
    public void upload(@RequestParam("file") MultipartFile file){
        try {
            List<List<Object>> lists = ExcelUtil.importExcel(file, 0,2);
            System.out.println(lists.size());
            for (List<Object> list : lists) {
                for (Object o : list) {
                    System.out.println(o);
                }
            }
        } catch (Exception e) {
            e.printStackTrace ();
        }
    }

 

Guess you like

Origin www.cnblogs.com/hsz-csy/p/11909753.html