struts2--实现Excel上传并解析

package com.bjpn.actions;

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

import org.apache.commons.io.FileUtils;
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.struts2.ServletActionContext;

/**
 * 用户上传excel文件到服务端, 解析excel文件
 * 
 * @author zhaoj
 * 
 */
public class ParseExcelAction {

	private File excel;// 必须与表单中的name属性一致
	private String excelFileName;// 必须是name属性+FileName

	public File getExcel() {
		return excel;
	}

	public void setExcel(File excel) {
		this.excel = excel;
	}

	public String getExcelFileName() {
		return excelFileName;
	}

	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}

	public String execute() throws IOException {

		// 将客户端的文件上传到服务端
		String desPath = ServletActionContext.getServletContext().getRealPath(
				"/imags");
		File destFile = new File(desPath, excelFileName);
		FileUtils.copyFile(excel, destFile);

		// 解析excel
		// 得到一个excel文件
		HSSFWorkbook book = new HSSFWorkbook(new FileInputStream(destFile));
		// 得到第一张表
		HSSFSheet sheet = book.getSheetAt(0);
		// 遍历输出
		for (int i = 0; i <= sheet.getLastRowNum(); i++) {
			// 得到行
			HSSFRow row = sheet.getRow(i);
			for (int j = 0; j < row.getLastCellNum(); j++) {
				// 得到一行中的单元格
				HSSFCell cell = row.getCell(j);
				System.out.print(cell + "\t");
			}
			System.out.println();
		}

		return "success";
	}
}


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>











	



你可能感兴趣的:(struts)