1. 程式人生 > >struts:poi讀取excel檔案(相容2003、2007)

struts:poi讀取excel檔案(相容2003、2007)

1、jsp程式碼:

	<div style="margin-bottom:10px;">
 		<input type="file" name="filedata" id="file" multiple/>
		<input type="button" value="上傳" id="fileBtn"/>
	</div>
	<div style="margin-bottom:10px;">
		款項稽核頁-資料匯出為excel-資料格式.xlsx<a id="downBtn1" href="">下載1</a><input type="button" value="下載2" id="downBtn2"/>
	</div>


	$("#fileBtn").click(function() {
 			//獲取上傳圖片的檔名
			var confirmfileImageName =$("#file").val();
			//員工是否選擇了圖片
			if(confirmfileImageName!=""){
			  $.ajaxFileUpload({
	             url:'ExcelReadAction',
	             secureuri:false,
	             fileElementId:'file',//file標籤的id
	             dataType: 'json',//返回資料的型別
	             data:{},//一同上傳的資料
	             success: function (ret) {alert("上傳成功");
 		         }
		     });
			} else {
			} 
		})
		
	$("#downBtn1").attr("href","/file/款項稽核頁-資料匯出為excel-資料格式.xlsx");
	$("#downBtn2").click(function() {
		  $.ajaxFileUpload({
             url:'ExcelWriteAction',
             secureuri:false,
             fileElementId:'file',//file標籤的id
             dataType: 'json',//返回資料的型別
             data:{},//一同上傳的資料
             success: function (ret) {alert("上傳成功");
		         }
	     });
	})


2、struts配置

		<!-- excel讀取 -->
		<action name="ExcelReadAction" class="com.dld.app.sales.action.ExcelOperateAction" method="excelRead">
			<result type="json" name="success">
				<param name="contentType">text/html</param>
			</result>
		</action>
		<!-- excel下載 -->
		<action name="ExcelWriteAction" class="com.dld.app.sales.action.ExcelOperateAction" method="excelWrite">
			<result type="json" name="success">
				<param name="contentType">text/html</param>
			</result>
		</action>

3、action程式碼:

package com.dld.app.sales.action;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import jxl.write.WriteException;

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

import com.alibaba.fastjson.JSONObject;
import com.dld.platform.client.ServiceClientFactory;
import com.dld.platform.data.DatasetFactory;
import com.dld.platform.data.Record;
import com.dld.platform.model.BaseModelFactory;
import com.dld.platform.model.RequestModel;
import com.dld.platform.model.ResponseModel;


public class ExcelOperateAction {

	private File[] filedata; // 檔案
	private String[] filedataFileName; // 檔名
	private String contractNum;

	/**
	 * 檔案上傳
	 * 
	 * @return
	 * @throws IOException 
	 * @throws InvalidFormatException 
	 */
	public String excelRead() throws IOException, InvalidFormatException {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setCharacterEncoding("utf-8");
		
		Map<String,Object> shopMap = new HashMap<String,Object>();
		List<Map<String,Object>> shopMapList=new ArrayList<Map<String,Object>>();
		if (this.filedata != null) {
			File excel = this.getFiledata()[0];
			Workbook workbook = WorkbookFactory.create(excel);
			// 遍歷excel頁
			for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
				Sheet sheet = workbook.getSheetAt(numSheet);
				if (sheet == null) {
					continue;
				}
				// 遍歷行
				for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
					Row row = sheet.getRow(rowNum);
					if (row != null) {
						Record record = DatasetFactory.buildRecord();
						Cell shopNo = row.getCell(0);
						record.addCell("shopNo",  getValue(shopNo));
						Cell shopName = row.getCell(1);
						record.addCell("shopName",  getValue(shopName));
						shopMapList.add(record.toMap());
					}
				}
			}
			shopMap.put("shopMapList", shopMapList);
		}
		
		RequestModel shopMapRequest=BaseModelFactory.buildRequestModel("sales_readExcelForShop",
				DatasetFactory.buildDatasetByRecord(new String[]{"shopMapStr"}, new Object[]{JSONObject.toJSONString(shopMap)}));
		ResponseModel shopMapResponse=ServiceClientFactory.getServiceClient().doRequestResponse(shopMapRequest);
		if(!shopMapResponse.isSuccess()){
			return null;
		}
		
		return null;
	}
	
	/**
	 * 檔案下載
	 * 
	 * @return
	 * @throws FileNotFoundException 
	 * @throws IOException 
	 * @throws InvalidFormatException 
	 * @throws WriteException 
	 */
	public String excelWrite() throws InvalidFormatException, IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");// 解決中文亂碼
		
		File file = new File(request.getSession().getServletContext().getRealPath("/") + "/file/款項稽核頁-資料匯出為excel-資料格式.xlsx");
		// 商戶模版
		Workbook book = WorkbookFactory.create(file);
		Sheet sheet = book.getSheetAt(0);
		Cell cell = sheet.createRow(3).createCell(1);
		cell.setCellValue("是");
		// 修改模板內容匯出新模板
		FileOutputStream out = new FileOutputStream("d:/a.xlsx");
		book.write(out);
		book.close();
		out.close();
		return null;
	}
	
	@SuppressWarnings("static-access")
	private String getValue(Cell cell) {
        if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
            // 返回布林型別的值
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
            // 返回數值型別的值
            return String.valueOf(cell.getNumericCellValue());
        } else {
            // 返回字串型別的值
            return String.valueOf(cell.getStringCellValue());
        }
    }
	
	/**
	 * 附件下載
	 * 
	 * @return
	 */
	public String downloadFile() {

		return null;
	}

	public static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		return fileName.substring(pos);
	}

	public File[] getFiledata() {
		return filedata;
	}

	public void setFiledata(File[] filedata) {
		this.filedata = filedata;
	}

	public String[] getFiledataFileName() {
		return filedataFileName;
	}

	public void setFiledataFileName(String[] filedataFileName) {
		this.filedataFileName = filedataFileName;
	}

	public String getContractNum() {
		return contractNum;
	}

	public void setContractNum(String contractNum) {
		this.contractNum = contractNum;
	}

	
}
檔案和檔名變數必須和jsp裡面的name名稱對應,struts能利用值桟進行相應map,獲取到相應資料
private File[] filedata; // 檔案
private String[] filedataFileName; // 檔名