java 導入導出 excel

java 導入導出 excel
一、POI

private ActionForward importExcel(ActionMapping mapping, LotStepEndTimeForm theform, HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {
        try {
            FormFile upFile = theform.getFormFile();
            String fileName = upFile.getFileName();
            if (StringUtils.isEmpty(fileName)) {
                throw new ValidateFailureException("Please select the Excel file to import!");
            }
            if (StringUtils.endsWithIgnoreCase(fileName, ".XLS") != true || upFile.getFileSize() < 1) {
                throw new ValidateFailureException("Only import .xls files!");
            }
            // 導入Excel
            ExcelImportHelper excelHelper = new ExcelImportHelper(fileName, 0, upFile);
            List<String[]> implist = excelHelper.getStringArrayList();
            excelHelper.closeExcel();
            int startRow = 1;
          
            List<Map<String, String>> impLotStepEndTimeList = new ArrayList<Map<String, String>>();
            for (int i = startRow; i < implist.size(); i++) {
                String[] rowData = implist.get(i);
                Map<String, String> endTimeInfo = new HashMap<>();
                boolean isNotEmptyRow = false;// 爲true時,表示此行至少有一列數據,爲false時,表示從此行數據全是空的
                for (int k = 0; k < colIds.length && k < rowData.length; k++) {
                    endTimeInfo.put(colIds[k], rowData[k]);
                    isNotEmptyRow = isNotEmptyRow || StringUtils.isNotEmptyTrim(rowData[k]);
                }
                if (isNotEmptyRow) {
                    impLotStepEndTimeList.add(validateImportData(endTimeInfo, theform, request));
                }
            }
            // 判斷是否重複,重複數據validateFlag置爲"false"
            Set<String> uniqueSet = new HashSet<String>();
            for (Map<String, String> impEndTime : impLotStepEndTimeList) {
                String uniqueKey = MapUtils.getString(impEndTime, "lotId") + MapUtils.getString(impEndTime, "stepId");
                if (uniqueSet.contains(uniqueKey)) {
                    if (MapUtils.getBooleanValue(impEndTime, "validateFlag")) {
                        impEndTime.put("validateFlag", new Boolean(false).toString());
                        impEndTime.put("validateMsg", "The data is repeated!");
                    }
                } else {
                    uniqueSet.add(uniqueKey);
                }
            }
            request.setAttribute("impLotStepEndTimesJsonStr", JSONUtils.toJSONString(impLotStepEndTimeList).replaceAll("\"", "\'"));
            request.setAttribute("impLotStepEndTimeList", impLotStepEndTimeList);
        } catch (Exception e) {
            log.error(e);
            request.setAttribute(ERROR_MSG, e.getMessage().replaceAll("\"", "\'"));
        }
        return mapping.findForward("import");
    }

 private Map validateImportData(Map<String, String> endTimeInfo, LotStepEndTimeForm theform,
                                    HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Long facilityRrn = (Long) session.getAttribute(SessionNames.FACILITY_KEY);
        StringBuffer validateMsg = new StringBuffer();
        try {
            String lotId = StringUtils.trimToUpperCase(MapUtils.getString(endTimeInfo, "lotId"));
            String stepId = StringUtils.trimToUpperCase(MapUtils.getString(endTimeInfo, "stepId"));
            String endTime = StringUtils.trim(MapUtils.getString(endTimeInfo, "endTime"));
            String comments = StringUtils.trim(MapUtils.getString(endTimeInfo, "comments"));
            if (StringUtils.isEmpty(lotId)) {
                throw new ValidateFailureException("Lot Id can not be empty ");
            }
            if (getLotRrn(facilityRrn, lotId) <= 0) {
                throw new ValidateFailureException("Lot Id " + lotId + " does not exist ");
            }
            if (StringUtils.isEmpty(stepId)) {
                throw new ValidateFailureException("Step Id can not be empty ");
            }
            if (getInstanceRrn(stepId, getNamedSpace(ObjectList.OPERATION_KEY, facilityRrn),
                                              ObjectList.OPERATION_KEY) <= 0) {
                throw new ValidateFailureException("Step Id " + stepId + " does not exist ");
            }
            if (StringUtils.isEmpty(endTime)) {
                throw new ValidateFailureException("EndTime can not be empty ");
            }
            if (!NumberUtils.isNumber(endTime)) {
                throw new ValidateFailureException("EndTime must be Number ");
            }
            endTime = new BigDecimal(endTime).setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();// 保留兩位有效數字

            endTimeInfo.put("lotId", lotId);
            endTimeInfo.put("stepId", stepId);
            endTimeInfo.put("endTime", endTime);
            endTimeInfo.put("comments", comments);
        } catch (Exception e) {
            validateMsg.append(e.getMessage());
        }
        endTimeInfo.put("validateMsg", validateMsg.toString());
        endTimeInfo.put("validateFlag", new Boolean(validateMsg.length() == 0).toString());
        return endTimeInfo;
    }
    

ExcelImportHelper.java

package com.mycim.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
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.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts.upload.FormFile;

/**
 * Excel導入工具類
 * 
 */
public class ExcelImportHelper {

    private static final String XLS_TYPE        = "XLS";                             // Excel 2007 之前,後綴爲.xls
    private static final String XLSX_TYPE       = "XLSX";                            // Excel 2007 之後,後綴爲.xlsx

    private String              excelType       = null;                              // XLS_TYPE or XLSX_TYPE Excel類型

    private Workbook            workbook        = null;
    private Sheet               sheet           = null;
    private Row                 row             = null;
    private Cell                cell            = null;

    private int                 totalRows       = 0;                                 // 總行數
    private short               totalCells      = 0;                                 // 總列數

    private Map<String, String> stringMapData   = null;                              // 存儲字符串Map
    private List<String[]>      stringArrayList = null;                              // 存儲字符串數組List
    private SimpleDateFormat    fmt             = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式yyyy-mm-dd

    /**
     * 讀取Excel
     * 
     * @param filePath 文件路徑
     * @param sheetIndex 表索引,第一個表爲0
     * @throws IOException
     */
    public ExcelImportHelper(String filePath, int sheetIndex, FormFile upFile) throws IOException{
        setExcelType(filePath);

        if (XLSX_TYPE.equals(excelType)) {
            initXLSX(upFile, sheetIndex);
        } else if (XLS_TYPE.equals(excelType)) {
            initXLS(upFile, sheetIndex);
        } else {
            throw new IOException("不支持的文件格式!");
        }
    }

    private void initXLS(FormFile upFile, int sheetIndex) throws IOException {
        this.workbook = getHssfWorkbook(upFile.getInputStream());
        this.sheet = getHssfSheet(sheetIndex);

        setTotalRows(sheet);
    }

    private void initXLSX(FormFile upFile, int sheetIndex) throws IOException {
        // 獲取Excel引用
        this.workbook = getXssfWorkbook(upFile.getInputStream());
        // 獲取Excel引用的第幾張表
        this.sheet = getXssfSheet(sheetIndex);
        // 獲取總行數
        setTotalRows(sheet);
    }

    // ---------- Private Methods
    /**
     * 設置當前讀取Excel文件類型
     * 
     * @param filePath 文件路徑
     */
    private void setExcelType(String filePath) {
        this.excelType = "X".equals(StringUtils.substringAfter(filePath.toUpperCase(), ".XLS")) ? XLSX_TYPE : XLS_TYPE;
    }

    /**
     * 獲取當前讀取Excel文件類型
     * 
     * @return XLS_TYPE or XLSX_TYPE
     */
    public String getExcelType() {
        return excelType;
    }

    /**
     * 獲取文件字節流
     * 
     * @param filePath 文件路徑
     * @return FileInputStream
     * @throws FileNotFoundException
     */
    private FileInputStream getFile(String filePath) throws FileNotFoundException {
        return new FileInputStream(new File(filePath));
    }

    // ----- For XLS
    /**
     * XLS類型的Excel引用
     * 
     * @param file 文件字節流
     * @return HSSFWorkbook
     * @throws IOException
     */
    private HSSFWorkbook getHssfWorkbook(InputStream file) throws IOException {
        return new HSSFWorkbook(file);
    }

    /**
     * XLS類型的Excel表單
     * 
     * @param sheetIndex 表單索引,第一個表爲0
     * @return HSSFSheet
     */
    private HSSFSheet getHssfSheet(int sheetIndex) {
        return (HSSFSheet) this.workbook.getSheetAt(sheetIndex);
    }

    /**
     * XLS類型的Excel表單中的行
     * 
     * @param rowNum 行號
     * @return HSSFRow
     */
    private HSSFRow getHSSFRow(int rowNum) {
        return (HSSFRow) sheet.getRow(rowNum);
    }

    /**
     * XLS類型的Excel表單中的列
     * 
     * @param rowNum 行號
     * @param cellNum 列號
     * @return HSSFCell
     */
    private HSSFCell getHSSFCell(int rowNum, int cellNum) {
        return getHSSFRow(rowNum).getCell(cellNum);
    }

    // ----- For XLSX
    /**
     * XLSX類型的Excel引用
     * 
     * @param file 文件字節流
     * @return XSSFWorkbook
     * @throws IOException
     */
    private XSSFWorkbook getXssfWorkbook(InputStream file) throws IOException {
        return new XSSFWorkbook(file);
    }

    /**
     * XLSX類型的Excel表單
     * 
     * @param sheetIndex 表單索引
     * @return XSSFSheet
     */
    private XSSFSheet getXssfSheet(int sheetIndex) {
        return (XSSFSheet) this.workbook.getSheetAt(sheetIndex);
    }

    /**
     * XLSX類型的Excel表單中的行
     * 
     * @param rowNum 行號
     * @return XSSFRow
     */
    private XSSFRow getXSSFRow(int rowNum) {
        return (XSSFRow) sheet.getRow(rowNum);
    }

    /**
     * XLSX類型的Excel表單中的列
     * 
     * @param rowNum 行號
     * @param cellNum 列號
     * @return XSSFCell
     */
    private XSSFCell getXSSFCell(int rowNum, int cellNum) {
        return getXSSFRow(rowNum).getCell(cellNum);
    }

    /**
     * 設置總行數
     * 
     * @param sheet 表單引用 HSSFSheet or XSSFSheet
     */
    private void setTotalRows(Sheet sheet) {
        this.totalRows = sheet.getLastRowNum() + 1;
    }

    /**
     * 設置某行的總列數
     * 
     * @param row 行引用 HSSFRow or XSSFRow
     */
    private void setTotalCells(Row row) {
        this.totalCells = row.getLastCellNum();
    }

    // ---------- Public Methods
    /**
     * 獲取Excel引用
     * 
     * @return HSSFWorkbook or XSSFWorkbook
     */
    public Workbook getWorkbook() {
        return workbook;
    }

    /**
     * 獲取Excel表單
     * 
     * @return HSSFSheet or XSSFSheet
     */
    public Sheet getSheet() {
        return sheet;
    }

    /**
     * 獲取Excel的行
     * 
     * @param i 行號
     * @return HSSFRow or XSSFRow
     */
    public Row getRow(int i) {
        return XLSX_TYPE.equals(excelType) ? getXSSFRow(i) : getHSSFRow(i);
    }

    /**
     * 獲取Excel的列
     * 
     * @param i 行號
     * @param j 列號
     * @return HSSFCell or XSSFCell
     */
    public Cell getCell(int i, int j) {
        return XLSX_TYPE.equals(excelType) ? getXSSFCell(i, j) : getHSSFCell(i, j);
    }

    /**
     * 檢查第i行是否爲空行
     * 
     * @param i 行號
     * @return boolean ? true : false
     */
    public boolean isRowNotNull(int i) {
        row = getRow(i);

        if (row != null) {
            setTotalCells(row);
            return true;
        }

        return false;
    }

    /**
     * 獲取第i行第j列的單元格的值 除日期類型,其他類型全處理爲文本,與表格內容一致
     * 
     * @param i 行號
     * @param j 列號
     * @return String 單元格中的數據
     */
    public String getCellStringValue(int i, int j) {

        String val = null;

        cell = getCell(i, j);

        if (cell != null) {
            if (cell.getCellTypeEnum().equals(CellType.NUMERIC) && DateUtil.isCellDateFormatted(cell)) {
                val = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
            } else {
                cell.setCellType(CellType.STRING);
                val = cell.toString().trim();
            }
        }
        return val == null ? "" : val.trim().toUpperCase();

    }

    /**
     * Map類型的數據集合<br>
     * 
     * @return Map<br>
     * key: R + i + C + j <br>
     * R代表行,i行號,C代表列,j列號<br>
     * e.g: map.get("R11C12")<br>
     * 第11行第12列的單元格中的值
     */
    public Map<String, String> getStringMapData() {
        stringMapData = new HashMap<>();
        for (int i = 0; i < totalRows; i++) {
            if (isRowNotNull(i)) {
                for (int j = 0; j < totalCells; j++) {
                    stringMapData.put("R" + i + "C" + j, getCellStringValue(i, j));
                }
            }
        }
        return stringMapData;
    }

    /**
     * String類型數組的List集合<br>
     * 
     * @return List<br>
     * Row,String[]: List.get(i) <br>
     * Cell,String: List.get(i)[j]<br>
     * e.g: list.get(11)[12]<br>
     * 第11行第12列的單元格中的值
     */
    public List<String[]> getStringArrayList() {
        stringArrayList = new ArrayList<>();
        for (int i = 0; i < totalRows; i++) {
            if (isRowNotNull(i)) {
                String[] strings = new String[totalCells];
                for (int j = 0; j < totalCells; j++) {
                    strings[j] = getCellStringValue(i, j);
                }
                stringArrayList.add(strings);
            }
        }
        return stringArrayList;
    }

    /**
     * 關閉流
     * 
     * @throws IOException
     */
    public void closeExcel() throws IOException {
        if (workbook != null) {
            workbook.close();
        }
    }

}

二、jxl


    private ActionForward exportExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                      HttpServletResponse response) {
        String exportData = request.getParameter("exportData");
        try {
            ByteArrayOutputStream os = (ByteArrayOutputStream) createWorkBook(exportData, request);
            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename=foupsInfo.xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            out.write(os.toByteArray());
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e);
        }
        return null;
    }

   private OutputStream createWorkBook(String exportData, HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession(false);
        String language = (String) session.getAttribute(SessionNames.LANGUAGE_KEY);
        JSONObject exportJsonObj = JSONObject.fromObject(exportData);
        JSONArray headers = exportJsonObj.getJSONArray("headers");
        JSONArray rows = exportJsonObj.getJSONArray("rows");
        OutputStream os = new ByteArrayOutputStream();

        jxl.write.WritableWorkbook wwb = Workbook.createWorkbook(os);
        String title = "Foups Info";
        jxl.write.WritableSheet ws = wwb.createSheet(title, 0);

        try {
            jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TAHOMA, 20, WritableFont.BOLD, true);
            jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
            wcfF.setAlignment(Alignment.CENTRE);

            ws.mergeCells(0, 0, 10, 0);
            jxl.write.Label labelTitle = new jxl.write.Label(0, 0, title, wcfF);
            ws.addCell(labelTitle);

            jxl.write.Label labelColes = null;
            jxl.write.WritableFont wfs = new jxl.write.WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false);
            jxl.write.WritableCellFormat wfColes = new jxl.write.WritableCellFormat(wfs);
            wfColes.setAlignment(Alignment.CENTRE);

            // labelColes = new jxl.write.Label(2, 3, "product Id:" + baseInfo.getString("productId"), wfColes);
            // ws.addCell(labelColes);

            jxl.write.Label labelCols = null;
            jxl.write.WritableCellFormat wfCols = new jxl.write.WritableCellFormat();
            wfCols.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
            wfCols.setVerticalAlignment(VerticalAlignment.CENTRE);

            int colCount = 0;
            // int colIndex = 0;
            for (Iterator iterator = headers.iterator(); iterator.hasNext();) {
                int rowCount = 5;
                JSONObject header = (JSONObject) iterator.next();
                if (!header.getBoolean("hidden")) {
                    // if (colIndex == 0) {// 第一列沒有值,不顯示
                    // colIndex++;
                    // continue;
                    // }
                    if (header.getInt("width") != 0) {
                        ws.setColumnView(colCount, header.getInt("width") / 6);// px-->cm
                    }
                    labelCols = new jxl.write.Label(colCount, rowCount, header.getString("colName"), wfCols);
                    ws.addCell(labelCols);
                    String preValue = null;
                    int preRowCount = rowCount;
                    for (Iterator iterator2 = rows.iterator(); iterator2.hasNext();) {
                        rowCount++;
                        JSONObject colValue = (JSONObject) iterator2.next();
                        String tempValue = null;
                        String headerId = header.getString("colId");
                        if (colValue.containsKey(headerId)) {
                            tempValue = colValue.getString(headerId);
                        }
                        String value = ((tempValue == null) || "null".equals(tempValue)) || "false".equals(tempValue) ? "" : tempValue;
                        if ("_routeId".equals(header.getString("colId"))) {// merge column name(hard code)
                            if (rowCount == 6) {
                                preRowCount = rowCount;
                                preValue = value;
                            }
                            if (!value.equals(preValue) && preValue != null) {
                                ws.mergeCells(colCount, preRowCount, colCount, rowCount - 1);
                                labelCols = new jxl.write.Label(colCount, preRowCount, preValue, wfCols);
                                ws.addCell(labelCols);
                                preRowCount = rowCount;
                                preValue = value;
                            }
                            if ((rowCount - 5) == rows.size()) {
                                ws.mergeCells(colCount, preRowCount, colCount, rowCount);
                                labelCols = new jxl.write.Label(colCount, preRowCount, value, wfCols);
                                ws.addCell(labelCols);
                            }
                        } else {
                            if (StringUtils.equals(headerId, "pollutionLevel")) {
                                if (StringUtils.isNotEmpty(value)) {
                                    value = lotService.getPollutionLevel4Show(value);
                                }
                            }
                            labelCols = new jxl.write.Label(colCount, rowCount, value, wfCols);
                            ws.addCell(labelCols);
                        }
                    }
                    colCount++;
                }
            }

            wwb.write();
        } catch (Exception d) {
            log.error(d);
        } finally {
            try {
                if (wwb != null) {
                    wwb.close();
                }
            } catch (Exception e) {
                log.error(e);
            }
        }
        return os;
    }

三、頁面

  <fieldset id="fld3"><legend><mycim2:contentDisplay id="LBS_IMPORT_ENDTIME_INFO" default="Import End Time Info" /></legend>	
		  <table width="100%">	
		  <thead> 		  		
          <tr align="center" class="myinnertable">
            <td nowrap width="5%">NO</td>
            <td nowrap width="5%"><mycim2:contentDisplay id="LBL_LOT_ID" default="Lot ID" /></td>
            <%-- <td nowrap width="5%"><mycim2:contentDisplay id="LBL_ROUTE_SEQ" default="Route Seq." /></td>
            <td nowrap width="5%"><mycim2:contentDisplay id="LBL_ROUTE_ID" default="Route ID"/></td>
            <td nowrap width="5%"><mycim2:contentDisplay id="LBL_OPERATION_SEQ" default="Step Seq." /></td> --%>
            <td nowrap width="5%"><mycim2:contentDisplay id="LBL_OPERATION_ID" default="Step ID"/></td>
            <td nowrap width="5%"><mycim2:contentDisplay id="LBL_END_TIME" default="End Time"/></td>
            <td nowrap width="10%"><mycim2:contentDisplay id="LBL_COMMENTS" default="Comments"/></td>
            <td nowrap width="10%"><mycim2:contentDisplay id="LBL_INSTRUCTION_INFO" default="Instruction Info"/></td>            
          </tr>   
          <thead> 		     
          
          <tbody>
          <logic:present name="impLotStepEndTimeList">
			<logic:iterate id="item" name="impLotStepEndTimeList"  indexId="seq">		         
          	<tr align="center" class="myinnertable2 implData">		
	            <td nowrap class="myfield">
	                <mycim2:write name="item" property="NO" filter="true"/>
	                <input type='hidden' name='validateFlag' value='<mycim2:write name="item" property="validateFlag"/>'/>
	            </td> 	            
	            <td nowrap class="myfield"><mycim2:write name="item" property="lotId" filter="true"/></td> 	            
	           <%--  <td nowrap class="myfield"><mycim2:write name="item" property="routeSeq" filter="true"/></td> 	            
	            <td nowrap class="myfield"><mycim2:write name="item" property="routeId" filter="true"/></td>  
	            <td nowrap class="myfield"><mycim2:write name="item" property="stepSeq" filter="true"/></td> --%> 	            	          			
	            <td nowrap class="myfield"><mycim2:write name="item" property="stepId" filter="true"/></td>
	            <td nowrap class="myfield"><mycim2:write name="item" property="endTime" filter="true"/></td>	
	            <td width="10%" class="myfield"><mycim2:write name="item" property="comments" filter="true"/></td>	
	            <%-- <td width="15%" class="myfield"><mycim2:write name="item" property="createUser" filter="true"/></td> --%>
	            <td width="10%" class="myfield"><mycim2:write name="item" property="validateMsg" filter="true"/></td>
	            <%--  <td class="myfield" ><a href="javascript:doDelete('delete=Y&lotRrn=<mycim2:write name="item" property="lotRrn" filter="true"/>&endTimeRrn=<mycim2:write name="item" property="endTimeRrn" filter="true"/>')">
	            <img  height=16 src="<%=request.getContextPath()%>/img/delete.gif" width=16 border=0></a></td> --%>
          	</tr>	
			</logic:iterate>
			</logic:present>
			</tbody>
			</table>
			</fieldset>
            <br>
		    <table width="100%">
		    <tr>
		        <td>
			        <div align="center">
			        <input type="button" name="saveimp" value="<mycim2:contentDisplay id="LBS_SAVE" default="Save"/>" onClick="saveImp()">
			        <input type="button" name="reset" value="<mycim2:contentDisplay id="LBS_RESET" default="Reset"/>" onClick="clearImplData();">
			        <input type="button" name="back" value="<mycim2:contentDisplay id="LBS_BACK" default="Back"/>" onClick="goToURL('self', '<%=request.getContextPath()%>/lotstependtime.do?edit=1&nav=true')">
			        </div>
			    </td>
		    </tr>
	        </table>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章