javascript学习指南_java 使用 Apache POI批量导入导出excel教程及实例

更新时间:2019-12-02    来源:apache    手机版     字体:

【www.bbyears.com--apache】

一、定义

  Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

二、所需jar包:

 


三、简单的一个读取excel的demo

1、读取文件方法

     /**
     * 读取出filePath中的所有数据信息
     * @param filePath excel文件的绝对路径
     * 
     */
    
    public static void getDataFromExcel(String filePath)
    {
        //String filePath = "E:\\\\123.xlsx";
        
        //判断是否为excel类型文件
        if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
        {
            System.out.println("文件不是excel类型");
        }
        
        FileInputStream fis =null;
        Workbook wookbook = null;
        
        try
        {
            //获取一个绝对地址的流
              fis = new FileInputStream(filePath);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
       
        try 
        {
            //2003版本的excel,用.xls结尾
            wookbook = new HSSFWorkbook(fis);//得到工作簿
             
        } 
        catch (Exception ex) 
        {
            //ex.printStackTrace();
            try
            {
                //2007版本的excel,用.xlsx结尾
                
                wookbook = new XSSFWorkbook(fis);//得到工作簿
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //得到一个工作表
        Sheet sheet = wookbook.getSheetAt(0);
        
        //获得表头
        Row rowHead = sheet.getRow(0);
        
        //判断表头是否正确
        if(rowHead.getPhysicalNumberOfCells() != 3)
        {
            System.out.println("表头的数量不对!");
        }
        
        //获得数据的总行数
        int totalRowNum = sheet.getLastRowNum();
        
        //要获得属性
        String name = "";
        int latitude = 0;
        
       //获得所有数据
        for(int i = 1 ; i <= totalRowNum ; i++)
        {
            //获得第i行对象
            Row row = sheet.getRow(i);
            
            //获得获得第i行第0列的 String类型对象
            Cell cell = row.getCell((short)0);
            name = cell.getStringCellValue().toString();
            
            //获得一个数字类型的数据
            cell = row.getCell((short)1);
            latitude = (int) cell.getNumericCellValue();
            
            System.out.println("名字:"+name+",经纬度:"+latitude);
            
        }
    }



2、测试

public static void main(String[] args) 
    {        
        getDataFromExcel("E:"+ File.separator +"123.xlsx");
    }


3、原始数据

4、结果

字:A1,经纬度:1
名字:A2,经纬度:2
名字:A3,经纬度:3
名字:A4,经纬度:4
名字:A5,经纬度:5
名字:A6,经纬度:6
名字:A7,经纬度:7
名字:A8,经纬度:8
名字:A9,经纬度:9
名字:A10,经纬度:10
名字:A11,经纬度:11


四、注意事项

1、运用多态,excel主要有.xls结尾(2003版本)和. xlsx(2007版本)两种类型结尾的文件,分别需要用HSSFWorkbook对象对.xls文件进行读取,用XSSFWorkbook对象对.xlsx文件进行读取,直接使用他们共同的父类Workbook进行初始化对象有利于代码的易用性。

2、通过流的方式初始化工作簿对象(Workbook),可以通过new XSSFWorkbook(文件绝对路径)和new XSSFWorkbook(输入流)两种方式初始化对象,但是假如我们只是通过修改.xls文件的后缀名为.xlsx,这样子当我们用new XSSFWorkbook(文件绝对路径)来读取文件的时候就会报错,因为他本身就不是一个2007版本的excel类型的文件,读取会报错;假如我们是通过流的方式的话,可以避免这种情况,我们即使你修改了文件的后缀名,我们依然在初始化的时候能获取到该对象是.xls类型文件,使用HSSFWorkbook对象进行处理,即能得出正确的结果。

五、增强版

添加了判断表头是否符合规范,允许表头对象的位置不同。进行了一定的解耦合。

    /**
     *     
     * @param cell 一个单元格的对象
     * @return 返回该单元格相应的类型的值
     */
    public static Object getRightTypeCell(Cell cell){
    
        Object object = null;
        switch(cell.getCellType())
        {
            case Cell.CELL_TYPE_STRING :
            {
                object=cell.getStringCellValue();
                break;
            }
            case Cell.CELL_TYPE_NUMERIC :
            {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                object=cell.getNumericCellValue();
                break;
            }
                
            case Cell.CELL_TYPE_FORMULA :
            {
                cell.setCellType(Cell.CELL_TYPE_NUMERIC);
                object=cell.getNumericCellValue();
                break;
            }
            
            case Cell.CELL_TYPE_BLANK :
            {
                cell.setCellType(Cell.CELL_TYPE_BLANK);
                object=cell.getStringCellValue();
                break;
            }
        }
        return object;
    }
/**
     * 读取出filePath中的所有数据信息
     * @param filePath excel文件的绝对路径
     * 
     */
    
    public static void getDataFromExcel2(String filePath)
    {
        List> list = new ArrayList>();
        //判断是否为excel类型文件
        if(!filePath.endsWith(".xls")&&!filePath.endsWith(".xlsx"))
        {
            System.out.println("文件不是excel类型");
        }
        
        FileInputStream fis =null;
        Workbook wookbook = null;
        int flag = 0;
        
        try
        {
            //获取一个绝对地址的流
              fis = new FileInputStream(filePath);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
       
        try 
        {
            //2003版本的excel,用.xls结尾
            wookbook = new HSSFWorkbook(fis);//得到工作簿
             
        } 
        catch (Exception ex) 
        {
            //ex.printStackTrace();
            try
            {
                //2007版本的excel,用.xlsx结尾
                
                wookbook = new XSSFWorkbook(filePath);//得到工作簿
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
        //得到一个工作表
        Sheet sheet = wookbook.getSheetAt(0);
        
        //获得表头
        Row rowHead = sheet.getRow(0);
        
      //根据不同的data放置不同的表头
        Map headMap = new HashMap();
        
        
        //判断表头是否合格  ------------------------这里看你有多少列
        if(rowHead.getPhysicalNumberOfCells() != 2)
        {
            System.out.println("表头列数与要导入的数据库不对应");
        }
        
        try
        {
            //----------------这里根据你的表格有多少列
            while (flag < 2)
            {
                Cell cell = rowHead.getCell(flag);
                if (getRightTypeCell(cell).toString().equals("基站名"))
                {
                    headMap.put("jizhan", flag);
                }
                if (getRightTypeCell(cell).toString().equals("经纬度"))
                {
                    headMap.put("jingweidu", flag);
                }
                flag++;
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            System.out.println("表头不合规范,请修改后重新导入");
        }
        
        
        //获得数据的总行数
        int totalRowNum = sheet.getLastRowNum();
        
        
        
        //要获得属性
        String name = "";
        double latitude = 0;
        
        if(0 == totalRowNum)
        {
            System.out.println("Excel内没有数据!");
        }
        
        Cell cell_1 = null,cell_2 = null;
        
       //获得所有数据
        for(int i = 1 ; i <= totalRowNum ; i++)
        {
            //获得第i行对象
            Row row = sheet.getRow(i);
            
            try
            {
                cell_1 = row.getCell(headMap.get("jizhan"));
                cell_2 = row.getCell(headMap.get("jingweidu"));
            } catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("获取单元格错误");
            }
            
            try
            {
                //基站
                name = (String) getRightTypeCell(cell_1);
                //经纬度
                latitude = (Double) getRightTypeCell(cell_2);
            } catch (ClassCastException e)
            {
                e.printStackTrace();
                System.out.println("数据不全是数字或全部是文字!");
            }
            System.out.println("名字:"+name+",经纬度:"+latitude);
            
        }
    }

    


用poi框架进行批量导入导出实例

批量导出:

步骤:1.导入架包:

          poi-3.0-rc4-20070503.jar、poi-contrib-3.0-rc4-20070503.jar、poi-scratchpad-3.0-rc4-20070503.jar

          2.Excel操纵类,可以根据Excel模板来生成Excel对象(模板代码)

          3.生成Excel文件提供下载

实例代码:

Excel操纵类:

package cn.test.excel;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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;
/**
 * 
 * 功能描述: Excel操纵类,可以根据Excel模板来生成Excel对象
 * 版本信息:1.0 
 * Copyright: Copyright (c) 2005
 */ public class ExcelTemplate {     private static Log logger = LogFactory.getLog(ExcelTemplate.class);     private static final String DATAS = "datas";          private HSSFWorkbook workbook;     private HSSFSheet sheet;     private HSSFRow currentRow;     private Map styles = new HashMap(); //数据行的默认样式配置     private Map confStyles = new HashMap(); //通过设置"#STYLE_XXX"来标识的样式配置     private int initrow; //数据输出起始行     private int initcol; //数据输出起始列     private int num; //index number     private int currentcol; //当前列     private int currentRowIndex; //当前行index     private int rowheight = 22; //行高     private int lastLowNum = 0;     private String cellStyle = null;          private ExcelTemplate() {     }          /**      * 使用默认模板创建ExcelTemplate对象      * @return 根据模板已初始化完成的ExcelTemplate对象      */     public static ExcelTemplate newInstance(){         return newInstance("templates/default.xls");     }     /**      * 指定模板创建ExcelTemplate对象      * @param templates 模板名称      * @return 根据模板已初始化完成的ExcelTemplate对象      */     public static ExcelTemplate newInstance(String templates){         try {             ExcelTemplate excel = new ExcelTemplate();             POIFSFileSystem fs = new POIFSFileSystem(                     Thread.currentThread().getContextClassLoader()                     .getResourceAsStream(templates));             excel.workbook = new HSSFWorkbook(fs);             excel.sheet = excel.workbook.getSheetAt(0);                          //查找配置             excel.initConfig();                          //查找其它样式配置             excel.readCellStyles();                          //删除配置行             excel.sheet.removeRow( excel.sheet.getRow(excel.initrow) );                          return excel;         } catch (Exception e) {             e.printStackTrace();             logger.trace("创建Excel对象出现异常",e);             throw new RuntimeException("创建Excel对象出现异常");         }     }               /**      * 设置特定的单元格样式,此样式可以通过在模板文件中定义"#STYLE_XX"来得到,如:      * #STYLE_1,传入的参数就是"STYLE_1"      * @param style       */     public void setCellStyle(String style){         cellStyle = style;     }          /**      * 取消特定的单元格格式,恢复默认的配置值,即DATAS所在行的值      */     public void setCellDefaultStyle(){         cellStyle = null;     }          /**      * 创建新行      * @param index 从0开始计数      */     public void createRow(int index){         //如果在当前插入数据的区域有后续行,则将其后面的行往后移动         if(lastLowNum > initrow && index > 0){             sheet.shiftRows(index + initrow ,lastLowNum + index,1,true,true);         }         currentRow = sheet.createRow(index + initrow);         currentRow.setHeight((short)rowheight);         currentRowIndex = index;         currentcol = initcol;     }          /**      * 根据传入的字符串值,在当前行上创建新列      * @param value 列的值(字符串)      */     public void createCell(String value){         HSSFCell cell = createCell();         cell.setCellType(HSSFCell.CELL_TYPE_STRING);         cell.setCellValue(value);     }          /**      * 根据传入的日期值,在当前行上创建新列      * 在这种情况下(传入日期),你可以在模板中定义对应列      * 的日期格式,这样可以灵活通过模板来控制输出的日期格式      * @param value 日期      */     public void createCell(Date value){         HSSFCell cell = createCell();         cell.setCellValue(value);     }          /**      * 创建当前行的序列号列,通常在一行的开头便会创建      * 注意要使用这个方法,你必需在创建行之前调用initPageNumber方法      */     public void createSerialNumCell(){         HSSFCell cell = createCell();         cell.setCellValue(currentRowIndex + num);     }          private HSSFCell createCell(){         HSSFCell cell = currentRow.createCell((short)currentcol++);         cell.setEncoding(HSSFCell.ENCODING_UTF_16);         HSSFCellStyle style = (HSSFCellStyle)styles.get(new Integer(cell.getCellNum()));         if(style != null){             cell.setCellStyle(style);         }                  //设置了特定格式         if(cellStyle != null){             HSSFCellStyle ts = (HSSFCellStyle)confStyles.get(cellStyle);             if(ts != null){                 cell.setCellStyle(ts);             }         }         return cell;     }          /**      * 获取当前HSSFWorkbook的实例      * @return      */     public HSSFWorkbook getWorkbook(){         return workbook;     }          /**      * 获取模板中定义的单元格样式,如果没有定义,则返回空      * @param style 模板定义的样式名称      * @return 模板定义的单元格的样式,如果没有定义则返回空      */     public HSSFCellStyle getTemplateStyle(String style){         return (HSSFCellStyle)confStyles.get(style);     }          /**      * 替换模板中的文本参数      * 参数以“#”开始      * @param props      */     public void replaceParameters(Properties props){         if(props == null || props.size() == 0){             return;         }         Set propsets = props.entrySet();         Iterator rowit = sheet.rowIterator();         while(rowit.hasNext()){             HSSFRow row = (HSSFRow)rowit.next();             if(row == null)    continue;             int cellLength = row.getLastCellNum();             for(int i=0; i


生成Excel文件并提供下载

package cn.test.web.manager;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.dao.impl.BookDaoImpl;
import cn.itcast.domain.Book;
import cn.itcast.excel.ExcelTemplate;
public class ExcelServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            //导出Excel文件,不需要返回值,因为在方法的内部已经处理完成response
            //HttpServletRequest request =ServletActionContext.getRequest();
            String chcCreateDate=request.getParameter("svrDueId");
            BookDaoImpl bd =new BookDaoImpl();
            List customers = bd.getAll();//从数据库中获取要导出的集合
            //获取模板样式,需自行创建
            ExcelTemplate template = ExcelTemplate.newInstance("cn/test/excel/export_template.xls");  
            for(int i=0; i


批量导入:

步骤:1.导入架包:

          poi-3.0-rc4-20070503.jar、poi-contrib-3.0-rc4-20070503.jar、poi-scratchpad-3.0-rc4-20070503.jar

          2.生成前台页面

          2.生出Excel工具类,将从Excel中获取的数据进行数据类型转换(模板代码)

          3.读取Excel文件批量上传

生出Excel工具类:

package com.ssh.crm.excel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
public class ExcelUtils {
    public static int getIntCellValue(HSSFRow row,int index){
        int rtn = 0;
        try {
            HSSFCell cell = row.getCell((short)index);
            rtn = (int)cell.getNumericCellValue();
        } catch (RuntimeException e) {
        }
        return rtn;
    }
    
    public static String getStringValue(HSSFRow row,int index){
        String rtn = "";
        try {
            HSSFCell cell = row.getCell((short)index);
            rtn = cell.getRichStringCellValue().getString();
        } catch (RuntimeException e) {
        }
        return rtn;
    }
}


前台使用Struts标签库实现的


    excel" required="true"/>
    


读取Excel文件批量上传

    //导入Excel文件
    protected File excel;
    //封装要上传的文件
    public File getExcel() {
        return excel;
    }
    public void setExcel(File excel) {
        this.excel = excel;
    }
    public String importExcel(){
        List success = new ArrayList();
        ActionContext tx =ActionContext.getContext();
        String successanderror="";
        if(excel != null){
            try {
                //读取excel文件分析Excel文件中的数据
                HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(excel));
                
                //读取第一页的内容
                HSSFSheet sheet = wb.getSheetAt(0);
                
                //从数据行开始读取数据
                System.out.println(sheet.getLastRowNum());
                for(int i=2; i<=sheet.getLastRowNum(); i++){
                    HSSFRow row = sheet.getRow(i);
                    Product product =new Product();
                    //名称
                    product.setProdName(ExcelUtils.getStringValue(row, 1));
                    product.setProdType(ExcelUtils.getStringValue(row, 2));
                    product.setProdBatch(ExcelUtils.getStringValue(row, 3));
                    product.setProdUnit(ExcelUtils.getStringValue(row, 4));
                    product.setProdPrice(new Double(ExcelUtils.getIntCellValue(row, 5)));
                    //System.out.println(product.getProdPrice());
                    product.setProdMemo(ExcelUtils.getStringValue(row, 6));
                    //检查用户输入是否合法
                    if(product.getProdName().equals("")){
                        throw new Exception("名称项格式不正确,请检查第"+(i+1)+"行第"+2+"列!");
                    }else if(product.getProdType().equals("")){
                        throw new Exception("型号项格式不正确,请检查第"+(i+1)+"行第"+3+"列!");
                    }else if(product.getProdBatch().equals("")){
                        throw new Exception("等级/批次项格式不正确,请检查第"+(i+1)+"行第"+4+"列!");
                    }else if(product.getProdUnit().equals("")){
                        throw new Exception("单位项格式不正确,请检查第"+(i+1)+"行第"+5+"列!");
                    }else if(product.getProdPrice()==0.0){
                        throw new Exception("单价项格式不正确,请检查第"+(i+1)+"行第"+6+"列!");
                    }else if(product.getProdMemo().equals("")){
                        throw new Exception("备注项格式不正确,请检查第"+(i+1)+"行第"+7+"列!");
                    }
                    
                    success.add(product);
                }
                successanderror=underlyingDataService.addproduct(success);
                tx.put("successList",success);
                
            } catch (Exception e) {
                successanderror=e.getMessage();
            }finally{
                tx.put("sande",successanderror);
            }
        }
        return "inputdaoru";
    }


本文来源:http://www.bbyears.com/jiaocheng/81817.html

热门标签

更多>>

本类排行