com.fjn.helper.common.io.file.office.excel.ExcelMgr.java Source code

Java tutorial

Introduction

Here is the source code for com.fjn.helper.common.io.file.office.excel.ExcelMgr.java

Source

/*
 *
 *  Copyright 2018 FJN Corp.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Author                        Date                       Issue
 *  fs1194361820@163.com          2015-01-01                 Initial Version
 *
 */

package com.fjn.helper.common.io.file.office.excel;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.fjn.helper.common.exception.FileDirFaultException;
import com.fjn.helper.common.io.file.common.FileUtil;
import com.fjn.helper.common.io.file.office.excel.Excel.ExcelType;
import com.fjn.helper.common.io.file.office.excel.exception.NullExcelException;
import com.fjn.helper.common.util.StreamUtil;

public class ExcelMgr {

    public static Excel createExcel(Excel.ExcelType type) {
        return new Excel(type);
    }

    /**
     * ?WorkBook
     *
     * @param type
     * @return
     */
    public static Workbook createWorkBook(Excel.ExcelType type) {
        Workbook wb = null;
        switch (type) {
        case XLSX:
            wb = new XSSFWorkbook();
            break;
        case XLS:
            wb = new HSSFWorkbook();
            break;
        default:
            wb = new SXSSFWorkbook();
            break;
        }
        return wb;
    }

    /**
     * workbook
     *
     * @param workbook
     * @param sheetname
     * @return
     */
    public static <T extends ExcelSheet> T addSheet(Excel excel, String sheetname, Class<T> sheetClass) {
        T t = null;
        Workbook workbook = excel.getWorkbook();
        try {
            t = sheetClass.newInstance();
            Sheet sheet = workbook.createSheet(sheetname);
            t.setSheet(sheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 
     *
     * @param path
     * @param fileName
     * @param workbook
     */
    public static void writeToFile(String path, String fileName, Excel excel) {
        if (excel == null || excel.getWorkbook() == null || excel.getType() == null)
            return;
        FileOutputStream out = null;
        // ?
        File dir = new File(path);
        boolean exist = dir.exists();

        fileName = FileUtil.setFileSuffix(fileName, excel.getFileExt());
        // fileName=FileHelper.getFileNameForDownload(fileName);

        if (exist) {
            try {
                dir = new File(dir + "/" + fileName);// 
                if (!dir.exists())
                    dir.createNewFile();
            } catch (Exception e) {
            }
        } else { // ???
            try {
                exist = dir.mkdirs();
                dir = new File(dir + "/" + fileName);// 
                dir.createNewFile();
                exist = true;
            } catch (Exception e) {
                throw new FileDirFaultException(path);
            }
        }
        if (!exist) {
            throw new FileDirFaultException(path);
        }

        try {
            out = new FileOutputStream(path + "/" + fileName);
            excel.getWorkbook().write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 
     *
     * @param response
     * @param fileName
     * @param workbook
     */
    public static void writeToBrowser(HttpServletResponse response, String fileName, Excel excel) throws Exception {
        if (excel == null || excel.getWorkbook() == null)
            throw new NullExcelException();
        if (excel.getType() == null)
            throw new NullPointerException("excel type is null");
        if (fileName == null) {
            throw new NullPointerException("export file name is null.");
        }
        response.setCharacterEncoding("UTF-8");
        fileName = FileUtil.setFileSuffix(fileName, excel.getFileExt());
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.addHeader("Content-Disposition",
                "attachment;filename=" + FileUtil.getFileNameForDownload(fileName));
        OutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            excel.getWorkbook().write(out);
            bos.flush();
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtil.close(bos);
            StreamUtil.close(out);
        }

    }

    /**
     * ?
     *
     * @param out
     * @param workbook
     */
    public static void writeToOutputStream(OutputStream out, Excel excel) {
        if (excel == null || excel.getWorkbook() == null)
            return;
        try {
            excel.getWorkbook().write(out);
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static Excel getExcel(InputStream in) {
        Workbook wb = null;
        try {
            wb = WorkbookFactory.create(in);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (wb == null)
            return null;
        if (wb instanceof HSSFWorkbook) {
            Excel excel = new Excel(ExcelType.XLS, false);
            excel.setWorkbook(wb);
            return excel;
        } else if (wb instanceof XSSFWorkbook) {
            Excel excel = new Excel(ExcelType.XLSX, false);
            excel.setWorkbook(wb);
            return excel;
        } else {
            Excel excel = new Excel(ExcelType.SXLSX, false);
            excel.setWorkbook(wb);
            return excel;
        }
    }

}