TA的每日心情 | 衰 2021-2-2 11:21 |
---|
签到天数: 36 天 [LV.5]常住居民I
|
页面代码:
- <form name="form2" method="post" enctype="multipart/form-data" action="baseInfoAction_upload.action">
- 文件:<input type="file" name="file">
- <input type="submit" value="上传" />
- </form>
复制代码
Action代码:
- import java.io.BufferedInputStream;
- 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.poi.poifs.filesystem.POIFSFileSystem;
- import org.apache.poi.ss.usermodel.Cell;
- import com.acts.web.common.action.BaseAction;
- import com.acts.web.util.Constants;
- /**
- *@Class Name: BaseInfoAction
- *@Author: zhangZhiPeng
- *@Date: 2014-1-7
- *@Modifications:
- *@Modifier Name; Date; The Reason for Modifying
- *
- */
- @SuppressWarnings("serial")
- public class BaseInfoAction extends BaseAction{
-
- private File file; //上传的文件
- private String fileFileName; //文件名称
- private String fileContentType; //文件类型
- /**
- * 上传文件 并读取 数据保存到数据库
- * @return
- */
- @SuppressWarnings("deprecation")
- public String upload(){
- String realpath = this.getRequest().getRealPath("/file");
- if (file != null) {
- File savefile = new File(new File(realpath), fileFileName);
- if (!savefile.getParentFile().exists())
- savefile.getParentFile().mkdirs();
- try {
- FileUtils.copyFile(file, savefile);
- BufferedInputStream in = new BufferedInputStream(new FileInputStream(realpath+Constants.SF_FILE_SEPARATOR+fileFileName));
- POIFSFileSystem fs = new POIFSFileSystem(in);
- HSSFWorkbook wb = new HSSFWorkbook(fs);
- HSSFSheet sheet = wb.getSheetAt(0);
- //获取到Excel文件中的所有行数
- int rows = sheet.getPhysicalNumberOfRows();
- //遍历行
- for (int i = 0; i < rows; i++) {
- // 读取左上端单元格
- HSSFRow row = sheet.getRow(i);
- // 行不为空
- if (row != null) {
- //获取到Excel文件中的所有的列
- int cells = row.getPhysicalNumberOfCells();
- //遍历列
- for (int j = 0; j < cells; j++) {
- //获取到列的值
- HSSFCell cell = row.getCell(j);
- if (cell != null) {
- //设置单元格式
- cell.setCellType(Cell.CELL_TYPE_STRING);
- //测试输出
- System.out.println(cell.getStringCellValue());
- }
- }
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return "success";
- }
- public File getFile() {
- return file;
- }
- public void setFile(File file) {
- this.file = file;
- }
- public String getFileFileName() {
- return fileFileName;
- }
- public void setFileFileName(String fileFileName) {
- this.fileFileName = fileFileName;
- }
- public String getFileContentType() {
- return fileContentType;
- }
- public void setFileContentType(String fileContentType) {
- this.fileContentType = fileContentType;
- }
- }
复制代码
struts.xml 配置文件:
- <constant name="struts.multipart.maxSize" value="10701096"/><!-- 上传文件最大值 -->
复制代码
读取excel文件格式:
|
|