Java工具类:将Excel文件转成字符串数组

pom.xml



    org.apache.poi
    poi
    3.17


    org.apache.poi
    poi-excelant
    3.17


    org.apache.poi
    poi-ooxml
    3.17


    org.apache.poi
    poi-ooxml-schemas
    3.17


    org.apache.poi
    poi-scratchpad
    3.17


    org.apache.xmlbeans
    xmlbeans
    2.6.0


    com.github.virtuald
    curvesapi
    1.04


ExcelUtils.java

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.usermodel.WorkbookFactory;

import java.io.*;
import java.util.Iterator;

/**
 * Excel工具类
 * @author [email protected]
 * @version 2018-8-9 20:26:30
 */
public class ExcelUtils {

    /**
     * 将Excel文件转成字符串数组。支持xls、xlsx
     * @param in Excel文件输入流
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static String[][] copyData(InputStream in) throws IOException, InvalidFormatException {
        Workbook wb = WorkbookFactory.create(in);
        Sheet sheet = wb.getSheetAt(0);
        int rowNumber = sheet.getPhysicalNumberOfRows() - 1;
        Iterator rowIterator = sheet.rowIterator();
        Row titleRow = rowIterator.next();
        int columnNumber = titleRow.getLastCellNum();
        String[][] table = new String[rowNumber][columnNumber];
        for (int i = 0; i < rowNumber && rowIterator.hasNext(); i++) {
            Row row = rowIterator.next();
            for (int j = 0; j < columnNumber; j++) {
                Cell cell = row.getCell(j);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    table[i][j] = cell.getStringCellValue().trim();
                } else {
                    table[i][j] = "";
                }
            }
        }
        return table;
    }

    /**
     * 将Excel文件转成字符串数组。支持xls、xlsx
     * @param bytes Excel文件字节数组
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static String[][] copyData(byte[] bytes) throws IOException, InvalidFormatException {
        return copyData(new ByteArrayInputStream(bytes));
    }

    /**
     * 将Excel文件转成字符串数组。支持xls、xlsx
     * @param file Excel文件
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static String[][] copyData(File file) throws IOException, InvalidFormatException {
        return copyData(new FileInputStream(file));
    }

}

你可能感兴趣的:(Java)