java 对excel 模板的读取,写入值操作

自己的备忘录

jar包不一定全部都要


    org.apache.poi
    poi
    3.15


    org.apache.poi
    poi-ooxml
    3.15


    org.apache.commons
    commons-lang3
    3.4


    commons-dbutils
    commons-dbutils
    1.6


    org.apache.poi
    poi-scratchpad
    3.9



    commons-io
    commons-io
    2.4


    commons-fileupload
    commons-fileupload
    1.3.2


@Data
public class ExcelNode {
    private int sheet; //sheet页

    // 第一个map key 是 row 多少行,第二个map key是cell 多少列,vlaue 是值
    private Map,Map,String>> value;

    //设置多个sheet页,第一个map key 是sheet页,第二个map key 是 row 多少行,第三个map key是cell 多少列,vlaue 是值
    private Map, Map,Map,String>>> setSheets;
}

因为模板在项目里,所以这样读,如果要读磁盘上的可以这样


String filePath = "C:\\Users\\Administrator\\Desktop\\1.xlsx";
File file = new File(filePath);
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));

import com.fangfa.jiliang.dto.ExcelNode;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 对excel 模板读取,写入值操作
 * @author green
 * @date 2018/6/14/014
 */
public class ExcelUtil {

   /**
    * 写入excel模板,对单个sheet页
    *@author  gl
    *@date    2018/6/14/014
    *@param
    *@return
    */
    public static Workbook writeExcelBySingletSheet(String templatePath, ExcelNode excelNode){
        String end = templatePath.substring(templatePath.lastIndexOf("."),templatePath.length());
        if(end.equalsIgnoreCase("xls")){
            return writeToExcelBySingletSheetEndXls(templatePath,excelNode);
        }else {
            return writeToExcelBySingletSheetEndXlsx(templatePath,excelNode);
        }
    }

    /**
     * 写入excel模板,对多个sheet页
     *@author  gl
     *@date    2018/6/14/014
     *@param
     *@return
     */
    public static Workbook writeExcelByMoreSheet(String templatePath, ExcelNode excelNode){
        String end = templatePath.substring(templatePath.lastIndexOf("."),templatePath.length());
        if(end.equalsIgnoreCase("xls")){
            return writeToExcelByMoreSheetEndXls(templatePath,excelNode);
        }else {
            return writeToExcelByMoreSheetEndXlsx(templatePath,excelNode);
        }
    }



    /**
     * 写入excel模板,对单个sheet页写入,主要在使用之前一定要,使用printExcel方法,(在最下面)
     * 检查一下你要替换的内容在那个部位;该方法只能用于 .xlsx 结尾的
     *@author  gl
     *@date    2018/6/14/014
     *@param templatePath:是文件模板路径,excelNode 数据对象
     *@return
     */
    public static XSSFWorkbook writeToExcelBySingletSheetEndXlsx(String templatePath, ExcelNode excelNode){
        try {
            InputStream in = UploadAndDownloadUtil.class.getClassLoader().getResourceAsStream(templatePath);
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheetAt(excelNode.getSheet());
            excelNode.getValue().forEach( (k,v) -> {
                XSSFRow row = sheet.getRow(k);
                v.forEach( (k1,v1) -> {
                    row.getCell(k1).setCellValue(v1);
                });
            });
            return workbook;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写入excel模板,对多个sheet页写入,该方法只能用于 .xlsx 结尾的
     *@author  gl
     *@date    2018/6/14/014
     *@param
     *@return
     */
    public static XSSFWorkbook writeToExcelByMoreSheetEndXlsx(String templatePath, ExcelNode excelNode){
        try {
            InputStream in = UploadAndDownloadUtil.class.getClassLoader().getResourceAsStream(templatePath);
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            excelNode.getSetSheets().forEach((k,v)->{
                XSSFSheet sheet = workbook.getSheetAt(k);
                v.forEach( (k1,v1) -> {
                    XSSFRow row = sheet.getRow(k1);
                    v1.forEach( (k2,v2) -> {
                        row.getCell(k2).setCellValue(v2);
                    });
                });
            });
            return workbook;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 该方法只能用于 .xls 结尾的
     *@author  gl
     *@date    2018/6/14/014
     *@param templatePath:是文件模板路径,excelNode 数据对象
     *@return
     */
    public static HSSFWorkbook writeToExcelBySingletSheetEndXls(String templatePath, ExcelNode excelNode){
        try {
            InputStream in = UploadAndDownloadUtil.class.getClassLoader().getResourceAsStream(templatePath);
            HSSFWorkbook workbook = new HSSFWorkbook(in);
            HSSFSheet sheet = workbook.getSheetAt(excelNode.getSheet());
            excelNode.getValue().forEach( (k,v) -> {
                HSSFRow row = sheet.getRow(k);
                v.forEach( (k1,v1) -> {
                    row.getCell(k1).setCellValue(v1);
                });
            });
            return workbook;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 写入excel模板,对多个sheet页写入,该方法只能用于 .xls 结尾的
     *@author  gl
     *@date    2018/6/14/014
     *@param
     *@return
     */
    public static HSSFWorkbook writeToExcelByMoreSheetEndXls(String templatePath, ExcelNode excelNode){
        try {
            InputStream in = UploadAndDownloadUtil.class.getClassLoader().getResourceAsStream(templatePath);
            HSSFWorkbook workbook = new HSSFWorkbook(in);
            excelNode.getSetSheets().forEach((k,v)->{
                HSSFSheet sheet = workbook.getSheetAt(k);
                v.forEach( (k1,v1) -> {
                    HSSFRow row = sheet.getRow(k1);
                    v1.forEach( (k2,v2) -> {
                        row.getCell(k2).setCellValue(v2);
                    });
                });
            });
            return workbook;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void checkRowCell(XSSFCell cell, int i, int j) {
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                System.out.println(cell.getRichStringCellValue().getString() + "="+i+":"+j);
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    System.out.println(String.valueOf(cell.getDateCellValue()) + "="+i+":"+j);
                } else {
                    System.out.println(cell.getNumericCellValue() + "="+i+":"+j);
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                System.out.println(cell.getBooleanCellValue() + "="+i+":"+j);
                break;
            default:
        }
    }

    public static void printExcel(String path) throws IOException {
        File file = new File(path);
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));
        XSSFSheet sheet = wb.getSheetAt(0);
        int rowcount = sheet.getLastRowNum() - sheet.getFirstRowNum();
        int rowcount1 = sheet.getPhysicalNumberOfRows();
        System.out.println(rowcount1);
        System.out.println("该excle的总行数为:" + (rowcount + 1) + "行 !");

        for (int i = 0; i < rowcount + 1; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
                    XSSFCell cell = (XSSFCell) row.getCell(j);
                    if (cell != null) {
                        ExcelUtil.checkRowCell(cell,i,j);
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        printExcel("C:\\Users\\Administrator\\Desktop\\1.xlsx");
    }
}

为什么要先把行列读出来呢?

在有些复杂的excel,有很多合并,行列并不是眼睛看上去的那样,先读出来在来对应



你可能感兴趣的:(java)