1. 程式人生 > >Excel讀寫工具類

Excel讀寫工具類

緣起

在J2SE和J2EE應用程式開發中,經常會遇到上傳Excel,匯出Excel的功能開發,對Excel的操作無非就是讀取Excel檔案內容轉成javabean,或者是將javabean物件寫入Excel檔案中。為了方便對Excel進行讀寫操作,可以將這塊程式碼進行封裝,讀取Excel的操作封裝在ExcelReadKit,寫入Excel的操作封裝在ExcelWriteKit工具類中。

核心程式碼

下面會寫出核心的java程式碼,其中會用到apache poi 這個開源組建對Excel進行讀寫操作。

ExcelConfig.java

import org.apache.poi.ss.usermodel.Cell;

public
class ExcelConfig { // Excel檔案輸出格式 public static final String FT_XLS = "xls"; public static final String FT_XLSX = "xlsx"; // Excel格資料型別 public static final int CT_NUMERIC = Cell.CELL_TYPE_NUMERIC; public static final int CT_STRING = Cell.CELL_TYPE_STRING; public static final
int CT_BOOLEAN = Cell.CELL_TYPE_BOOLEAN; public static final int CT_BLANK = Cell.CELL_TYPE_BLANK; public static final int CT_FORMULA = Cell.CELL_TYPE_FORMULA; }

ExcelReadResultBean.java


import java.util.List;

public class ExcelReadResultBean {
    private boolean result = true;
    private
String errMsg = ""; private List<List<String>> contentList = null; public boolean getResult() { return result; } public void setResult(boolean result) { this.result = result; } public String getErrMsg() { return errMsg; } public void setErrMsg(String errMsg) { this.errMsg = errMsg; } public List<List<String>> getContentList() { return contentList; } public void setContentList(List<List<String>> contentList) { this.contentList = contentList; } }

ExcelWriteBean.java

package com.trendy.fw.common.excel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ExcelWriteBean {
    String fileName = "";// 檔名,不帶字尾
    String fileType = "";// 檔案型別,xsl或xslx
    String sheetName = "";// sheet名
    List<String> headerList = new ArrayList<String>();// 表頭列表,可以為空
    List<List<Object>> contentList = new ArrayList<List<Object>>();// 內容列表
    HashMap<Integer, Integer> cellTypeMap = new HashMap<Integer, Integer>();// 表格型別,不填寫預設為字串
    HashMap<Integer, String> cellFormatMap = new HashMap<Integer, String>();// 表格格式,不填寫預設為字串格式

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public String getSheetName() {
        return sheetName;
    }

    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }

    public List<String> getHeaderList() {
        return headerList;
    }

    public void setHeaderList(List<String> headerList) {
        this.headerList = headerList;
    }

    public List<List<Object>> getContentList() {
        return contentList;
    }

    public void setContentList(List<List<Object>> contentList) {
        this.contentList = contentList;
    }

    public HashMap<Integer, Integer> getCellTypeMap() {
        return cellTypeMap;
    }

    public void setCellTypeMap(HashMap<Integer, Integer> cellTypeMap) {
        this.cellTypeMap = cellTypeMap;
    }

    public void setCellType(int cellIndex, int cellType) {
        cellTypeMap.put(cellIndex, cellType);
    }

    public HashMap<Integer, String> getCellFormatMap() {
        return cellFormatMap;
    }

    public void setCellFormatMap(HashMap<Integer, String> cellFormatMap) {
        this.cellFormatMap = cellFormatMap;
    }

    public void setCellFormat(int cellIndex, String cellFormat) {
        cellFormatMap.put(cellIndex, cellFormat);
    }
}

ExcelReadKit.java

package com.trendy.fw.common.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
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.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.trendy.fw.common.util.DateKit;

public class ExcelReadKit {

    protected static Logger log = LoggerFactory.getLogger(ExcelReadKit.class);

    /**
     * 
     * @param filePath
     *            檔案路徑
     * @param sheetIndex
     *            第x個sheet
     * @return
     */
    public ExcelReadResultBean readExcel(String filePath, int sheetIndex) {
        ExcelReadResultBean resultBean = new ExcelReadResultBean();
        try {
            Sheet sheet = null;
            if (filePath.endsWith(ExcelConfig.FT_XLS)) {
                FileInputStream fis = new FileInputStream(filePath); // 根據excel檔案路徑建立檔案流
                POIFSFileSystem fs = new POIFSFileSystem(fis); // 利用poi讀取excel檔案流
                HSSFWorkbook wb = new HSSFWorkbook(fs); // 讀取excel工作簿
                sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
            } else {
                OPCPackage pkg = OPCPackage.open(new File(filePath));
                XSSFWorkbook wb = new XSSFWorkbook(pkg);// 讀取excel工作簿
                sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
                pkg.close();
            }

            resultBean = realSheetValue(sheet);
        } catch (Exception e) {
            log.error("[讀取Excel<{}>出錯]:", filePath, e);
            resultBean.setResult(false);
            resultBean.setErrMsg("讀取Excel檔案出錯");
        }
        return resultBean;
    }

    /**
     * 
     * @param fis
     *            輸入的檔案流
     * @param sheetIndex
     *            第x個sheet
     * @return
     */
    public ExcelReadResultBean readExcel(InputStream fis, int sheetIndex) {
        ExcelReadResultBean resultBean = new ExcelReadResultBean();
        try {
            Sheet sheet = null;
            Workbook wb = null;
            try {
                POIFSFileSystem fs = new POIFSFileSystem(fis); // 利用poi讀取excel檔案流
                wb = new HSSFWorkbook(fs); // 讀取excel工作簿
                sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
            } catch (Exception e) {
                wb = new XSSFWorkbook(fis); // 讀取excel工作簿
                sheet = wb.getSheetAt(sheetIndex); // 讀取excel的sheet,0表示讀取第一個
            }

            resultBean = realSheetValue(sheet);

            wb.cloneSheet(sheetIndex);
            fis.close();
        } catch (Exception e) {
            log.error("讀取Excel檔案流時出錯:", e);
            resultBean.setResult(false);
            resultBean.setErrMsg("讀取Excel檔案流出錯");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (Exception e) {
                }
            }
        }
        return resultBean;
    }

    private ExcelReadResultBean realSheetValue(Sheet sheet) {
        ExcelReadResultBean resultBean = new ExcelReadResultBean();
        boolean result = true;
        String errMsg = "";
        List<List<String>> list = new ArrayList<List<String>>();

        int i = 0, j = 0;
        for (i = 0; i <= sheet.getLastRowNum(); i++) {
            try {
                Row row = sheet.getRow(i); // 取出sheet中的某一行資料
                if (row != null) {
                    List<String> rowList = new ArrayList<String>(row.getPhysicalNumberOfCells());
                    // 獲取該行中總共有多少列資料row.getLastCellNum()
                    for (j = 0; j < row.getLastCellNum(); j++) {
                        try {
                            Cell cell = row.getCell(j); // 獲取該行中的一個單元格物件
                            /*
                             * 當取某一行中的資料的時候,需要判斷資料型別,否則會報錯
                             * java.lang.NumberFormatException: You cannot get a
                             * string value from a numeric cell等等錯誤
                             */
                            if (cell != null) {// 判斷cell是否為空
                                if (cell.getCellType() == ExcelConfig.CT_NUMERIC) {
                                    if (HSSFDateUtil.isCellDateFormatted(cell)) {// 判斷是否日期型別
                                        Date dateValue = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                                        rowList.add(DateKit.formatDate(dateValue, DateKit.DEFAULT_DATE_TIME_FORMAT));
                                    } else {
                                        rowList.add(String.valueOf(cell.getNumericCellValue()));
                                    }
                                } else if (cell.getCellType() == ExcelConfig.CT_FORMULA) {// 讀取公式的值
                                    try {
                                        rowList.add(String.valueOf(cell.getNumericCellValue()));
                                    } catch (IllegalStateException e) {
                                        rowList.add(String.valueOf(cell.getRichStringCellValue()));
                                    }
                                } else {
                                    rowList.add(cell.getStringCellValue());
                                }
                            } else {// 如果cell為空,用空格欄位代替
                                rowList.add("");
                            }
                        } catch (Exception e) {
                            log.error("讀取{}行{}列時出錯", i + 1, j + 1);
                            result = false;
                            errMsg = errMsg + "讀取" + (i + 1) + "行" + (j + 1) + "列時出錯;";
                            rowList.add("");
                        }
                    }
                    list.add(rowList);
                }
            } catch (Exception e) {
                log.error("讀取{}行時出錯", i + 1);
                result = false;
                errMsg = errMsg + "讀取" + (i + 1) + "行時出錯";
            }
        }

        resultBean.setResult(result);
        resultBean.setErrMsg(errMsg);
        resultBean.setContentList(list);
        return resultBean;
    }
}

ExcelWriteKit.java

   package com.trendy.fw.common.excel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
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.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.trendy.fw.common.config.Constants;
import com.trendy.fw.common.util.StringKit;

public class ExcelWriteKit {
    protected static Logger log = LoggerFactory.getLogger(ExcelWriteKit.class);

    private short fontSize = 11;

    private CellStyle cellStyleCommon = null;
    private CellStyle cellStyleHeader = null;
    private CellStyle cellStyleNumeric = null;
    private CellStyle cellStyleDate = null;

    private Font fontStyleCommon = null;
    private Font fontStyleBolder = null;

    private boolean isNeedStyle = true;

    public ExcelWriteKit() {

    }

    public Workbook createWorkbook(String fileType) {
        Workbook wb = null;
        if (fileType.equals(ExcelConfig.FT_XLS)) {
            wb = new HSSFWorkbook();
        } else {
            wb = new SXSSFWorkbook(-1);
        }
        return wb;
    }

    /**
     * 建立一個內容格,字串格式
     * 
     * @param wb
     *            工作表
     * @param row
     *            行
     * @param cellIndex
     *            列
     * @param cellValue
     *            內容值
     * @return
     */
    public Cell createCell(Workbook wb, Row row, int cellIndex, String cellValue) {
        Cell cell = row.createCell(cellIndex);
        cell.setCellType(ExcelConfig.CT_STRING);
        cell.setCellValue(cellValue);
        cell.setCellStyle(getCommonCellStyle(wb));
        return cell;
    }

    private CellStyle getCommonCellStyle(Workbook wb) {
        if (isNeedStyle) {
            if (cellStyleCommon == null) {
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle = addCellBorder(cellStyle);
                cellStyle.setFont(getCellFont(wb));
                cellStyleCommon = cellStyle;
            }
        }
        return cellStyleCommon;
    }

    /**
     * 建立一個表頭內容格
     * 
     * @param wb
     *            工作表
     * @param row
     *            列
     * @param cellIndex
     *            行
     * @param cellValue
     *            內容值
     * @return
     */
    public Cell createHeaderCell(Workbook wb, Row row, int cellIndex, String cellValue) {
        Cell cell = row.createCell(cellIndex);
        cell.setCellValue(cellValue);
        cell.setCellStyle(getHeaderCellStyle(wb));
        return cell;
    }

    private CellStyle getHeaderCellStyle(Workbook wb) {
        if (isNeedStyle) {
            if (cellStyleHeader == null) {
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle = addCellBorder(cellStyle);
                cellStyle.setFont(getCellBoldFont(wb));
                cellStyleHeader = cellStyle;
            }
        }
        return cellStyleHeader;
    }

    /**
     * 建立一個數字內容格
     * 
     * @param wb
     *            內容表
     * @param row
     *            列
     * @param cellIndex
     *            行
     * @param cellValue
     *            內容值
     * @param formatStr
     *            格式
     * @return
     */
    public Cell createNumericCell(Workbook wb, Row row, int cellIndex, double cellValue, String formatStr) {
        Cell cell = row.createCell(cellIndex, ExcelConfig.CT_NUMERIC);
        cell.setCellValue(cellValue);
        cell.setCellStyle(getNumericCellStyle(wb, formatStr));
        return cell;
    }

    private CellStyle getNumericCellStyle(Workbook wb, String formatStr) {
        if (isNeedStyle) {
            if (cellStyleNumeric == null) {
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle = addCellBorder(cellStyle);
                cellStyle.setFont(getCellFont(wb));

                DataFormat format = wb.createDataFormat();
                cellStyle.setDataFormat(format.getFormat(formatStr));
                cellStyle.setAlignment(CellStyle.ALIGN_RIGHT);

                cellStyleNumeric = cellStyle;
            }
        }
        return cellStyleNumeric;
    }

    /**
     * 建立一個日期內容格
     * 
     * @param wb
     *            內容表
     * @param row
     *            列
     * @param cellIndex
     *            行
     * @param cellValue
     *            內容值
     * @param formatStr
     *            格式
     * @return
     */
    public Cell createDateCell(Workbook wb, Row row, int cellIndex, Date cellValue, String formatStr) {
        Cell cell = row.createCell(cellIndex);
        cell.setCellValue(cellValue);
        cell.setCellStyle(getDateCellStyle(wb, formatStr));
        return cell;
    }

    private CellStyle getDateCellStyle(Workbook wb, String formatStr) {
        if (isNeedStyle) {
            if (cellStyleDate == null) {
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle = addCellBorder(cellStyle);
                cellStyle.setFont(getCellFont(wb));
                cellStyleDate = cellStyle;
            }
        }
        return cellStyleDate;
    }

    /**
     * 增加內容格邊線
     * 
     * @param cellStyle
     * @return
     */
    public CellStyle addCellBorder(CellStyle cellStyle) {
        cellStyle.setBorderBottom(CellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(CellStyle.BORDER_THIN);
        cellStyle.setBorderRight(CellStyle.BORDER_THIN);
        cellStyle.setBorderTop(CellStyle.BORDER_THIN);
        return cellStyle;
    }

    /**
     * 獲取普通字型
     * 
     * @param wb
     *            工作表
     * @return
     */
    public Font getCellFont(Workbook wb) {
        if (fontStyleCommon == null) {
            Font font = wb.createFont();
            font.setFontHeightInPoints(getFontSize());
            fontStyleCommon = font;
        }
        return fontStyleCommon;
    }

    /**
     * 獲取加粗字型
     * 
     * @param wb
     *            工作表
     * @return
     */
    public Font getCellBoldFont(Workbook wb) {
        if (fontStyleBolder == null) {
            Font font = wb.createFont();
            font.setFontHeightInPoints(getFontSize());
            font.setBoldweight(Font.BOLDWEIGHT_BOLD);
            fontStyleBolder = font;
        }
        return fontStyleBolder;
    }

    /**
     * 寫Excel工作簿
     * 
     * @param bean
     *            WriteExcelBean
     * @return Workbook工作簿物件
     */
    public Workbook writeExcel(ExcelWriteBean bean) {
        Workbook wb = createWorkbook(bean.getFileType());
        String sheetName = bean.getSheetName();
        if (!StringKit.isValid(sheetName)) {
            sheetName = "sheet1";
        }
        Sheet sheet = wb.createSheet(sheetName);

        // 處理表頭內容
        if (bean.getHeaderList().size() > 0) {
            Row row = sheet.createRow(0);
            for (int i = 0; i < bean.getHeaderList().size(); i++) {
                String headerValue = bean.getHeaderList().get(i);
                createHeaderCell(wb, row, i, headerValue);
            }
        }

        // 處理表中內容
        if (bean.getContentList().size() > 0) {
            int rowCount = 1;// 行計數器
            // 沒有表頭的情況
            if (bean.getHeaderList().size() == 0) {
                rowCount = 0;
            }

            for (List<Object> contentList : bean.getContentList()) {
                Row row = sheet.createRow(rowCount);
                for (int i = 0; i < contentList.size(); i++) {
                    Object cellValue = contentList.get(i);
                    if (getCellType(i, bean.getCellTypeMap()) == ExcelConfig.CT_NUMERIC) {
                        if (cellValue == null) {// 如果值為空,預設填0
                            cellValue = new Integer(0);
                        }
                        createNumericCell(wb, row, i, Double.valueOf(cellValue.toString()),
                                getCellFormat(i, bean.getCellFormatMap()));
                    } else {
                        if (cellValue == null) {// 如果值為空,預設空字串
                            cellValue = new String("");
                        }
                        createCell(wb, row, i, cellValue.toString());
                    }
                }
                rowCount++;

                if (rowCount % 100 == 0) {
                    try {
                        ((SXSSFSheet) sheet).flushRows(100);
                    } catch (Exception e) {
                        log.error("", e);
                    }
                }
            }

        }
        return wb;
    }

    /**
     * 寫Excel工作簿多個sheet
     * 
     * @param bean
     *            WriteExcelBean
     * @return Workbook工作簿物件
     */
    public Workbook writeExcel(List<ExcelWriteBean> excelWriteList) {
        if(excelWriteList == null || excelWriteList.size()==0){
            return null;
        }
        Workbook wb = createWorkbook(excelWriteList.get(0).getFileType());

        int sheetNumber = 0;
        for(ExcelWriteBean bean : excelWriteList){
            sheetNumber++;
            String sheetName = bean.getSheetName();
            if (!StringKit.isValid(sheetName)) {
                sheetName = "sheet"+sheetNumber;
            }
            Sheet sheet = wb.createSheet(sheetName);

            // 處理表頭內容
            if (bean.getHeaderList().size() > 0) {
                Row row = sheet.createRow(0);
                for (int i = 0; i < bean.getHeaderList().size(); i++) {
                    String headerValue = bean.getHeaderList().get(i);
                    createHeaderCell(wb, row, i, headerValue);
                }
            }

            // 處理表中內容
            if (bean.getContentList().size() > 0) {
                int rowCount = 1;// 行計數器
                // 沒有表頭的情況
                if (bean.getHeaderList().size() == 0) {
                    rowCount = 0;
                }

                for (List<Object> contentList : bean.getContentList()) {
                    Row row = sheet.createRow(rowCount);
                    for (int i = 0; i < contentList.size(); i++) {
                        Object cellValue = contentList.get(i);
                        if (getCellType(i, bean.getCellTypeMap()) == ExcelConfig.CT_NUMERIC) {
                            if (cellValue == null) {// 如果值為空,預設填0
                                cellValue = new Integer(0);
                            }
                            createNumericCell(wb, row, i, Double.valueOf(cellValue.toString()),
                                    getCellFormat(i, bean.getCellFormatMap()));
                        } else {
                            if (cellValue == null) {// 如果值為空,預設空字串
                                cellValue = new String("");
                            }
                            createCell(wb, row, i, cellValue.toString());
                        }
                    }
                    rowCount++;

                    if (rowCount % 100 == 0) {
                        try {
                            ((SXSSFSheet) sheet).flushRows(100);
                        } catch (Exception e) {
                            log.error("", e);
                        }
                    }
                }

            }
        }
        return wb;
    }

    /**
     * 輸出Excel檔案
     * 
     * @param bean
     *            WriteExcelBean
     * @param filePath
     *            檔案全路徑
     */
    public void outputExcel(ExcelWriteBean bean, String filePath) {
        FileOutputStream fos = null;
        try {
            Workbook wb = writeExcel(bean);
            String fileName = bean.getFileName() + "." + bean.getFileType();
            fos = new FileOutputStream(filePath + Constants.FILE_SEPARATOR + fileName);
            wb.write(fos);
            fos.close();
        } catch (IOException e) {
            log.error("輸出檔案[{}]出錯:", filePath, e);
        } catch (Exception e) {
            log.error("輸出檔案[{}]出錯:", filePath, e);
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (Exception e) {
                log.error("輸出檔案[{}]出錯:", filePath, e);
            }
        }
    }

    /**
     * 獲取cell的型別
     * 
     * @param cellIndex
     * @param cellTypeMap
     * @return
     */
    private int getCellType(int cellIndex, HashMap<Integer, Integer> cellTypeMap) {
        int cellType = ExcelConfig.CT_STRING;
        try {
            if (!cellTypeMap.isEmpty()) {
                cellType = cellTypeMap.get(cellIndex);
            }
        } catch (Exception e) {
            cellType = ExcelConfig.CT_STRING;
        }
        return cellType;
    }

    /**
     * 獲取cell的格式
     * 
     * @param cellIndex
     * @param cellFormatMap
     * @return
     */
    private String getCellFormat(int cellIndex, HashMap<Integer, String> cellFormatMap) {
        String cellFormat = "";
        try {
            if (!cellFormatMap.isEmpty()) {
                cellFormat = cellFormatMap.get(cellIndex);
            }
        } catch (Exception e) {
            cellFormat = "";
        }
        return cellFormat;
    }

    public short getFontSize() {
        return fontSize;
    }

    public void setFontSize(short fontSize) {
        this.fontSize = fontSize;
    }

    public CellStyle getCellStyleCommon() {
        return cellStyleCommon;
    }

    public void setCellStyleCommon(CellStyle cellStyleCommon) {
        this.cellStyleCommon = cellStyleCommon;
    }

    public CellStyle getCellStyleHeader() {
        return cellStyleHeader;
    }

    public void setCellStyleHeader(CellStyle cellStyleHeader) {
        this.cellStyleHeader = cellStyleHeader;
    }

    public CellStyle getCellStyleNumeric() {
        return cellStyleNumeric;
    }

    public void setCellStyleNumeric(CellStyle cellStyleNumeric) {
        this.cellStyleNumeric = cellStyleNumeric;
    }

    public CellStyle getCellStyleDate() {
        return cellStyleDate;
    }

    public void setCellStyleDate(CellStyle cellStyleDate) {
        this.cellStyleDate = cellStyleDate;
    }

    public Font getFontStyleCommon() {
        return fontStyleCommon;
    }

    public void setFontStyleCommon(Font fontStyleCommon) {
        this.fontStyleCommon = fontStyleCommon;
    }

    public Font getFontStyleBolder() {
        return fontStyleBolder;
    }

    public void setFontStyleBolder(Font fontStyleBolder) {
        this.fontStyleBolder = fontStyleBolder;
    }

    public boolean getIsNeedStyle() {
        return isNeedStyle;
    }

    public void setIsNeedStyle(boolean isNeedStyle) {
        this.isNeedStyle = isNeedStyle;
    }
}

WebExcelWriteKit.java

package com.trendy.fw.common.excel;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;

import com.trendy.fw.common.web.HttpResponseKit;

public class WebExcelWriteKit extends ExcelWriteKit {

    /**
     * 輸出成文件
     * 
     * @param wb
     *            工作表
     * @param fileName
     *            檔名
     * @param response
     */
    public void output(Workbook wb, String fileName, HttpServletRequest request, HttpServletResponse response) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            wb.write(os);

            byte[] content = os.toByteArray();
            InputStream is = new ByteArrayInputStream(content);

            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            HttpResponseKit.setAttachmentFile(request, response, fileName);

            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[2048];
            int bytesRead;

            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (IOException e) {
            log.error("輸出Excel出錯:", e);
        } catch (Exception e) {
            log.error("輸出Excel出錯:", e);
        } finally {
            try {
                if (bis != null)
                    bis.close();
                if (bos != null)
                    bos.close();
                if (os != null)
                    os.close();
            } catch (Exception e) {
                log.error("輸出Excel出錯:{}", e);
            }
        }
    }

    /**
     * 從頁面上輸出Excel
     * 
     * @param bean
     *            WriteExcelBean
     * @param response
     */
    public void outputExcel(ExcelWriteBean bean, HttpServletRequest request, HttpServletResponse response) {
        Workbook wb = writeExcel(bean);
        String fileName = bean.getFileName() + "." + bean.getFileType();
        output(wb, fileName, request, response);
    }

    /**
     * 從頁面上輸出Excel多個sheet
     * 
     * @param bean
     *            WriteExcelBean
     * @param response
     */
    public void outputExcel(List<ExcelWriteBean> excelWriteList, HttpServletRequest request, HttpServletResponse response) {
        Workbook wb = writeExcel(excelWriteList);
        String fileName = excelWriteList.get(0).getFileName() + "." + excelWriteList.get(0).getFileType();
        output(wb, fileName, request, response);
    }
}

使用說明

將以上程式碼放到同一個excel包中,在對Excel進行讀寫的操作的時候,分別呼叫ExcelReadKit和ExcelWriteKit兩個類中的方法,可以很方便地將Excel中的內容轉換成ExcelReadResultBean物件,封裝ExcelWriteBean物件將資料寫入Excel檔案中。

備註:以上程式碼使用需要依賴 apache poi jar包,記得先引入到專案當中

這裡寫圖片描述

相關推薦

Excel工具

緣起 在J2SE和J2EE應用程式開發中,經常會遇到上傳Excel,匯出Excel的功能開發,對Excel的操作無非就是讀取Excel檔案內容轉成javabean,或者是將javabean物件寫入Excel檔案中。為了方便對Excel進行讀寫操作,可以將這塊程

properties文件工具PropertiesUtil.java

prop ace sys pan str pri finally res println import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException

Spring-Boot ? ShapeFile文件工具+接口調用

void while har ble mage cto next() bound 添加 一、項目目錄結構樹 二、項目啟動 三、往指定的shp文件裏寫內容 (1) json數據【Post】 {

android 檔案工具

public static String readFile(File file) throws IOException{FileInputStream inputStream = new FileInputStream(file);int len=inputStream.available();byte []

Java的Excel檔案操作工具,包括、合併等功能

一、直接上程式碼: package com.cycares.crm.utils.ExcelUtil; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputS

Python excel

pty xxx oam 切換 ont ext ces cell 創建 1 # coding=utf-8 2 3 print "----------------分割線 xlrd--------------------" 4 import xlrd 5

python操作Excel(使用xlrd和xlrt)

bold 新建 例子 ref boolean 取整 設置 xfs .py 包下載地址:https://pypi.python.org/pypi/xlrd 導入 import xlrd 打開excel data = xlrd.open_workbook(‘demo.xl

Java 通過Xml導出Excel文件,Java Excel 導出工具,Java導出Excel工具

public emp cep sdf value 提交 bsp datetime rtm Java 通過Xml導出Excel文件,Java Excel 導出工具類,Java導出Excel工具類 ============================== ?Copyri

python 操作excel

exc python ng- gpo ati ref github -c div 【轉】http://wenqiang-china.github.io/2016/05/13/python-opetating-excel/python 操作excel讀寫

關於InnoDB的型以及加鎖方式

索引 不完全 b2c text 按順序 net c中 加鎖 並不是 (本文為了方便,英文關鍵詞都都采用小寫方式,相關知識點會簡單介紹,爭取做到可以獨立閱讀) 文章開始我會先介紹本文需要的知識點如下: innodb的聚簇索引(聚集索引)和非聚簇索引(二級索引、非聚集索引

Excel 操作

文件的 python https TE xlwt open rom shee int 讀 import xlrd from xlrd.book import Book from xlrd.sheet import Sheet from xlrd.sheet import C

python之excel操作

install excel讀寫 下載 int sheet 指定路徑 file 列數 裝包 一、xlrd和xlwt安裝 1、下載xlwt安裝包https://pypi.org/project/xlwt/#files 2、解壓後進入文件目錄 3、執行python setup.p

Asp.net core 學習筆記 (Excel )

environ org host asd combine openxml end create rop EPPlus 已經支持 .net core 了 https://www.nuget.org/packages/EPPlus https://github.com/JanK

HSSFWorkbook操作excel

HSSFWorkbook操作excel讀寫 //exlel讀操作 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = m

Tuxera ntfs破解版|Tuxera ntfs for mac(mac工具)v2018 中

Tuxera ntfs 破解版是Mac os平臺上的一種簡單、實用的解壓縮軟體,可以快速,簡單,高效解壓檔案,其易於使用的介面,個性化設定讓你輕鬆辦公,可以非常方便使用Rar Sharp for mac壓縮解壓工具,並且該軟體支援常用的壓縮格式,如rar、zip、gzip、tar等格式,支援壓縮包內檔案預

excel匯出FileUtil工具

package com.ziyun.pop.common.utils; import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.a

Excel導入工具兼容xls和xlsx

imp rownum group else new rac 不同的 multi info package com.bj58.finance.platform.operation.provider.util; import org.apache.log4j.Logger;

POI中HSSFWorkbook匯出excel封裝的工具

     在實際中匯出excel非常常見,於是自己封裝了一個匯出資料到excel的工具類,先附上程式碼,最後會寫出例項和解釋。   程式碼中依賴了slf4j日誌包,commons-io包的IOUtils關閉流,commons-lang和commons-collections包等包。 package

Paragon NTFS 15 for Mac(mac ntfs工具)無需paragon ntf

ntfs for mac 破解版是mac上首個支援Mac上讀寫NTFS外接儲存裝置解決方案 ,解決mac不能讀寫識別問題,NTFS讓您更加簡單直觀的在Mac機上隨意對NTFS檔案修改、刪除等操作。 NTFS For Mac工具可以高速傳輸外界NTFS硬碟檔案,並且可以保證資料檔案傳輸的完整性及安全性。使用

最好用的mac ntfs工具Paragon NTFS 15 Mac破解版 v15.5.10永久使用教程

ntfs for mac 破解版是mac上首個支援Mac上讀寫NTFS外接儲存裝置解決方案 ,解決mac不能讀寫識別問題,NTFS讓您更加簡單直觀的在Mac機上隨意對NTFS檔案修改、刪除等操作。 NTFS For Mac工具可以高速傳輸外界NTFS硬碟檔案,並且可以保證資料檔案傳輸的完整性及安全性