编程准备:commons-fileupload.jar
commons-io.jar
poi.jar(解读Excel表格用)导入以上Jar包
JSP端:
- <form name="readExcel" action="readExcel.action" method="post" enctype="multipart/form-data">
- Excel文件Path: <input type="file" name="uploadFile"><br>
- <input type="submit" value="导入">
- </form>
Action端:
- package com.blog.action.excel;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- 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 com.blog.dto.ArticleTypeBean;
- import com.blog.service.excel.ReadExcelService;
- import com.blog.service.excel.impl.ReadExcelServiceImpl;
- import com.opensymphony.xwork2.ActionSupport;
- public class ReadExcelAction extends ActionSupport {
- private File uploadFile;
- private String uploadFileFileName;
- private ReadExcelService readExcelService = new ReadExcelServiceImpl();
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- public File getUploadFile() {
- return uploadFile;
- }
- public void setUploadFile(File uploadFile) {
- this.uploadFile = uploadFile;
- }
- public String getUploadFileFileName() {
- return uploadFileFileName;
- }
- public void setUploadFileFileName(String uploadFileFileName) {
- this.uploadFileFileName = uploadFileFileName;
- }
- public ReadExcelService getReadExcelService() {
- return readExcelService;
- }
- public void setReadExcelService(ReadExcelService readExcelService) {
- this.readExcelService = readExcelService;
- }
- /**
- * 把Excele表读出的数据,组装成一个List,统一导入数据库
- * @return
- */
- public String importExcelData(){
- try {
- FileInputStream fs = new FileInputStream(uploadFile);
- Workbook workbook = new HSSFWorkbook(fs);
- //讀取Excel Sheet頁
- Sheet sheet = workbook.getSheetAt(0);
- int rowNum = sheet.getLastRowNum() + 1;//行數
- //讀取每一行
- for(int i = 0 ; i < rowNum ; i++){
- ArticleTypeBean articleTypeBean = new ArticleTypeBean();
- Row row = sheet.getRow(i);//當前行
- //列數
- int cellNum = row.getLastCellNum() ;
- for(int j = 0 ; j < cellNum ; j++){
- Cell cell = row.getCell(j);
- if(j == 0 )
- articleTypeBean.setArticleTypeName(cell.getStringCellValue());
- if(j == 1)
- articleTypeBean.setArticleOrder(Integer.valueOf(((int)cell.getNumericCellValue() )));
- }
- this.readExcelService.importData(articleTypeBean);
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception exception){
- exception.printStackTrace();
- }
- return SUCCESS;
- }
- }
转载于:https://blog.51cto.com/zhangmin/581637